diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 734f8a0569..57b3d41224 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -236,11 +236,12 @@ fn main() -> ExitCode { } /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the -/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541) and the custom dictionary's words (#4936), in the folders +/// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply /// as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_profile_store(&mut h.session); + prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); prefs_dir::attach_pdf_preset_store(&mut h.session); prefs_dir::attach_custom_dictionary(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 7e4f245d3e..b97ee681fe 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -456,6 +456,8 @@ fn main() -> std::process::ExitCode { let mut session = Session::new(); // The profiles loaded before come back before the preferences name any of them. prefs_dir::attach_profile_store(&mut session); + // Then Edit › Color Settings, which may name one of those profiles. + prefs_dir::attach_color_settings(&mut session); // Before any plug-in loads: this launch's marker in the Launch folder next to the // preferences (none for runs without preferences), and Safe Mode. let launch_dir = prefs_path().filter(|_| prefs_enabled()).and_then(|p| Some(p.parent()?.join("Launch"))); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 8e64027031..063d9b1aa1 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -41,6 +41,14 @@ pub fn attach_profile_store(session: &mut vectorcraft_engine::Session) { } } +/// Make Edit › Color Settings kept in `Color Settings.json` the active ones (#6335), and keep them +/// there when they change. After [`attach_profile_store`]: they may name a loaded profile. +pub fn attach_color_settings(session: &mut vectorcraft_engine::Session) { + if let Some(path) = store_dir("Color Settings.json") { + session.attach_color_settings(path); + } +} + /// Install the plug-ins Install Plug-in kept in the `Plug-ins` folder (#2541), and keep the ones /// installed from now on there. pub fn attach_plugin_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index f669374465..afe256e596 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -124,7 +124,7 @@ fn bake_node(d: &mut Document, n: &Node) -> Option { if let Some(m) = crate::addons::halftone::halftone_art(d, n) { return Some(bake_pieces(d, m)); } - if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -481,7 +481,7 @@ pub type StrokeArt<'a> = &'a mut dyn FnMut(&mut Document, &PathData, FillRule, & /// without transparency or effects of its own takes `n`'s place itself. Hidden fills, strokes and /// effects are dropped. `None` for other kinds of objects. pub fn expand_leaf(d: &mut Document, n: &Node, stroke_art: StrokeArt) -> Option { - if let Some(m) = crate::revolve::expand_revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve::expand_revolve_art_in(Some(d), n).or_else(|| crate::solid_art_in(Some(d), n)) { let m = evaluate_container(Some(d), &m).unwrap_or(m); return Some(bake_pieces(d, m)); } @@ -551,7 +551,7 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { /// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to /// outline nor a geometry effect, so bending first changes nothing. pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { - if let Some(m) = crate::revolve_art(n).or_else(|| crate::solid_art(n)) { + if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { return Some(m); } if !matches!(n.kind, NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. }) { diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 82db95b5b2..ae8b7d9e90 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -83,11 +83,12 @@ pub use reshape::{ SYMBOL_ART_MAX_NODES, expand_outlined, gives_image_shape, has_gradient_copies, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, needs_outline, outline_art, outline_text, reshape, }; -pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_options, validate_revolve}; +pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in}; pub use solids::{ CLASSIC_EXTRUDE, EXTRUDE, INFLATE, ROTATE, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, - classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, three_d_meshes, three_d_meshes_of, three_d_params_as, - validate_solid, validate_three_d, validate_three_d_at, validate_three_d_params, view_options, + classic_shading, extrude_options, has_solid, inflate_options, is_three_d, solid_art, solid_art_in, three_d_meshes, three_d_meshes_in, + three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, + validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 89f3bba867..a5004ab996 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -3,11 +3,11 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, FillLayer, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{PathData, PathEl, Point, Rect, Vec2}; use vectorcraft_three_d::{Edge, Revolve}; -use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, solid_paints, union_bounds}; +use crate::solids::{Profile, Scope, is_container, members, object_profile, profile, reshape_members, resolve_for, solid_paints, union_bounds}; use crate::util::{flag, num, text}; use crate::{GeomContext, apply_geometry_with, is_geometry, merged_params}; @@ -75,7 +75,14 @@ pub fn revolve_options(p: &Value) -> Revolve { /// Validate before a command mutates the document. Loading external files is still bounded /// by the evaluator; unsupported source kinds remain unchanged when rendered. pub fn validate_revolve(n: &Node, p: &Value) -> Result<(), String> { + validate_revolve_in(None, n, p) +} + +/// [`validate_revolve`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// revolve the art they show ([`resolve_for`]), cut for Revolve whatever 3D effect `n` carries now. +pub fn validate_revolve_in(doc: Option<&Document>, n: &Node, p: &Value) -> Result<(), String> { validate_revolve_params(p)?; + let n = &*resolve_for(doc, n, "Revolve", false)?; let effects = &n.appearance.effects; // The profile is measured before the object's one Revolve, hidden or shown. let before = effects.iter().position(|e| e.id == REVOLVE).and_then(|i| effects.get(..i)).unwrap_or(effects); @@ -318,12 +325,26 @@ fn paint_of(item: &AppearanceItem) -> (Paint, f32, vectorcraft_doc::color::Blend /// Evaluated art keeps the source's identity and transparency. Each item's opacity belongs /// to its entire surface, not to each face, so overlapping faces don't accumulate alpha. pub fn revolve_art(n: &Node) -> Option { - art(n, false) + revolve_art_in(None, n) } -/// Revolve's own Expand Appearance path. The shared command and UI remain unchanged. +/// [`revolve_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone +/// or in a group, revolve the art they show ([`resolve_for`]). `None` too when that art can't be +/// resolved. +pub fn revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { + art(doc, n, false) +} + +/// [`expand_revolve_art_in`] without a document. +#[cfg(test)] pub(crate) fn expand_revolve_art(n: &Node) -> Option { - art(n, true) + expand_revolve_art_in(None, n) +} + +/// Revolve's own Expand Appearance path, with the symbols of `doc` ([`revolve_art_in`]). The shared +/// command and UI remain unchanged. +pub(crate) fn expand_revolve_art_in(doc: Option<&Document>, n: &Node) -> Option { + art(doc, n, true) } /// The surfaces [`revolve_art`] draws, as meshes ([`crate::three_d_meshes`]): with the effect on @@ -388,10 +409,11 @@ fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result Option { +fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option { if !has_revolve(n) { return None; } + let n = &*resolve_for(doc, n, "Revolve", false).ok()?; if is_container(n) { return group_art(n, expand); } @@ -1143,6 +1165,38 @@ mod tests { assert!(validate_revolve(&object, &json!({})).is_err(), "one object past the budget"); } + #[test] + fn the_art_of_symbol_instances_and_blends_shares_the_budget_of_paint_copies() { + use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; + use vectorcraft_doc::{BlendSpacing, BlendSpec, Symbol}; + let plain = member(1, 0.0); + let NodeKind::Path { path: profile, .. } = &plain.kind else { panic!("a path") }; + let faces = vectorcraft_three_d::revolve(profile, profile.bounds().unwrap(), revolve_options(&json!({}))).unwrap().len(); + let stops = MAX_PAINT_COPIES * 6 / 10 / (faces * 4) / std::mem::size_of::(); + let painted = |id: u64, x: f64| { + let stops = (0..stops).map(|i| GradientStop::new(i as f32 / stops as f32, Color::BLACK)).collect(); + let paint = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut node = (*member(id, x)).clone(); + node.appearance = Appearance::basic(paint, Paint::None, 0.0).into(); + Arc::new(node) + }; + let mut d = Document::new(500.0, 500.0); + d.symbols.push(Symbol { dynamic: false, name: "P".into(), art: painted(0, 0.0) }); + let instance = |id: u64| Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "P".into(), xf: Affine::IDENTITY })); + // One instance's art fits; two in the same place, each of whose surfaces fits alone, pass + // the budget together, as two paths would. + assert_eq!(validate_revolve_in(Some(&d), &group_with(json!({}), vec![instance(1)]), &json!({})), Ok(())); + let two = group_with(json!({}), vec![instance(1), instance(2)]); + let refused = validate_revolve_in(Some(&d), &two, &json!({})).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + assert_eq!(revolve_art_in(Some(&d), &two), None, "past the budget the source draws"); + // A blend's keys and step count together too. + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1), ..Default::default() }); + let blend = Arc::new(Node::new(NodeId(3), NodeKind::Blend { children: vec![painted(4, 0.0), painted(5, 0.0)], spec })); + let refused = validate_revolve_in(Some(&d), &group_with(json!({}), vec![blend]), &json!({})).unwrap_err(); + assert!(refused.contains("simplify the gradient"), "{refused}"); + } + #[test] fn the_fills_of_one_object_share_the_budget_of_paint_copies() { use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop}; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ab119192c4..4ac4628b17 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, Effect, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeKind, StrokeLayer}; use vectorcraft_geom::{FillRule, PathData, Rect}; use vectorcraft_three_d::{Bevel, BevelShape, Extrude, Facet, Inflate, Mesh, View}; @@ -17,6 +17,9 @@ use crate::{GeomContext, apply_geometry_with, is_geometry}; mod classic; pub use classic::{CLASSIC_EXTRUDE, SHADING_COLORS, classic_extrude_options, classic_shading}; +mod source; +pub(crate) use source::{resolve, resolve_for}; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; @@ -198,10 +201,22 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { Ok(()) } +/// The name an error gives 3D effect `id`. +pub(crate) fn label_of(id: &str) -> &'static str { + crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')) +} + /// Validate before a command changes the document; the evaluator bounds loaded files too. pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { + validate_solid_in(None, n, id, p) +} + +/// [`validate_solid`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// build from the art they show ([`resolve`]). +pub fn validate_solid_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { validate_solid_params(id, p)?; - let label = crate::effect_info(id).map_or("This effect", |e| e.label.trim_end_matches('…')); + let label = label_of(id); + let n = &*source::resolve_for(doc, n, label, id == ROTATE)?; if is_container(n) { let shapes = members(n, label)?; let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; @@ -213,14 +228,13 @@ pub fn validate_solid(n: &Node, id: &str, p: &Value) -> Result<(), String> { } /// [`profile`], or the error a command reports for object `n`: type with no outlines to build from -/// (empty, or only spaces) is a shape without anchors, and any other object is the wrong kind. +/// (empty, or only spaces) is a shape without anchors, an image is traced first, and any other +/// object is the wrong kind. pub(crate) fn object_profile(n: &Node, label: &str) -> Result<(PathData, FillRule), String> { - profile(n).ok_or_else(|| { - if matches!(n.kind, NodeKind::Text(_)) { - format!("{label} requires a shape with at least two anchors") - } else { - format!("{label} currently requires a path, compound path, type or group. Convert images and other objects to paths first.") - } + profile(n).ok_or_else(|| match n.kind { + NodeKind::Text(_) => format!("{label} requires a shape with at least two anchors"), + NodeKind::Image(_) => source::image_refusal(label), + _ => format!("{label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first."), }) } @@ -264,8 +278,10 @@ const MAX_MEMBERS: usize = 4096; const MAX_MESH_TRIANGLES: usize = 2_000_000; /// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path, -/// compound path and type in it, at any depth of its groups, each through its own geometry -/// effects and painted with its own fills and strokes. Like the effect on a group in the +/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends +/// and clipping groups), at any depth of its groups, each through its own geometry +/// effects, then those of each group it is in (on that group's members together), and painted +/// with its own fills and strokes. Like the effect on a group in the /// reference app, they turn about one shared axis (the centre of their bounds together) rather /// than each about its own. An error names what the group holds that can't become a solid. pub(crate) fn members(n: &Node, label: &str) -> Result, String> { @@ -287,18 +303,23 @@ pub(crate) fn members(n: &Node, label: &str) -> Result, String> { scopes.push(Scope { key: w.keys, opacity: c.opacity, blend: c.blend }); } if is_container(c) { + let first = w.out.len(); walk(c, opacity, &scopes, w)?; + // The group's own geometry effects reshape its members together, as it is drawn. + if let Some(shapes) = w.out.get_mut(first..) { + reshape_members(c, &c.appearance.effects, shapes); + } continue; } let Some((path, rule)) = profile(c) else { let what = match &c.kind { - NodeKind::Group { clip: true, .. } => "clipping groups", - NodeKind::Image(_) => "images", - NodeKind::SymbolInstance { .. } => "symbol instances", + NodeKind::Image(_) => return Err(source::image_refusal(label)), NodeKind::Path { clipping: true, .. } => "clipping paths", - _ => "objects other than paths, compound paths and type", + _ => "other objects", }; - return Err(format!("{label} on a group needs paths, compound paths and type: release or expand its {what} first.")); + return Err(format!( + "{label} on a group needs paths, compound paths, type, groups, clipping groups, blends and symbol instances: release or expand its {what} first." + )); }; if w.out.len() >= MAX_MEMBERS { return Err(format!("{label} on a group takes at most {MAX_MEMBERS} objects")); @@ -319,7 +340,12 @@ pub(crate) fn members(n: &Node, label: &str) -> Result, String> { /// before a command changes the document: Revolve by [`crate::validate_revolve`], the others by /// [`validate_solid`]. pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { - if id == crate::REVOLVE { crate::validate_revolve(n, p) } else { validate_solid(n, id, p) } + validate_three_d_in(None, n, id, p) +} + +/// [`validate_three_d`] with the symbols of `doc` ([`validate_solid_in`]). +pub fn validate_three_d_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value) -> Result<(), String> { + if id == crate::REVOLVE { crate::revolve::validate_revolve_in(doc, n, p) } else { validate_solid_in(doc, n, id, p) } } /// [`validate_three_d`] for an effect at `(item, index)`, index `index` of the effects of @@ -328,10 +354,18 @@ pub fn validate_three_d(n: &Node, id: &str, p: &Value) -> Result<(), String> { /// item's geometry effects before it, together with the object's other items that carry a Revolve. /// A group's or layer's fills and strokes take no 3D effect: only the group's own effect draws. pub fn validate_three_d_at(n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { + validate_three_d_at_in(None, n, id, p, at) +} + +/// [`validate_three_d_at`] with the symbols of `doc` ([`validate_solid_in`]). A symbol instance, a +/// blend and a clipping group take a 3D effect as groups do: on the object itself. +pub fn validate_three_d_at_in(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: Option<(usize, usize)>) -> Result<(), String> { match at { - Some(_) if is_container(n) => Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()), + Some(_) if is_container(n) || source::resolves(n) => { + Err("A 3D effect on a group or layer goes on the group itself, not on its fill or stroke".into()) + } Some((item, index)) if id == crate::REVOLVE => crate::revolve::validate_item_revolve(n, p, item, index), - _ => validate_three_d(n, id, p), + _ => validate_three_d_in(doc, n, id, p), } } @@ -535,9 +569,17 @@ fn geometry(path: &PathData, fx: &[Effect], ctx: &GeomContext) -> PathData { /// On a group or layer the effect builds a solid from each path, compound path and type in it, /// all turned about one shared axis ([`members`]). pub fn solid_art(n: &Node) -> Option { + solid_art_in(None, n) +} + +/// [`solid_art`] with the symbols of `doc`: a symbol instance, a blend and a clipping group, alone +/// or in a group, build from the art they show ([`resolve`]). `None` too when that art can't be +/// resolved. +pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option { if !has_solid(n) { return None; } + let n = &*resolve(doc, n, "").ok()?; if is_container(n) { return group_solid_art(n); } @@ -689,28 +731,44 @@ fn meshes_for(fx: &Effect, shapes: &[Profile], total: &mut usize, limit: usize) /// such effect, its solids can't be built, none has a triangle, or together they have more than /// [`MAX_MESH_TRIANGLES`]. pub fn three_d_meshes(n: &Node) -> Result, String> { - meshes_within(n, &mut 0, MAX_MESH_TRIANGLES) + three_d_meshes_in(None, n) +} + +/// [`three_d_meshes`] with the symbols of `doc`: a symbol instance, a blend and a clipping group +/// build from the art they show ([`resolve`]). +pub fn three_d_meshes_in(doc: Option<&Document>, n: &Node) -> Result, String> { + meshes_within(doc, n, &mut 0, MAX_MESH_TRIANGLES) } /// The meshes of every object in `nodes` ([`three_d_meshes`]), in order, as one 3D asset exports /// them: the objects share one budget of [`MAX_MESH_TRIANGLES`]. pub fn three_d_meshes_of<'a>(nodes: impl IntoIterator) -> Result, String> { - meshes_of_within(nodes, MAX_MESH_TRIANGLES) + three_d_meshes_of_in(None, nodes) } -/// [`three_d_meshes_of`] with a budget of `limit` triangles. -fn meshes_of_within<'a>(nodes: impl IntoIterator, limit: usize) -> Result, String> { +/// [`three_d_meshes_of`] with the symbols of `doc` ([`three_d_meshes_in`]). +pub fn three_d_meshes_of_in<'a>(doc: Option<&Document>, nodes: impl IntoIterator) -> Result, String> { + meshes_of_within(doc, nodes, MAX_MESH_TRIANGLES) +} + +/// [`three_d_meshes_of_in`] with a budget of `limit` triangles. +fn meshes_of_within<'a>(doc: Option<&Document>, nodes: impl IntoIterator, limit: usize) -> Result, String> { let mut total = 0usize; let mut out = vec![]; for n in nodes { - out.extend(meshes_within(n, &mut total, limit)?); + out.extend(meshes_within(doc, n, &mut total, limit)?); } Ok(out) } -/// [`three_d_meshes`], with the triangles of every solid added to `total` as it is built and an +/// [`three_d_meshes_in`], with the triangles of every solid added to `total` as it is built and an /// error as soon as `total` passes `limit`. -fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result, String> { +fn meshes_within(doc: Option<&Document>, n: &Node, total: &mut usize, limit: usize) -> Result, String> { + if !crate::has_revolve(n) && !has_solid(n) { + return Err("the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)".into()); + } + let label = n.appearance.effects.iter().find(|e| e.visible && is_three_d(&e.id)).map_or("This effect", |e| label_of(&e.id)); + let n = &*resolve(doc, n, label)?; let meshes = if crate::has_revolve(n) { crate::revolve::revolve_meshes(n, total, limit)? } else if !has_solid(n) { @@ -722,7 +780,7 @@ fn meshes_within(n: &Node, total: &mut usize, limit: usize) -> Result String { + format!("{label} can't build a solid from an image: trace it first with Object › Image Trace › Make.") +} + +/// Is `n` a symbol instance, a blend or a clipping group or layer? +pub(crate) fn resolves(n: &Node) -> bool { + matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Blend { .. }) || n.clips() +} + +/// Is `n`, or a visible member of `n` at any depth of its groups and layers, one [`resolves`] takes? +fn needs(n: &Node) -> bool { + let mut stack = vec![n]; + while let Some(n) = stack.pop() { + if resolves(n) { + return true; + } + if is_container(n) { + stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| &**c)); + } + } + false +} + +/// `n` as a 3D effect builds from it: unchanged when neither it nor a visible member of its groups +/// is a symbol instance, a blend or a clipping group, otherwise a group with `n`'s id, appearance +/// and transparency holding that art (a symbol instance's symbol art from `doc`). An error names +/// what can't be resolved: an image, a missing symbol, art nested or numbering past the limits, or +/// a clipping path too complex to cut the art with. `label` is the effect's name. The art is cut +/// for the solid effect `n` carries ([`resolve_for`]). +pub(crate) fn resolve<'a>(doc: Option<&Document>, n: &'a Node, label: &str) -> Result, String> { + let every_fill = super::solid(&n.appearance.effects).is_some_and(|(_, fx)| fx.id == super::ROTATE); + resolve_for(doc, n, label, every_fill) +} + +/// [`resolve`] for the 3D effect that builds from `n`: `every_fill` for Rotate, which turns every +/// fill, so each fill a clipping path cuts keeps its own place among the strokes. Otherwise the +/// effect builds from the top fill, and the fills cut go together in the top fill's place. +pub(crate) fn resolve_for<'a>(doc: Option<&Document>, n: &'a Node, label: &str, every_fill: bool) -> Result, String> { + if !needs(n) { + return Ok(Cow::Borrowed(n)); + } + let mut r = Resolver { doc, label, every_fill, leaves: 0, work: 0, shown: None }; + let children = r.content(n, 0); + #[cfg(test)] + WORK.with(|w| w.set(r.work)); + let mut out = n.clone(); + out.kind = NodeKind::Group { children: children?, clip: false }; + Ok(Cow::Owned(out)) +} + +#[cfg(test)] +thread_local! { + /// The objects the last [`resolve`] on this thread visited or made ([`Resolver::work`]). + pub(super) static WORK: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +struct Resolver<'a> { + doc: Option<&'a Document>, + label: &'a str, + /// Does each fill a clipping path cuts become a piece of its own ([`resolve_for`])? + every_fill: bool, + /// The objects other than groups and layers kept so far, counted against [`MAX_MEMBERS`]. + leaves: usize, + /// The objects visited or made so far, counted against [`MAX_WORK`]. + work: usize, + /// Inside clipping groups, the box of what their clipping paths show together. + shown: Option, +} + +impl Resolver<'_> { + /// Count `steps` more objects visited or made, or an error past [`MAX_WORK`]. + fn spend(&mut self, steps: usize) -> Result<(), String> { + self.work = self.work.saturating_add(steps); + if self.work > MAX_WORK { + return Err(self.too_much_work()); + } + Ok(()) + } + + fn too_much_work(&self) -> String { + format!("{} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects", self.label) + } + + /// `f` run on the art of `c`. The effects of an object or group can move its art into a clip, + /// so inside one with effects no image is left out for lying outside the clip ([`Self::shown`]). + fn inside(&mut self, c: &Node, f: impl FnOnce(&mut Self) -> Result) -> Result { + let outer = self.shown; + if has_effects(c) { + self.shown = None; + } + let out = f(self); + self.shown = outer; + out + } + + /// The art `n`, a symbol instance, a blend, a clipping group or layer, or a group holding one, + /// shows, as the members of a plain group. + fn content(&mut self, n: &Node, depth: usize) -> Result>, String> { + let label = self.label; + if depth > MAX_DEPTH { + return Err(self.too_deep()); + } + self.spend(1)?; + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } => { + // Counted before the art is placed, so a symbol past the limit is never copied. + let held = self.doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)).map_or(0, |s| s.art.count_with_masks()); + if self.work.saturating_add(held) > MAX_WORK { + return Err(self.too_much_work()); + } + let art = crate::outline_object(self.doc, n).ok_or_else(|| { + format!("{label} can't build a solid from the instance of symbol \"{symbol}\": the symbol's art isn't available") + })?; + Ok(self.list(kids(&art), depth + 1)?.0) + } + NodeKind::Blend { children, spec } => { + // Counted before the steps are made, so a blend past the limit is never expanded. + let made = vectorcraft_doc::blend::blend_steps(children, spec).into_iter().fold(children.len(), usize::saturating_add); + if self.leaves.saturating_add(made) > MAX_MEMBERS { + return Err(self.too_many()); + } + self.spend(made)?; + let steps: Vec> = crate::expand_live(self.doc, n).into_iter().map(Arc::new).collect(); + Ok(self.list(&steps, depth + 1)?.0) + } + _ if n.clips() => { + let Some((first, rest)) = kids(n).split_first() else { return Ok(vec![]) }; + if clip_nested_past(first, MAX_DEPTH.saturating_sub(depth)) { + return Err(self.too_deep()); + } + let clip = clip_area(first); + // An image wholly outside every clip around it shows nothing and is left out. + let outer = self.shown; + let here = clip.0.bounds().unwrap_or(Rect::ZERO); + self.shown = Some(outer.map_or(here, |o| o.intersect(here))); + let listed = self.list(rest, depth + 1); + self.shown = outer; + let (inner, _) = listed?; + let mut out = vec![]; + for c in &inner { + if let Some(c) = self.clipped(c, &clip, depth + 1)? { + out.push(Arc::new(c)); + } + } + Ok(out) + } + _ => Ok(self.list(kids(n), depth + 1)?.0), + } + } + + /// The visible members of `children` as plain art: images refused, guides left out, symbol + /// instances, blends and clipping groups resolved into groups with their transparency and + /// geometry effects, groups holding them rebuilt. Also whether any member changed: a group + /// whose members did not is kept as it is. Each object is visited once. + fn list(&mut self, children: &[Arc], depth: usize) -> Result<(Vec>, bool), String> { + let mut out = Vec::with_capacity(children.len()); + let mut changed = false; + for c in children { + self.spend(1)?; + if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + continue; + } + if matches!(c.kind, NodeKind::Image(_)) { + // Only an image with no effects or fills and strokes of its own is measured by its + // frame; any other one may draw inside the clip. + let plain = !has_effects(c) && c.appearance.items.iter().all(|i| !i.visible()); + let hidden = plain && self.shown.is_some_and(|k| c.visual_bounds().is_none_or(|b| b.intersect(k).area() <= 0.0)); + if hidden { + changed = true; + continue; + } + return Err(image_refusal(self.label)); + } + if resolves(c) { + let kids = self.inside(c, |r| r.content(c, depth))?; + out.push(Arc::new(with_effects(wrap(c, kids), c))); + changed = true; + continue; + } + if is_container(c) { + // At the depth limit a group is kept, and not walked further, only when it holds no + // group with members and nothing in it needs resolving. + if depth >= MAX_DEPTH { + if nested_past(c, 1) || needs(c) { + return Err(self.too_deep()); + } + out.push(c.clone()); + continue; + } + let (kids, inner) = self.inside(c, |r| r.list(kids(c), depth + 1))?; + if inner { + out.push(Arc::new(with_effects(wrap(c, kids), c))); + changed = true; + } else { + out.push(c.clone()); + } + continue; + } + self.leaves += 1; + if self.leaves > MAX_MEMBERS { + return Err(self.too_many()); + } + out.push(c.clone()); + } + Ok((out, changed)) + } + + fn too_complex(&self) -> String { + format!("{}: the clipping path is too complex to cut the art with", self.label) + } + + fn too_many(&self) -> String { + format!("{} takes at most {MAX_MEMBERS} objects", self.label) + } + + fn too_deep(&self) -> String { + format!("{} can't build solids from art nested more than {MAX_DEPTH} levels deep", self.label) + } + + /// `n`, plain art inside a clipping group, cut to `clip`: each shape's fills as its area inside + /// the clip and each stroke as the part of its outline inside it, filled in the stroke's paint, + /// after the geometry effects of the shape and of the groups it is in; hidden objects and guides + /// left out. `None` when nothing of it is inside. Objects that build no solid stay as they are. + fn clipped(&mut self, n: &Node, clip: &(PathData, FillRule), depth: usize) -> Result, String> { + if depth > MAX_DEPTH { + return Err(self.too_deep()); + } + self.spend(1)?; + if is_container(n) { + let mut kids = vec![]; + if n.appearance.effects.iter().any(|e| e.visible && is_geometry(&e.id)) { + // The group's geometry effects reshape its members together before the clip cuts + // them, as they are drawn: each member becomes its reshaped outline. + if nested_past(n, MAX_DEPTH.saturating_sub(depth)) { + return Err(self.too_deep()); + } + let mut shapes = members(n, self.label)?; + reshape_members(n, &n.appearance.effects, &mut shapes); + let mut cut = vec![]; + for s in shapes { + if let Some(c) = self.clipped(&shape(n, s.path, s.rule, s.items), clip, depth + 1)? { + cut.push((s.scopes, c)); + } + } + kids = nest(n, cut, 0); + } else { + for c in n.children().into_iter().flatten() { + if !c.visible || matches!(c.kind, NodeKind::Path { guide: true, .. }) { + continue; + } + if let Some(c) = self.clipped(c, clip, depth + 1)? { + kids.push(Arc::new(c)); + } + } + } + return Ok((!kids.is_empty()).then(|| wrap(n, kids))); + } + let Some((path, rule)) = profile(n) else { return Ok(Some(n.clone())) }; + let items = solid_paints(n); + // The fills' piece goes where the top fill is, the one Extrude & Bevel and Inflate build + // their solid from, so the strokes above and below it keep their places. Rotate turns + // every fill, so each fill is a piece in its own place. + let top_fill = items.iter().rposition(|i| matches!(i, AppearanceItem::Fill(_))); + let fill_pieces = + if self.every_fill { items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).count() } else { usize::from(top_fill.is_some()) }; + // Each cut makes a piece, counted before it is made: the shape was counted once already. + let made = fill_pieces + items.iter().filter(|i| matches!(i, AppearanceItem::Stroke(_))).count(); + self.spend(made)?; + self.leaves = self.leaves.saturating_add(made.saturating_sub(1)); + if self.leaves > MAX_MEMBERS { + return Err(self.too_many()); + } + let path = geometry(&path, &n.appearance.effects, &GeomContext::of(n)); + let cut = |area: &PathData, rule: FillRule| -> Result, String> { + let inside = + po::try_boolean(area, rule, &clip.0, clip.1, po::BoolOp::Intersect, po::DEFAULT_PRECISION).map_err(|_| self.too_complex())?; + Ok(inside.bounds().is_some().then_some(inside)) + }; + let fills: Vec = items.iter().filter(|i| matches!(i, AppearanceItem::Fill(_))).cloned().collect(); + // Every fill paints the same area: it is cut once. + let mut fill_area: Option> = None; + let mut pieces = vec![]; + for (k, item) in items.iter().enumerate() { + match item { + AppearanceItem::Fill(_) if self.every_fill || Some(k) == top_fill => { + let area = match &fill_area { + Some(area) => area.clone(), + None => fill_area.insert(cut(&path, rule)?).clone(), + }; + if let Some(area) = area { + let painted = if self.every_fill { vec![item.clone()] } else { fills.clone() }; + pieces.push(Arc::new(shape(n, area, FillRule::NonZero, painted))); + } + } + AppearanceItem::Fill(_) => {} + AppearanceItem::Stroke(s) => { + let (outline, outline_rule) = region(&path, rule, item); + if let Some(area) = cut(&outline, outline_rule)? { + let mut fill = FillLayer::new(s.paint.clone()); + fill.opacity = s.opacity; + fill.blend = s.blend; + pieces.push(Arc::new(shape(n, area, FillRule::NonZero, vec![AppearanceItem::Fill(fill)]))); + } + } + } + } + Ok((!pieces.is_empty()).then(|| wrap(n, pieces))) + } +} + +/// The area clipping path `first` keeps, as the renderer clips by it ([`crate::clip_outline`]): a +/// nested clipping group's own clipping path, the union of a group's members. Empty when it keeps +/// nothing. +fn clip_area(first: &Node) -> (PathData, FillRule) { + crate::clip_outline(first).map_or_else(|| (PathData::default(), FillRule::NonZero), |(bp, rule)| (PathData::from_bezpath(&bp), rule)) +} + +/// `pieces`, each with the [`Scope`]s of the groups it was in, back in groups of `n`'s id with +/// those groups' opacity and blending mode: consecutive pieces sharing the scope at `level` go into +/// one group, so its transparency applies to them together. `level` stays below the nesting the +/// pieces came from ([`nested_past`]). +fn nest(n: &Node, pieces: Vec<(Vec, Node)>, level: usize) -> Vec> { + let mut out = vec![]; + let mut run: Vec<(Vec, Node)> = vec![]; + let mut key = None; + let close = |run: &mut Vec<(Vec, Node)>, scope: Option, out: &mut Vec>| { + let Some(scope) = scope else { return }; + let mut g = Node::group(n.id, nest(n, std::mem::take(run), level + 1)); + g.opacity = scope.opacity; + g.blend = scope.blend; + out.push(Arc::new(g)); + }; + for (scopes, piece) in pieces { + let here = scopes.get(level).copied(); + if here.map(|s| s.key) != key.map(|s: Scope| s.key) { + close(&mut run, key, &mut out); + key = here; + } + match here { + Some(_) => run.push((scopes, piece)), + None => out.push(Arc::new(piece)), + } + } + close(&mut run, key, &mut out); + out +} + +/// Does `n` carry a visible effect? +fn has_effects(n: &Node) -> bool { + n.appearance.effects.iter().any(|e| e.visible) +} + +/// Does the group `n` hold shown objects nested more than `levels` deep in groups and layers? +/// Only the members [`members`] walks are followed: hidden members are skipped, and the paths of +/// a compound path are one shape. Walked without recursion. +fn nested_past(n: &Node, levels: usize) -> bool { + let mut stack = vec![(n, 0usize)]; + while let Some((n, level)) = stack.pop() { + if level > levels { + return true; + } + if level == 0 || is_container(n) { + stack.extend(kids(n).iter().filter(|c| c.visible).map(|c| (&**c, level + 1))); + } + } + false +} + +/// Does the clipping path `n` reach objects nested more than `levels` deep along the members that +/// [`Node::clip_shapes`] visits: the first member of a clipping group, the shown members of other +/// groups and layers (not a group's shaper), and every member of a live object. Walked without +/// recursion. +fn clip_nested_past(n: &Node, levels: usize) -> bool { + let mut stack = vec![(n, 0usize)]; + while let Some((n, level)) = stack.pop() { + if level > levels { + return true; + } + match &n.kind { + NodeKind::Group { children, clip: true } => stack.extend(children.first().map(|c| (&**c, level + 1))), + NodeKind::Group { children, .. } | NodeKind::Layer { children, .. } => { + let skip = usize::from(n.extras().shaper.is_some()); + stack.extend(children.iter().skip(skip).filter(|c| c.visible).map(|c| (&**c, level + 1))); + } + NodeKind::Compound { .. } | NodeKind::SymbolInstance { .. } => {} + _ => stack.extend(kids(n).iter().map(|c| (&**c, level + 1))), + } + } + false +} + +/// The members of `n`, none for an object without members. +fn kids(n: &Node) -> &[Arc] { + n.children().map_or(&[], Vec::as_slice) +} + +/// A path of `n`'s id on `path`, painted by `items` under `rule`. +fn shape(n: &Node, path: PathData, rule: FillRule, items: Vec) -> Node { + let mut piece = Node::path(n.id, path, Appearance { items, ..Default::default() }); + if let NodeKind::Path { rule: r, .. } = &mut piece.kind { + *r = rule; + } + piece +} + +/// A plain group of `children` with `n`'s id, visibility, opacity and blending mode. +fn wrap(n: &Node, children: Vec>) -> Node { + let mut g = Node::group(n.id, children); + g.name = n.name.clone(); + g.opacity = n.opacity; + g.blend = n.blend; + g +} + +/// `g`, the group `n` was resolved into, with `n`'s appearance: a 3D effect's group reshapes its +/// members with its geometry effects ([`members`]), which read its stroke as they do when `n` is +/// drawn. A group's own fills and strokes build no solid. +fn with_effects(mut g: Node, n: &Node) -> Node { + g.appearance = n.appearance.clone(); + g +} diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 475868d6f8..7273a44b22 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -591,13 +591,14 @@ fn a_3d_effect_on_a_group_turns_every_member_about_one_shared_axis() { // Hidden members and guides are left out; a group holding what can't become a solid is // refused with what to do. let mut g = group(EXTRUDE, json!({})); - let mut clip = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]); - clip.kind = NodeKind::Group { children: clip.children().unwrap().clone(), clip: true }; + let mut woven = Node::group(NodeId(5), vec![Arc::new(square_at(6, 0.0, RED))]); + woven.kind = NodeKind::Intertwine { children: woven.children().unwrap().clone() }; if let NodeKind::Group { children, .. } = &mut g.kind { - children.push(Arc::new(clip)); + children.push(Arc::new(woven)); } let err = validate_solid(&g, EXTRUDE, &json!({})).unwrap_err(); - assert!(err.contains("clipping groups"), "{err}"); + assert!(err.contains("release or expand its other objects"), "{err}"); + assert!(err.contains("type, groups, clipping groups, blends and symbol instances"), "{err}"); assert!(solid_art(&g).is_none(), "drawn as the group it is"); } diff --git a/crates/effects/src/solids/tests_mesh.rs b/crates/effects/src/solids/tests_mesh.rs index 7b223f389b..1ae347c978 100644 --- a/crates/effects/src/solids/tests_mesh.rs +++ b/crates/effects/src/solids/tests_mesh.rs @@ -79,7 +79,7 @@ fn revolve_stops_at_the_first_mesh_past_the_budget() { assert!(whole.as_ref().is_err_and(|e| !e.contains("to export")), "the stroke's own error: {whole:?}"); // With room for less than the fill's mesh, the stroke's is never built. let mut total = 0; - let capped = meshes_within(&n, &mut total, triangles - 1); + let capped = meshes_within(None, &n, &mut total, triangles - 1); assert!(capped.as_ref().is_err_and(|e| e.contains("too complex to export")), "{capped:?}"); assert_eq!(total, triangles); } @@ -92,10 +92,10 @@ fn the_objects_of_one_asset_share_one_triangle_budget() { b.appearance.effects.push(fx(EXTRUDE, json!({}))); let triangles = |n: &Node| three_d_meshes(n).unwrap().iter().map(|m| m.mesh.triangles.len()).sum::(); let (ta, tb) = (triangles(&a), triangles(&b)); - assert!(meshes_of_within([&a], ta).is_ok()); - assert!(meshes_of_within([&b], tb).is_ok()); - assert!(meshes_of_within([&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export"))); - assert_eq!(meshes_of_within([&a, &b], ta + tb).map(|m| m.len()), Ok(4)); + assert!(meshes_of_within(None, [&a], ta).is_ok()); + assert!(meshes_of_within(None, [&b], tb).is_ok()); + assert!(meshes_of_within(None, [&a, &b], ta.max(tb)).is_err_and(|e| e.contains("too complex to export"))); + assert_eq!(meshes_of_within(None, [&a, &b], ta + tb).map(|m| m.len()), Ok(4)); assert_eq!(three_d_meshes_of([&a, &b]).map(|m| m.len()), Ok(4)); } diff --git a/crates/effects/src/solids/tests_sources.rs b/crates/effects/src/solids/tests_sources.rs new file mode 100644 index 0000000000..35e89e61f0 --- /dev/null +++ b/crates/effects/src/solids/tests_sources.rs @@ -0,0 +1,487 @@ +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{AppearanceItem, BlendSpacing, BlendSpec, Document, FillLayer, ImageObject, NodeId, StrokeLayer, Symbol}; +use vectorcraft_geom::{Affine, shapes}; + +use super::*; + +const TYPES: [&str; 5] = [EXTRUDE, CLASSIC_EXTRUDE, INFLATE, ROTATE, crate::REVOLVE]; + +/// Rotate facing the viewer: the art drawn where it is. +fn front() -> Value { + json!({"rotationX": 0.0, "rotationY": 0.0, "rotationZ": 0.0}) +} + +fn rect(id: u64, x0: f64, y0: f64, x1: f64, y1: f64, stroke: f64) -> Node { + let path = shapes::rectangle(Rect::new(x0, y0, x1, y1)); + let stroke_paint = if stroke > 0.0 { Paint::solid(Color::BLACK) } else { Paint::None }; + Node::path(NodeId(id), path, Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), stroke_paint, stroke)) +} + +fn with(mut n: Node, id: &str, params: Value) -> Node { + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +fn art(d: &Document, n: &Node, id: &str) -> Option { + if id == crate::REVOLVE { crate::revolve_art_in(Some(d), n) } else { solid_art_in(Some(d), n) } +} + +fn bounds(n: &Node) -> Rect { + n.visual_bounds().unwrap() +} + +fn close(a: Rect, b: Rect, tolerance: f64) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() <= tolerance) +} + +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: Arc::new(rect(0, 0.0, 0.0, 100.0, 100.0, 2.0)) }); + d +} + +/// A rectangular clipping path covering `clip`. +fn clipping_path(id: u64, clip: Rect) -> Node { + let mut path = Node::path(NodeId(id), shapes::rectangle(clip), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut path.kind { + *clipping = true; + } + path +} + +/// A clipping group: `art` inside a rectangular clipping path covering `clip`. +fn clip_group(id: u64, clip: Rect, art: Node) -> Node { + Node::new(NodeId(id), NodeKind::Group { children: vec![Arc::new(clipping_path(id + 1, clip)), Arc::new(art)], clip: true }) +} + +fn blend(id: u64, steps: u32) -> Node { + let keys = vec![Arc::new(rect(id + 1, 100.0, 100.0, 140.0, 140.0, 0.0)), Arc::new(rect(id + 2, 300.0, 120.0, 360.0, 180.0, 0.0))]; + let spec = BlendSpec { spacing: BlendSpacing::Steps(steps), ..Default::default() }; + Node::new(NodeId(id), NodeKind::Blend { children: keys, spec: Box::new(spec) }) +} + +fn instance(id: u64, symbol: &str, xf: Affine) -> Node { + Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: symbol.into(), xf }) +} + +fn image(id: u64) -> Node { + Node::new( + NodeId(id), + NodeKind::Image(Box::new(ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ) +} + +fn sources() -> [(&'static str, Node); 3] { + [ + ("clipping group", clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0))), + ("blend", blend(20, 3)), + ("symbol instance", instance(30, "Box", Affine::translate((300.0, 0.0)))), + ] +} + +#[test] +fn every_three_d_type_builds_clipping_groups_blends_and_symbol_instances_alone_and_in_a_group() { + let d = document(); + for (what, source) in sources() { + for id in TYPES { + let n = with(source.clone(), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id} on a {what}"); + assert!(art(&d, &n, id).is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws"); + assert!(three_d_meshes_in(Some(&d), &n).is_ok_and(|m| !m.is_empty()), "{id} on a {what} exports"); + let g = with(Node::group(NodeId(90), vec![Arc::new(source.clone()), Arc::new(rect(91, 600.0, 600.0, 650.0, 650.0, 0.0))]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding a {what}"); + assert!(art(&d, &g, id).is_some(), "{id} on a group holding a {what} draws"); + assert!(three_d_meshes_in(Some(&d), &g).is_ok_and(|m| !m.is_empty()), "{id} on a group holding a {what} exports"); + } + } +} + +#[test] +fn a_clipping_groups_solid_is_built_from_its_art_inside_the_clip() { + let d = document(); + let clip = Rect::new(100.0, 100.0, 150.0, 200.0); + let fill_only = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0)), ROTATE, front()); + let cut = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &fill_only).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // The stroke is cut to the clip too: nothing reaches past it but the faces' seams. + let stroked = with(clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 8.0)), EXTRUDE, front()); + let b = bounds(&solid_art_in(Some(&d), &stroked).unwrap()); + let outside = b.x0 < clip.x0 - 1.0 || b.x1 > clip.x1 + 1.0; + let extruded = + bounds(&solid_art(&with(Node::group(NodeId(10), vec![Arc::new(rect(12, 100.0, 100.0, 150.0, 200.0, 0.0))]), EXTRUDE, front())).unwrap()); + assert!(!outside && close(b, extruded, 1.0), "{b:?} within {clip:?}"); + // A clip inside a clip keeps what both show. + let nested = + with(clip_group(40, Rect::new(120.0, 0.0, 400.0, 400.0), clip_group(10, clip, rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))), ROTATE, front()); + let both = with(Node::group(NodeId(10), vec![Arc::new(rect(12, 120.0, 100.0, 150.0, 200.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &nested).unwrap()), bounds(&solid_art(&both).unwrap()), 0.01)); + // A clipping group used as the clipping path clips by its own clipping path, not by its art. + let mask = Arc::new(clip_group(70, clip, rect(72, 100.0, 100.0, 110.0, 110.0, 0.0))); + let by_mask = with( + Node::new(NodeId(10), NodeKind::Group { children: vec![mask, Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }), + ROTATE, + front(), + ); + assert!(close(bounds(&solid_art_in(Some(&d), &by_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // A stroke between two fills keeps its place below the top fill's solid. + let mut layered = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0); + layered.appearance = Appearance { + items: vec![ + AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))), + AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), 6.0)), + AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)))), + ], + ..Default::default() + } + .into(); + let colors = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), EXTRUDE, json!({}))).unwrap().iter().map(|m| m.color).collect::>(); + let plain = colors(&Node::group(NodeId(10), vec![Arc::new(layered.clone())])); + assert_eq!(plain.len(), 2, "the stroke's solid and the top fill's"); + assert_eq!(colors(&clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered.clone())), plain); + // Rotate turns both fills and the stroke, each in its own place. + let turned = |n: &Node| three_d_meshes_in(Some(&d), &with(n.clone(), ROTATE, front())).unwrap().iter().map(|m| m.color).collect::>(); + let plain = turned(&Node::group(NodeId(10), vec![Arc::new(layered.clone())])); + assert_eq!(plain.len(), 3, "both fills' surfaces and the stroke's"); + let clipped = clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), layered); + assert_eq!(turned(&clipped), plain); + assert_eq!(validate_three_d_in(Some(&d), &clipped, ROTATE, &json!({})), Ok(())); + // Each fill Rotate turns counts against the limit on objects; another effect takes the top + // fill only, whatever 3D effect the object carries before it changes type. + let mut many = rect(12, 100.0, 100.0, 150.0, 200.0, 0.0); + many.appearance = + Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK))); MAX_MEMBERS + 1], ..Default::default() }.into(); + let rotated = with(clip_group(10, Rect::new(0.0, 0.0, 400.0, 400.0), many), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &rotated, ROTATE, &json!({})).is_err_and(|e| e.contains("takes at most"))); + for id in [EXTRUDE, crate::REVOLVE] { + assert_eq!(validate_three_d_in(Some(&d), &rotated, id, &json!({})), Ok(()), "Rotate changed to {id}"); + } + // Art nested past the limit inside a clipping group is refused, not followed to any depth. + let mut deep = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0); + for i in 0..200 { + deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]); + } + let n = with(clip_group(10, clip, deep.clone()), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep"))); + assert!(solid_art_in(Some(&d), &n).is_none()); + // So is a clipping path nested past the limit, and a symbol's art nested past it. + let by_deep = + Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(deep.clone()), Arc::new(rect(12, 0.0, 0.0, 10.0, 10.0, 0.0))], clip: true }); + let mut deep_symbol = d.clone(); + deep_symbol.symbols.push(Symbol { dynamic: false, name: "Deep".into(), art: Arc::new(deep) }); + for n in [with(by_deep, ROTATE, front()), with(instance(30, "Deep", Affine::IDENTITY), ROTATE, front())] { + assert!(validate_three_d_in(Some(&deep_symbol), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep")), "{:?}", n.id); + assert!(three_d_meshes_in(Some(&deep_symbol), &n).is_err()); + } + // A compound path counts as one shape at the depth limit: a symbol's art nested as deep as a + // path may be also takes a compound path there. + let square = rect(80, 0.0, 0.0, 10.0, 10.0, 0.0); + let mut compound = + Node::new(NodeId(81), NodeKind::Compound { children: vec![Arc::new(square.clone())], rule: vectorcraft_geom::FillRule::NonZero }); + compound.appearance = square.appearance.clone(); + let mut seen = vec![]; + for levels in 60..70 { + let ok = |leaf: &Node| { + let mut art = leaf.clone(); + for i in 0..levels { + art = Node::group(NodeId(2000 + i), vec![Arc::new(art)]); + } + let mut doc = d.clone(); + doc.symbols.push(Symbol { dynamic: false, name: "Nested".into(), art: Arc::new(art) }); + validate_three_d_in(Some(&doc), &with(instance(30, "Nested", Affine::IDENTITY), ROTATE, front()), ROTATE, &json!({})).is_ok() + }; + let path_ok = ok(&square); + assert_eq!(ok(&compound), path_ok, "{levels} levels"); + seen.push(path_ok); + } + assert!(seen.contains(&true) && seen.contains(&false), "the levels cross the limit: {seen:?}"); + // A clipping group used as the clipping path clips by its first member only, so deep art it + // clips is not walked for the clip. + let mask = Node::new( + NodeId(70), + NodeKind::Group { children: vec![Arc::new(clipping_path(71, clip)), Arc::new(deep_symbol.symbols[1].art.as_ref().clone())], clip: true }, + ); + let by_deep_mask = with( + Node::new(NodeId(10), NodeKind::Group { children: vec![Arc::new(mask), Arc::new(rect(12, 100.0, 100.0, 200.0, 200.0, 0.0))], clip: true }), + ROTATE, + front(), + ); + assert_eq!(validate_three_d_in(Some(&d), &by_deep_mask, ROTATE, &json!({})), Ok(())); + assert!(close(bounds(&solid_art_in(Some(&d), &by_deep_mask).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); + // A clip that shows none of the art builds nothing, and says so. + let empty = clip_group(10, Rect::new(500.0, 500.0, 550.0, 550.0), rect(12, 100.0, 100.0, 200.0, 200.0, 2.0)); + for id in TYPES { + let n = with(empty.clone(), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("at least two anchors")), "{id}"); + assert!(art(&d, &n, id).is_none(), "{id}"); + } +} + +#[test] +fn a_symbol_instances_solid_is_its_symbols_art_where_the_instance_places_it() { + let d = document(); + let placed = with(instance(30, "Box", Affine::translate((300.0, 50.0))), EXTRUDE, json!({})); + let same = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 300.0, 50.0, 400.0, 150.0, 2.0))]), EXTRUDE, json!({})); + assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&same).unwrap()), 0.01)); + // A redefined symbol reshapes the solid. + let mut wider = d.clone(); + wider.symbols[0].art = Arc::new(rect(0, 0.0, 0.0, 200.0, 100.0, 2.0)); + assert!(bounds(&solid_art_in(Some(&wider), &placed).unwrap()).width() > bounds(&solid_art_in(Some(&d), &placed).unwrap()).width() + 50.0); + // Without the symbol there is nothing to build from. + let missing = with(instance(30, "Gone", Affine::IDENTITY), EXTRUDE, json!({})); + assert!(validate_three_d_in(Some(&d), &missing, EXTRUDE, &json!({})).is_err_and(|e| e.contains("\"Gone\""))); + assert!(validate_three_d(&placed, EXTRUDE, &json!({})).is_err(), "no document: no symbol art"); + // A symbol holding an instance of itself is refused, not followed without end. + let mut looped = d.clone(); + let inner = Arc::new(instance(0, "Loop", Affine::translate((10.0, 10.0)))); + looped.symbols.push(Symbol { + dynamic: false, + name: "Loop".into(), + art: Arc::new(Node::group(NodeId(0), vec![Arc::new(rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)), inner])), + }); + let n = with(instance(30, "Loop", Affine::IDENTITY), EXTRUDE, json!({})); + assert!(validate_three_d_in(Some(&looped), &n, EXTRUDE, &json!({})).is_err()); + assert!(solid_art_in(Some(&looped), &n).is_none()); +} + +#[test] +fn a_blends_solid_is_built_from_its_keys_and_steps() { + let d = document(); + for steps in [1, 3, 8] { + let n = with(blend(20, steps), ROTATE, front()); + let expanded = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, steps)).into_iter().map(Arc::new).collect()); + assert_eq!(expanded.children().unwrap().len(), steps as usize + 2); + let same = with(expanded, ROTATE, front()); + let (a, b) = (solid_art_in(Some(&d), &n).unwrap(), solid_art(&same).unwrap()); + assert_eq!(a.children().unwrap().len(), b.children().unwrap().len(), "a surface for each key and step"); + assert!(close(bounds(&a), bounds(&b), 0.01)); + } + // A blend making more objects than a 3D effect takes is refused. + let keys = (0..6).map(|i| Arc::new(rect(21 + i, 100.0 * i as f64, 0.0, 100.0 * i as f64 + 40.0, 40.0, 0.0))).collect(); + let spec = BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() }; + let n = with(Node::new(NodeId(20), NodeKind::Blend { children: keys, spec: Box::new(spec) }), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at most 4096 objects"))); +} + +#[test] +fn images_are_refused_alone_and_in_a_group_with_image_trace_named() { + let d = document(); + for id in TYPES { + for n in [ + with(image(50), id, json!({})), + with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(image(53))]), id, json!({})), + with(clip_group(60, Rect::new(0.0, 0.0, 10.0, 10.0), image(62)), id, json!({})), + ] { + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}"); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err_and(|e| e.contains("Image Trace")), "{id}"); + } + // An image wholly outside the clip, alone or in a group, shows nothing and is left out; + // one the clip shows part of is refused. + let clip = Rect::new(100.0, 100.0, 150.0, 150.0); + let masked = |inside: bool| { + let mut img = image(63); + if let NodeKind::Image(i) = &mut img.kind { + i.xf = Affine::translate(if inside { (95.0, 95.0) } else { (300.0, 300.0) }); + } + img + }; + for img in [masked(false), Node::group(NodeId(64), vec![Arc::new(masked(false))])] { + let children = vec![Arc::new(clipping_path(61, clip)), Arc::new(rect(62, 100.0, 100.0, 200.0, 200.0, 0.0)), Arc::new(img)]; + let n = with(Node::new(NodeId(60), NodeKind::Group { children, clip: true }), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}"); + assert!(art(&d, &n, id).is_some(), "{id}"); + } + let partly = with(clip_group(60, clip, masked(true)), id, json!({})); + assert!(validate_three_d_in(Some(&d), &partly, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}"); + // An effect on the image, or on a group holding it, can move it into the clip: refused. + let moved = |n: Node| with(n, "distort.transform", json!({"moveH": -200.0, "moveV": -200.0})); + for img in [moved(masked(false)), moved(Node::group(NodeId(64), vec![Arc::new(masked(false))]))] { + let n = with(clip_group(60, clip, img), id, json!({})); + assert!(validate_three_d_in(Some(&d), &n, id, &json!({})).is_err_and(|e| e.contains("Image Trace")), "{id}"); + } + // A hidden image is not drawn, so it builds nothing and refuses nothing. + let mut hidden = image(53); + hidden.visible = false; + let g = with(Node::group(NodeId(51), vec![Arc::new(rect(52, 0.0, 0.0, 10.0, 10.0, 0.0)), Arc::new(hidden)]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id}"); + } +} + +/// Symbols `L0` to `L{levels}`: `L0` holds `leaf`, each later one `fan` instances of the one +/// before it. +fn nested_symbols(levels: usize, fan: usize, leaf: Node) -> Document { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "L0".into(), art: Arc::new(Node::group(NodeId(0), vec![Arc::new(leaf)])) }); + for level in 1..=levels { + let below = format!("L{}", level - 1); + let members = (0..fan).map(|i| Arc::new(instance(0, &below, Affine::translate((i as f64 * 2.0, 0.0))))).collect(); + d.symbols.push(Symbol { dynamic: false, name: format!("L{level}"), art: Arc::new(Node::group(NodeId(0), members)) }); + } + d +} + +#[test] +fn nested_symbol_instances_that_repeat_hidden_art_are_refused_past_the_work_limit() { + // Four instances at each of ten levels repeat the hidden path about a million times, with no + // object to count against the 4,096-object limit. + let mut hidden = rect(0, 0.0, 0.0, 10.0, 10.0, 0.0); + hidden.visible = false; + let d = nested_symbols(10, 4, hidden); + for id in TYPES { + let n = with(instance(30, "L10", Affine::IDENTITY), id, json!({})); + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{id}: {err}"); + assert!(source::WORK.with(std::cell::Cell::get) <= source::MAX_WORK + 1, "{id}: stopped at the limit"); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}"); + } + // A clipped shape with more strokes than a 3D effect takes objects is refused before its + // strokes are cut into pieces. + let mut stroked = rect(12, 100.0, 100.0, 200.0, 200.0, 0.0); + let strokes = (0..5000).map(|_| AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))).collect(); + stroked.appearance = Appearance { items: strokes, ..Default::default() }.into(); + let n = with(clip_group(10, Rect::new(100.0, 100.0, 150.0, 200.0), stroked), ROTATE, front()); + let err = validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).unwrap_err(); + assert!(err.contains("takes at most 4096 objects") && !err.contains("on a group"), "{err}"); + // The same nesting with 1,024 visible squares stays far below the limit and builds: each + // square, group and instance is visited once (an instance twice: listed, then resolved). + let d = nested_symbols(5, 4, rect(0, 0.0, 0.0, 10.0, 10.0, 0.0)); + let n = with(instance(30, "L5", Affine::IDENTITY), ROTATE, front()); + assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(())); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 1024 + 1365 * 3, "{work}"); + assert!(solid_art_in(Some(&d), &n).is_some()); +} + +#[test] +fn a_symbol_holding_more_objects_than_the_work_limit_is_refused_before_its_art_is_placed() { + let mut d = document(); + let members = (0..=source::MAX_WORK).map(|i| Arc::new(rect(0, i as f64, 0.0, i as f64 + 1.0, 1.0, 0.0))).collect(); + d.symbols.push(Symbol { dynamic: false, name: "Big".into(), art: Arc::new(Node::group(NodeId(0), members)) }); + let n = with(instance(30, "Big", Affine::IDENTITY), EXTRUDE, json!({})); + let err = validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({})).unwrap_err(); + assert!(err.contains("hold too many objects"), "{err}"); + let work = source::WORK.with(std::cell::Cell::get); + assert!(work <= 2, "refused before the symbol's art is placed and listed: {work}"); +} + +#[test] +fn empty_sources_and_sources_inside_sources_build_or_refuse_cleanly() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Empty".into(), art: Arc::new(Node::group(NodeId(0), vec![])) }); + let clip = Rect::new(0.0, 0.0, 50.0, 100.0); + d.symbols.push(Symbol { dynamic: false, name: "Clipped".into(), art: Arc::new(clip_group(0, clip, rect(0, 0.0, 0.0, 100.0, 100.0, 0.0))) }); + let empty_clip = Node::new(NodeId(10), NodeKind::Group { children: vec![], clip: true }); + let empty_symbol = instance(30, "Empty", Affine::IDENTITY); + let no_keys = Node::new(NodeId(20), NodeKind::Blend { children: vec![], spec: Box::default() }); + for id in TYPES { + // Alone, an empty clipping group, an instance of an empty symbol and a blend without keys + // build nothing and say so. + for empty in [&empty_clip, &empty_symbol, &no_keys] { + let n = with(empty.clone(), id, json!({})); + let err = validate_three_d_in(Some(&d), &n, id, &json!({})).unwrap_err(); + assert!(err.contains("at least two anchors"), "{id} on {:?}: {err}", empty.kind); + assert!(art(&d, &n, id).is_none(), "{id}"); + assert!(three_d_meshes_in(Some(&d), &n).is_err(), "{id}"); + // In a group they add nothing, and the group's other members still build. + let g = with(Node::group(NodeId(90), vec![Arc::new(empty.clone()), Arc::new(rect(91, 0.0, 0.0, 50.0, 50.0, 0.0))]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {:?}", empty.kind); + assert!(art(&d, &g, id).is_some(), "{id}"); + } + // A blend set to no steps draws one step, and builds from its keys and that step. + let n = with(blend(20, 0), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &n, id, &json!({})), Ok(()), "{id}"); + } + let drawn = Node::group(NodeId(20), crate::expand_live(Some(&d), &blend(20, 0)).into_iter().map(Arc::new).collect()); + assert_eq!(drawn.children().unwrap().len(), 3); + let (a, b) = (solid_art_in(Some(&d), &with(blend(20, 0), ROTATE, front())).unwrap(), solid_art(&with(drawn, ROTATE, front())).unwrap()); + assert_eq!(a.children().unwrap().len(), b.children().unwrap().len()); + assert!(close(bounds(&a), bounds(&b), 0.01)); + // A symbol holding a clipping group builds from the art inside the clip, where the instance + // places it. + let placed = with(instance(30, "Clipped", Affine::translate((200.0, 0.0))), ROTATE, front()); + let cut = with(Node::group(NodeId(30), vec![Arc::new(rect(31, 200.0, 0.0, 250.0, 100.0, 0.0))]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &placed).unwrap()), bounds(&solid_art(&cut).unwrap()), 0.01)); +} + +#[test] +fn resolved_objects_and_groups_in_a_three_d_group_keep_their_geometry_effects() { + let mut d = document(); + d.symbols.push(Symbol { dynamic: false, name: "Left".into(), art: Arc::new(rect(0, 0.0, 100.0, 50.0, 200.0, 0.0)) }); + let moved = |n: Node| with(n, "distort.transform", json!({"moveH": 100.0})); + let clip = Rect::new(100.0, 100.0, 150.0, 200.0); + let target = rect(1, 100.0, 100.0, 150.0, 200.0, 0.0); + let expected = bounds(&solid_art(&with(Node::group(NodeId(90), vec![Arc::new(target.clone())]), ROTATE, front())).unwrap()); + let left = || rect(2, 0.0, 100.0, 50.0, 200.0, 0.0); + let members = [ + ("a symbol instance", moved(instance(30, "Left", Affine::IDENTITY))), + ("a clipping group", moved(clip_group(40, Rect::new(0.0, 100.0, 50.0, 200.0), left()))), + ("a plain group", moved(Node::group(NodeId(50), vec![Arc::new(left())]))), + ("a group in a clipping group", clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(left())])))), + ]; + for (what, member) in members { + for id in TYPES { + let g = with(Node::group(NodeId(90), vec![Arc::new(member.clone())]), id, json!({})); + assert_eq!(validate_three_d_in(Some(&d), &g, id, &json!({})), Ok(()), "{id} on a group holding {what}"); + } + let g = with(Node::group(NodeId(90), vec![Arc::new(member)]), ROTATE, front()); + assert!(close(bounds(&solid_art_in(Some(&d), &g).unwrap()), expected, 0.01), "{what} moved by its Transform effect"); + } + // A blend's effect moves its keys and steps together. + let blended = with(Node::group(NodeId(90), vec![Arc::new(moved(blend(20, 3)))]), ROTATE, front()); + let unmoved = with(Node::group(NodeId(90), vec![Arc::new(blend(20, 3))]), ROTATE, front()); + let (a, b) = (bounds(&solid_art_in(Some(&d), &blended).unwrap()), bounds(&solid_art_in(Some(&d), &unmoved).unwrap())); + assert!(close(a, Rect::new(b.x0 + 100.0, b.y0, b.x1 + 100.0, b.y1), 0.01), "{a:?} is {b:?} moved"); + // A geometry effect that reads the object's stroke reads the resolved object's, as a group's. + let stroked = |kind: NodeKind| { + let mut n = Node::new(NodeId(20), kind); + n.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 10.0).into(); + with(n, "path.outlineStroke", json!({})) + }; + let NodeKind::Blend { children, spec } = blend(20, 3).kind else { panic!("a blend") }; + let steps = crate::expand_live(Some(&d), &blend(20, 3)).into_iter().map(Arc::new).collect(); + let group_of = |n: Node| with(Node::group(NodeId(90), vec![Arc::new(n)]), ROTATE, front()); + let resolved = bounds(&solid_art_in(Some(&d), &group_of(stroked(NodeKind::Blend { children, spec }))).unwrap()); + let plain = bounds(&solid_art(&group_of(stroked(NodeKind::Group { children: steps, clip: false }))).unwrap()); + assert!(close(resolved, plain, 0.01), "{resolved:?} {plain:?}"); + // A member's opacity and blending mode stay on it when its group's effects reshape it in a clip. + let mut multiplied = left(); + multiplied.opacity = 0.5; + multiplied.blend = BlendMode::Multiply; + let n = clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(multiplied), Arc::new(left())]))); + let resolved = resolve(Some(&d), &n, "").unwrap().into_owned(); + let mut found = vec![]; + resolved.walk(&mut |c| { + if c.blend == BlendMode::Multiply { + found.push((c.opacity, c.children().map_or(0, Vec::len))); + } + }); + assert_eq!(found, vec![(0.5, 1)], "one Multiply group at 50% holding the one member's piece"); + // Groups nested past the limit under a group with geometry effects in a clipping group are + // refused before the effects reshape them. + let mut deep = left(); + for i in 0..200 { + deep = Node::group(NodeId(1000 + i), vec![Arc::new(deep)]); + } + let n = with(clip_group(60, clip, moved(deep.clone())), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("levels deep"))); + // A hidden member nested past the limit is left out, as it is drawn, and does not refuse. + deep.visible = false; + let n = with(clip_group(60, clip, moved(Node::group(NodeId(62), vec![Arc::new(deep), Arc::new(left())]))), ROTATE, front()); + assert_eq!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})), Ok(())); + // Hidden members of a group inside a clipping group build nothing. + let mut hidden = rect(63, 100.0, 100.0, 150.0, 200.0, 0.0); + hidden.visible = false; + let n = with(clip_group(60, clip, Node::group(NodeId(62), vec![Arc::new(hidden)])), ROTATE, front()); + assert!(validate_three_d_in(Some(&d), &n, ROTATE, &json!({})).is_err_and(|e| e.contains("at least two anchors"))); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 7c1c9eea49..c76492f454 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -70,6 +70,7 @@ pub mod pdfcmds; pub mod perspgrid; pub mod place; pub mod plugin; +pub(crate) mod plugin_call; pub mod prefscmds; pub mod print; pub(crate) mod printadvanced; diff --git a/crates/engine/src/cmd/addons/contour.rs b/crates/engine/src/cmd/addons/contour.rs index 46df381edc..34b9443429 100644 --- a/crates/engine/src/cmd/addons/contour.rs +++ b/crates/engine/src/cmd/addons/contour.rs @@ -12,8 +12,8 @@ use vectorcraft_doc::NodeKind; use vectorcraft_render::effects; use super::super::edit::{copy_above, selected_roots}; -use super::super::pathops::{len_param, num_param}; -use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, str_param}; +use super::super::pathops::{length_given, number_given}; +use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_selection, text_param}; const C: &str = "addon.contour.set"; /// The live effect that does the offsetting (the one Effect › Path › Offset Path applies). @@ -44,12 +44,12 @@ fn joins_for(corners: Option<&str>) -> Result<&'static str> { } fn contour(s: &mut Session, p: &Value) -> Result { - let offset = len_param(p, "offset").ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; + let offset = length_given(p, "offset", C)?.ok_or_else(|| bad(C, "missing `offset` (a distance in points)"))?; if offset.abs() > MAX_OFFSET { return Err(bad(C, "offset out of range")); } - let joins = joins_for(str_param(p, "corners"))?; - let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let joins = joins_for(text_param(p, "corners", C)?)?; + let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0); let effect = effects::new_effect(EFFECT, &json!({"offset": offset, "joins": joins, "miterLimit": miter})) .ok_or_else(|| EngineError::Other("Contour: the Offset Path effect is not available".into()))?; let roots = selected_roots(s)?; diff --git a/crates/engine/src/cmd/addons/contour/tests.rs b/crates/engine/src/cmd/addons/contour/tests.rs index 900d110d58..3983ed942d 100644 --- a/crates/engine/src/cmd/addons/contour/tests.rs +++ b/crates/engine/src/cmd/addons/contour/tests.rs @@ -158,6 +158,39 @@ fn contour_refuses_what_it_cannot_offset() { assert!(err.contains("select paths or shapes"), "{err}"); } +/// A param of the wrong type is an error naming the param, and leaves the document, the selection +/// and the undo history as they were. Null keeps a param's default, and `offset` still takes a +/// string with a unit. +#[test] +fn contour_refuses_a_param_of_the_wrong_type() { + let mut s = session(); + rect(&mut s, 100.0, 100.0, 50.0, 40.0); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + for (p, want) in [ + (json!({"offset": true}), "`offset` must be a number, not true"), + (json!({"offset": "abc"}), "`offset` must be a number, not \"abc\""), + (json!({"offset": [5]}), "`offset` must be a number, not [5]"), + (json!({"offset": 5, "corners": 3}), "`corners` must be a string"), + (json!({"offset": 5, "miterLimit": "high"}), "`miterLimit` must be a number, not \"high\""), + (json!({"offset": 5, "miterLimit": false}), "`miterLimit` must be a number, not false"), + ] { + let r = s.execute("addon.contour.set", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + assert!(state(&s) == before, "{p} changed the document, the selection or the undo history"); + } + // A null `offset` is a missing one. + let err = s.execute("addon.contour.set", &json!({"offset": null})).unwrap_err().to_string(); + assert!(err.contains("missing `offset`"), "{err}"); + // Null corners and miter limit keep sharp corners at 4; the offset takes a unit. + let r = s.execute("addon.contour.set", &json!({"offset": "1 in", "corners": null, "miterLimit": null})).unwrap(); + let fx = effects_of(&s, ids_of(&r, "created")[0]); + assert_eq!((fx[0].1["offset"].clone(), fx[0].1["joins"].clone(), fx[0].1["miterLimit"].clone()), (json!(72.0), json!("miter"), json!(4.0))); +} + /// The border-with-a-gap recipe: two Contours of one shape (the gap, then the border), baked, then /// the gap taken out of the border with Minus Front, leaves a ring between the two. #[test] diff --git a/crates/engine/src/cmd/assets.rs b/crates/engine/src/cmd/assets.rs index 31639519f0..0b57565af4 100644 --- a/crates/engine/src/cmd/assets.rs +++ b/crates/engine/src/cmd/assets.rs @@ -213,7 +213,7 @@ fn add_3d(s: &mut Session, p: &Value) -> Result { ids.dedup(); for id in &ids { let n = d.node(*id).ok_or_else(|| bad(C, format!("no such object {0}", id.0)))?; - if let Err(e) = vectorcraft_render::effects::three_d_meshes(n) { + if let Err(e) = vectorcraft_render::effects::three_d_meshes_in(Some(d), n) { let what = n.name.clone().unwrap_or_else(|| format!("#{}", id.0)); return Err(bad(C, format!("{what} can't be exported in 3D: {e}"))); } @@ -281,7 +281,8 @@ fn export_3d(s: &mut Session, p: &Value) -> Result { a.nodes.iter().map(|node| d.node(*node).ok_or_else(|| bad(C, format!("no such object {0}", node.0)))).collect::>>()?; // The asset's objects share one budget of triangles. let what = &a.name; - let parts = vectorcraft_render::effects::three_d_meshes_of(nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; + let parts = + vectorcraft_render::effects::three_d_meshes_of_in(Some(d), nodes).map_err(|e| bad(C, format!("{what} can't be exported in 3D: {e}")))?; let base = Some(safe_file_name(&a.name)).filter(|b| !b.is_empty()).unwrap_or_else(|| "Asset".into()); let mut stem = base.clone(); let mut k = 1; diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index d387d63d2c..5ff09dc284 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -264,6 +264,8 @@ impl Clipboard { .and_then(|p| *compound_bounds.entry(p.id).or_insert_with(|| p.geometric_bounds())); // A compound's member or piece copied on its own takes the compound's look (its paint, // transparency, opacity mask, pixel alignment and fill rule), so it pastes as it looked. + // It is linked to the compound's graphic style while it still has that style's look + // (a gradient pinned to the compound's bounds does not), else to none. let inherit_appearance = |mut piece: Node| { if let Some(parent) = compound_parent && let (NodeKind::Compound { rule: compound_rule, .. }, NodeKind::Path { rule, .. }) = (&parent.kind, &mut piece.kind) @@ -276,11 +278,21 @@ impl Clipboard { piece.opacity = parent.opacity; piece.blend = parent.blend; piece.isolate = parent.isolate; + piece.knockout = parent.knockout; piece.knockout_shape = parent.knockout_shape; let (mask, pixel_aligned) = (parent.extras().mask.clone(), parent.extras().pixel_aligned); - let mut extras = piece.extras_mut(); - extras.mask = mask; - extras.pixel_aligned = pixel_aligned; + { + let mut extras = piece.extras_mut(); + extras.mask = mask; + extras.pixel_aligned = pixel_aligned; + } + let link = parent + .extras() + .graphic_style + .and_then(|g| d.graphic_style_by_id(g)) + .filter(|g| super::style::in_sync(&piece, g)) + .map(|g| g.id); + piece.extras_mut().graphic_style = link; } piece }; diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index d9b5784b68..03b171de71 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Color Settings…", ["Edit"], Some("Cmd+Shift+K"), - "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}", + "{rgb?: profile, cmyk?: profile, intent?: \"perceptual\"|\"relative\"|\"saturation\"|\"absolute\", bpc?: bool} set the working spaces → {rgb, cmyk, intent, bpc, profiles: [{name, kind, builtin}]}. The desktop app and vectorcraft-cli keep them in `Color Settings.json` next to the preferences and use them again at the next start (not with VECTORCRAFT_NO_PREFS); saved settings naming a profile that is gone leave the defaults", always, color_settings ), @@ -192,6 +192,8 @@ fn color_settings(s: &mut Session, p: &Value) -> Result { st.bpc = switch_or(p, "bpc", st.bpc, C)?; if st != before { cms::set_active(&st).map_err(|e| bad(C, e.to_string()))?; + // Saved for the next start when the app attached a settings file (#6335). + s.store_color_settings(&st); touch_all(s); } Ok(settings_json(&st)) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 68fb9b74e8..024ba535b4 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -166,7 +166,7 @@ pub fn specs() -> Vec { "Copy", ["Edit"], Some("Cmd+C"), - "{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask and fill rule, a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", + "{selectedArtboards?: [n…] (the artboards the Artboard tool had selected, which the journal records for a replay; it runs artboard.copy with any tool chosen), art?: bool (default: the Artboard tool's moveArt option; the journal records it beside selectedArtboards), lockedAndHidden?: bool (the Artboard tool chosen, as artboard.copy)} the selection with what it uses (a compound-path member selected on its own, whole or in part, with Direct or Group Selection, is copied as an ordinary path with the compound's paint, transparency, opacity mask, fill rule and graphic style link (while it has that style's look), a gradient keeping the compound's fit; the compound is copied when it is selected, or when every member is selected whole outside isolation mode), and the selected ruler guides (pasted on the layer new art goes to, moved as the objects are; alone, where they were); the Artboard tool chosen: artboard.copy; with an object of a symbol instance's art selected, the instance is copied whole → {copied, guides}", has_selection_guides_or_artboard_tool, copy ), diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 9d396edc16..8bf5c9a3d7 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -282,11 +282,12 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { if effects::is_three_d(id) { let targets = appearance_targets(s, p)?; for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) { - let n = s.doc()?.doc.node(target).ok_or(EngineError::NoNode(target))?; + let d = &s.doc()?.doc; + let n = d.node(target).ok_or(EngineError::NoNode(target))?; // A new effect goes after the item's others. let on = at.and_then(|at| at.effects_item(&n.appearance, C).ok()).flatten(); let on = on.and_then(|i| Some((i, n.appearance.items.get(i)?.effects().len()))); - effects::validate_three_d_at(n, id, &effect.params, on).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, id, &effect.params, on).map_err(|e| bad(C, e))?; if id == effects::REVOLVE && effects::has_revolve(n) { return Err(bad(C, "A profile supports one Revolve effect. Edit the existing effect's options instead.")); } @@ -575,7 +576,8 @@ fn set_params(s: &mut Session, p: &Value) -> Result { params["name"] = json!(svg_filter_name(s, xml, C)?); } for &(id, target, index) in &targets { - let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + let d = &s.doc()?.doc; + let n = d.node(id).ok_or(EngineError::NoNode(id))?; let effect = n.appearance.effects_at(target).and_then(|fx| fx.get(index)); if warp_id.is_some() && effect.is_some_and(|e| e.id.strip_prefix("warp.").and_then(effects::WarpStyle::from_id).is_none()) { return Err(bad(C, "warpStyle can only edit an applied Warp effect")); @@ -593,7 +595,7 @@ fn set_params(s: &mut Session, p: &Value) -> Result { cur.extend(new); } if visible != Some(false) { - effects::validate_three_d_at(n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; + effects::validate_three_d_at_in(Some(d), n, to, &prospective, target.map(|item| (item, index))).map_err(|e| bad(C, e))?; } else { // Hidden, the effect draws nothing, so its object need not fit. The values given are // checked, and after a change of 3D type so is every value it keeps. @@ -1006,6 +1008,9 @@ fn expand_appearance(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod lighting_presets_tests; +#[cfg(test)] +mod three_d_source_tests; + #[cfg(test)] mod three_d_type_tests; diff --git a/crates/engine/src/cmd/effectcmd/tests.rs b/crates/engine/src/cmd/effectcmd/tests.rs index 6604c99a2e..e4c8d79450 100644 --- a/crates/engine/src/cmd/effectcmd/tests.rs +++ b/crates/engine/src/cmd/effectcmd/tests.rs @@ -130,7 +130,8 @@ fn solid_effects_apply_save_edit_export_expand_and_undo() { } /// #4506: a 3D effect on a group builds a solid from each member, turned about one shared axis; -/// the members stay editable, and a group holding what can't become a solid is refused. +/// the members stay editable. A group holding a clipping group builds from the art it shows, and a +/// group holding what can't become a solid is refused. #[test] fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { for effect in effects::SOLIDS { @@ -151,17 +152,59 @@ fn solid_effects_apply_to_a_group_and_its_members_stay_editable() { s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); assert!(!effects::has_solid(&node(&s, g)), "{effect}: expanded"); } - // A clipping group in the group: refused, nothing changed. + // A clipping group in the group: each effect builds from the art it shows. + for effect in effects::SOLIDS { + let (mut s, _, g) = group_with_a_clipping_group(); + s.execute("effect.apply", &json!({"effect": effect, "ids": [g.0], "item": null})).unwrap_or_else(|e| panic!("{effect}: {e}")); + let n = node(&s, g); + assert_eq!(n.children().unwrap().len(), 2, "{effect}: the members stay as they were"); + let art = effects::solid_art_in(Some(&s.doc().unwrap().doc), &n); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{effect}: draws its solid"); + } + // An image in the group: refused, nothing changed. + let (mut s, _, g) = group_with_an_image(); + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("Image Trace"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); +} + +/// A group of a clipping group (a rectangle clipped by an ellipse) and a rectangle: the session, +/// the clipping group and the group. +fn group_with_a_clipping_group() -> (Session, NodeId, NodeId) { let (mut s, a) = session_with_rect(); let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone(); s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); - let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone(); + let clip = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap()); let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone(); - s.execute("select.set", &json!({"ids": [clip, c]})).unwrap(); + s.execute("select.set", &json!({"ids": [clip.0, c]})).unwrap(); let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - let err = s.execute("effect.apply", &json!({"effect": "threeD.extrude", "ids": [g.0], "item": null})).unwrap_err().to_string(); - assert!(err.contains("clipping groups"), "{err}"); - assert!(node(&s, g).appearance.effects.is_empty()); + (s, clip, g) +} + +/// A group of a rectangle and an image: the session, the image and the group. +fn group_with_an_image() -> (Session, NodeId, NodeId) { + let (mut s, a) = session_with_rect(); + let image = s + .edit("Place", |d, _| { + let id = d.alloc_id(); + let img = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((250.0, 250.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let (parent, index, _) = d.position(a).unwrap(); + d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?; + Ok(id) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [a.0, image.0]})).unwrap(); + let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + (s, image, g) } /// #4715: type extrudes as its glyph outlines, painted with its characters' colour, and stays @@ -339,21 +382,25 @@ fn revolve_on_a_group_shares_one_axis_and_members_stay_editable() { assert!(effects::has_revolve(&node(&s, g))); } -/// A group holding what can't be swept is refused as a whole, and a clipping group is named. +/// A group holding what can't be swept is refused as a whole, and an image is named. A clipping +/// group, alone or in a group, sweeps the art it shows. #[test] fn revolve_refuses_a_group_with_a_member_it_can_not_sweep() { - let (mut s, a) = session_with_rect(); - let b = s.execute("shape.ellipse", &json!({"x": 120, "y": 120, "width": 60, "height": 60})).unwrap()["id"].clone(); - s.execute("select.set", &json!({"ids": [a.0, b]})).unwrap(); - let clip = s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].clone(); - let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [clip.as_u64().unwrap()], "item": null})).unwrap_err().to_string(); - assert!(err.contains("path, compound path, type or group"), "{err}"); - let c = s.execute("shape.rectangle", &json!({"x": 250, "y": 250, "width": 50, "height": 50})).unwrap()["id"].clone(); - s.execute("select.set", &json!({"ids": [clip, c]})).unwrap(); - let g = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); - let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [g.0], "item": null})).unwrap_err().to_string(); - assert!(err.contains("Revolve on a group") && err.contains("clipping groups"), "{err}"); - assert!(node(&s, g).appearance.effects.is_empty()); + let (mut s, image, g) = group_with_an_image(); + let before = s.doc().unwrap().doc.clone(); + for target in [image, g] { + let err = s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null})).unwrap_err().to_string(); + assert!(err.contains("Revolve") && err.contains("Image Trace"), "{err}"); + assert_eq!(s.doc().unwrap().doc, before, "nothing changed"); + } + for clipping_group_itself in [true, false] { + let (mut s, clip, g) = group_with_a_clipping_group(); + let target = if clipping_group_itself { clip } else { g }; + s.execute("effect.apply", &json!({"effect": "threeD.revolve", "ids": [target.0], "item": null})) + .unwrap_or_else(|e| panic!("{clipping_group_itself}: {e}")); + let art = effects::revolve_art_in(Some(&s.doc().unwrap().doc), &node(&s, target)); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{clipping_group_itself}: draws its surface"); + } } /// Scripts from before the Perspective angle give `perspective` as a 0–100 % strength: it is diff --git a/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs new file mode 100644 index 0000000000..122d937b98 --- /dev/null +++ b/crates/engine/src/cmd/effectcmd/three_d_source_tests.rs @@ -0,0 +1,98 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"]; + +fn id_of(v: &Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +/// A clipping group, a blend and a symbol instance, each made through its command. +fn sources(s: &mut Session) -> Vec<(&'static str, NodeId)> { + let art = rect(s, 20.0, 20.0, 60.0, 60.0); + let clip = rect(s, 40.0, 10.0, 20.0, 80.0); + select(s, &[art, clip]); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let clipped = s.doc().unwrap().selection.objects[0]; + let a = rect(s, 120.0, 20.0, 20.0, 20.0); + let b = rect(s, 200.0, 60.0, 30.0, 30.0); + select(s, &[a, b]); + let blend = id_of(&s.execute("object.blend.make", &json!({})).unwrap()); + let art = rect(s, 20.0, 200.0, 50.0, 40.0); + let instance = id_of(&s.execute("symbol.new", &json!({"name": "Box", "ids": [art.0]})).unwrap()); + vec![("clipping group", clipped), ("blend", blend), ("symbol instance", instance)] +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s +} + +#[test] +fn every_three_d_type_applies_to_clipping_groups_blends_and_symbol_instances_in_one_undo_step() { + for id in TYPES { + let mut s = session(); + for (what, target) in sources(&mut s) { + select(&mut s, &[target]); + let undo = s.doc().unwrap().history.undo.len(); + s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_or_else(|e| panic!("{id} on a {what}: {e}")); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "{id} on a {what}"); + let n = s.doc().unwrap().doc.node(target).unwrap().clone(); + assert_eq!(n.appearance.effects.iter().filter(|e| e.id == id).count(), 1, "{id} on a {what}"); + // The object stays what it is, and the effect draws its solid. + assert!(!matches!(n.kind, NodeKind::Path { .. }), "{id} on a {what}"); + let d = &s.doc().unwrap().doc; + let art = vectorcraft_render::effects::revolve_art_in(Some(d), &n).or_else(|| vectorcraft_render::effects::solid_art_in(Some(d), &n)); + assert!(art.is_some_and(|a| a.visual_bounds().is_some()), "{id} on a {what} draws its solid"); + // Edited through the dialog's command too. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"rotationY": 20.0}})) + .unwrap_or_else(|e| panic!("{id} on a {what}: {e}")); + } + } +} + +#[test] +fn a_group_holding_an_image_refuses_every_three_d_type_and_names_image_trace() { + let mut s = session(); + let a = rect(&mut s, 20.0, 20.0, 60.0, 60.0); + let image = s + .edit("Place", |d, _| { + let id = d.alloc_id(); + let img = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 4, + height: 4, + xf: vectorcraft_geom::Affine::translate((100.0, 100.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let (parent, index, _) = d.position(a).unwrap(); + d.insert(parent, index + 1, vectorcraft_doc::Node::new(id, NodeKind::Image(Box::new(img))))?; + Ok(id) + }) + .unwrap(); + select(&mut s, &[a, image]); + s.execute("object.group", &json!({})).unwrap(); + for target in [image, s.doc().unwrap().selection.objects[0]] { + select(&mut s, &[target]); + for id in TYPES { + let before = s.doc().unwrap().doc.clone(); + let err = s.execute("effect.apply", &json!({"effect": id, "item": null})).unwrap_err().to_string(); + assert!(err.contains("Object › Image Trace › Make"), "{id}: {err}"); + assert_eq!(s.doc().unwrap().doc, before, "{id}: nothing changed"); + } + } +} diff --git a/crates/engine/src/cmd/expand.rs b/crates/engine/src/cmd/expand.rs index 8834e6a741..546b5a8258 100644 --- a/crates/engine/src/cmd/expand.rs +++ b/crates/engine/src/cmd/expand.rs @@ -25,7 +25,7 @@ use super::edit::selected_roots; use super::menucmds::{run_raw, squash}; use super::object::as_clipping_path; use super::pathops::{assemble, node_path, outline_strokes, replace_leaves, styled_copy, with_transparency}; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, f64_or, has_selection, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, has_selection, number_or, switch_or, text_param}; const C: &str = "object.expand"; /// Expand Gradient To → Specify … Objects: the default and the most. @@ -101,11 +101,11 @@ enum GradientTo { impl GradientTo { fn parse(p: &Value) -> Result { - let steps = f64_or(p, "steps", DEFAULT_STEPS as f64).round(); + let steps = number_or(p, "steps", DEFAULT_STEPS as f64, C)?.round(); if !(1.0..=MAX_STEPS as f64).contains(&steps) { return Err(bad(C, format!("steps must be 1..{MAX_STEPS}"))); } - match str_param(p, "gradient").unwrap_or("objects") { + match text_param(p, "gradient", C)?.unwrap_or("objects") { "objects" => Ok(Self::Objects(steps as u32)), "mesh" => Ok(Self::Mesh), _ => Err(bad(C, "gradient must be \"objects\" or \"mesh\"")), @@ -236,9 +236,9 @@ fn expand(s: &mut Session, p: &Value) -> Result { } fn expand_steps(s: &mut Session, p: &Value) -> Result { - let object = bool_or(p, "object", true); - let fill = bool_or(p, "fill", true); - let stroke = bool_or(p, "stroke", true); + let object = switch_or(p, "object", true, C)?; + let fill = switch_or(p, "fill", true, C)?; + let stroke = switch_or(p, "stroke", true, C)?; let to = GradientTo::parse(p)?; let from = s.doc()?.history.undo.len(); let mut e = Expandable::of(&s.doc()?.doc, &selected_roots(s)?); diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 2387088b3f..e0acc2d52d 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption; PDF/X files, 1.3 and 1.4 write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused", has_doc, export_pdf ), @@ -334,6 +334,8 @@ fn encode_carrying_at( let pages = opts.artboards.clone().unwrap_or_else(|| (0..doc.artboards.len()).collect()); let filled = super::export::with_artboard_fills(doc, p, pages).map_err(|e| bad(cmd, e))?; let doc = &*filled; + // A page the file can't hold fails the export before the thumbnails and the flattening. + vectorcraft_pdf::check_page_sizes(doc, &opts).map_err(|e| pdf_error(cmd, e))?; if opts.settings.thumbnails { opts.thumbnails = thumbnails(doc, &opts).map_err(|e| pdf_error(cmd, e))?; } diff --git a/crates/engine/src/cmd/fileio/tests_pdfedit.rs b/crates/engine/src/cmd/fileio/tests_pdfedit.rs index 4a6f671432..2970238e38 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfedit.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfedit.rs @@ -187,6 +187,26 @@ fn an_ai_with_an_artboard_past_14400_pt_reopens_at_its_size() { assert_eq!(size(&s), (20_000.0, 10_000.0)); } +/// A page that a PDF 1.3 file can't hold (a side past 32,767 pt that isn't a whole number of +/// points) fails the export before the thumbnails, the editing data and the flattening: the editing data is never asked for, and the flattener options, which the +/// flattening would refuse, are never read. +#[test] +fn a_page_too_long_for_pdf_1_3_fails_before_the_flattening() { + let doc = vectorcraft_doc::Document::new(40_000.5, 300.0); + let p = json!({"compatibility": "1.3", "thumbnails": true, "preserveEditing": true, "flattener": {"balance": 500}}); + let asked = std::cell::Cell::new(false); + let native = || { + asked.set(true); + Ok(vec![]) + }; + let e = super::pdf::encode_carrying("document.exportPdf", &doc, &p, native, || Ok(None)).unwrap_err(); + assert!( + e.to_string().contains("PDF 1.3 files hold real numbers up to 32,767, and the page of artboard 1, 40001 pt long, needs larger ones"), + "{e}" + ); + assert!(!asked.get(), "the editing data is not made"); +} + #[test] fn ait_templates_open_their_document_untitled() { let mut s = rich(); diff --git a/crates/engine/src/cmd/opacitymask.rs b/crates/engine/src/cmd/opacitymask.rs index 9d81576b0a..75d5852ea2 100644 --- a/crates/engine/src/cmd/opacitymask.rs +++ b/crates/engine/src/cmd/opacitymask.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::{Document, Knockout, Node, NodeId, NodeKind, OpacityMask, S use super::maskedit::{begin, finish, mask_group, mask_parts, show_editing}; use super::pathops::{Beside, separate}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ids_param, ok, targets}; +use super::{CommandSpec, Result, Session, always, bad, cmd, has_doc, ids_param, ok, switch_or, targets}; use crate::EngineError; pub fn specs() -> Vec { @@ -246,8 +246,8 @@ fn make(s: &mut Session, p: &Value) -> Result { { return Err(bad(C, why)); } - let clip = bool_or(p, "clip", !s.menu.new_masks_unclipped); - let invert = bool_or(p, "invert", s.menu.new_masks_inverted); + let clip = switch_or(p, "clip", !s.menu.new_masks_unclipped, C)?; + let invert = switch_or(p, "invert", s.menu.new_masks_inverted, C)?; // Several objects: the top one is the mask. One: an empty mask, drawn in mask editing. let (art, mask_id) = if below.is_empty() { (&ids[..], None) } else { (below, Some(top)) }; // Several objects go into a new group, and a layer can't: the group takes a layer's art. @@ -330,8 +330,13 @@ fn release(s: &mut Session, p: &Value) -> Result { /// Set the mask flags given in `p` on the masked objects among `target`'s targets. fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result { - let get = |k: &str| p.get(k).and_then(Value::as_bool); - let (clip, invert, disabled, linked) = (get("clip"), get("invert"), get("disabled"), get("linked")); + let get = |k: &str| -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(_) => switch_or(p, k, false, "transparency.setOpacityMask").map(Some), + } + }; + let (clip, invert, disabled, linked) = (get("clip")?, get("invert")?, get("disabled")?, get("linked")?); if clip.is_none() && invert.is_none() && disabled.is_none() && linked.is_none() { return Err(bad("transparency.setOpacityMask", "give at least one of clip, invert, disabled, linked")); } @@ -363,7 +368,7 @@ fn set_flags(s: &mut Session, target: &Value, label: &str, p: &Value) -> Result< } fn toggle_new_clip(s: &mut Session, p: &Value) -> Result { - let v = bool_or(p, "value", s.menu.new_masks_unclipped); + let v = switch_or(p, "value", s.menu.new_masks_unclipped, "transparency.toggleNewMasksClipping")?; s.menu.new_masks_unclipped = !v; Ok(json!({ "value": v })) } @@ -376,7 +381,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result { } let d = &s.doc()?.doc; let cur = if knockout { d.page_knockout } else { d.page_isolate }; - let v = bool_or(p, "value", !cur); + let v = switch_or(p, "value", !cur, if knockout { "transparency.togglePageKnockoutGroup" } else { "transparency.togglePageIsolatedBlending" })?; if v != cur { s.edit(if knockout { "Page Knockout Group" } else { "Page Isolated Blending" }, |d, _| { *flag(d, knockout) = v; @@ -387,7 +392,7 @@ fn toggle_page(s: &mut Session, p: &Value, knockout: bool) -> Result { } fn toggle_new_invert(s: &mut Session, p: &Value) -> Result { - let v = bool_or(p, "value", !s.menu.new_masks_inverted); + let v = switch_or(p, "value", !s.menu.new_masks_inverted, "transparency.toggleNewMasksInverted")?; s.menu.new_masks_inverted = v; Ok(json!({ "value": v })) } diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index c18412c1da..a8306d25c7 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -16,8 +16,8 @@ use vectorcraft_pathops::{BoolOp, PathfinderOp}; use super::edit::selected_roots; use super::expand::{fill_shape, reshaped, seeded}; use super::{ - CommandSpec, EngineError, Result, Session, always, bad, bool_or, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, - number_or, str_param, switch_or, + CommandSpec, EngineError, Result, Session, always, bad, check_switches, checked_ids_or_selection, cmd, has_doc, has_selected_path, has_selection, + number_or, switch_or, text_param, }; pub fn specs() -> Vec { @@ -221,6 +221,25 @@ pub(crate) fn len_param(p: &Value, key: &str) -> Option { } } +/// The number `p` gives `cmd` for `key`, as [`num_param`] reads it, or `None` when `p` leaves it out +/// or gives null. Any other value, such as `true` or `"wide"`, is an error: "`{key}` must be a +/// number, not {v}". +pub(crate) fn number_given(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => num_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } +} + +/// The distance `p` gives `cmd` for `key`, as [`len_param`] reads it (`"5 mm"` included), or `None` +/// when `p` leaves it out or gives null. Any other value is an error, as [`number_given`] gives it. +pub(crate) fn length_given(p: &Value, key: &str, cmd: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => len_param(p, key).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a number, not {v}"))), + } +} + fn ids_json(ids: &[NodeId]) -> Value { json!({ "ids": ids.iter().map(|i| i.0).collect::>() }) } @@ -687,18 +706,19 @@ fn trap(s: &mut Session, p: &Value) -> Result { use vectorcraft_render::effects::trap::{TRAP_LABEL, TrapOptions, TrapSource, trap_appearance, traps}; const ID: &str = "object.pathfinder.trap"; let mut q = p.clone(); - if let Some(t) = len_param(p, "thickness") { + if let Some(t) = length_given(p, "thickness", ID)? { if !(po::TRAP_MIN_WIDTH..=po::TRAP_MAX_WIDTH).contains(&t) { return Err(bad(ID, "thickness must be from 0.01 to 5000 pt")); } q["thickness"] = json!(t); } - if num_param(p, "heightWidth").is_some_and(|v| !(1.0..=1000.0).contains(&v)) { + if number_given(p, "heightWidth", ID)?.is_some_and(|v| !(1.0..=1000.0).contains(&v)) { return Err(bad(ID, "heightWidth must be from 1 to 1000 %")); } - if num_param(p, "tintReduction").is_some_and(|v| !(0.0..=100.0).contains(&v)) { + if number_given(p, "tintReduction", ID)?.is_some_and(|v| !(0.0..=100.0).contains(&v)) { return Err(bad(ID, "tintReduction must be from 0 to 100 %")); } + check_switches(p, &["trapsWithProcessColor", "reverseTraps"], ID)?; // The effect-only settings stay at their defaults. if let Some(o) = q.as_object_mut() { o.remove("precision"); @@ -743,21 +763,23 @@ fn trap(s: &mut Session, p: &Value) -> Result { // ---------- Offset Path ---------- -fn join_param(p: &Value, key: &str) -> po::Join { - match str_param(p, key).map(str::to_ascii_lowercase).as_deref() { - Some("round") => po::Join::Round, - Some("bevel") => po::Join::Bevel, - _ => po::Join::Miter, +fn join_param(p: &Value, key: &str, cmd: &str) -> Result { + match text_param(p, key, cmd)?.map(str::to_ascii_lowercase).as_deref() { + None | Some("miter") => Ok(po::Join::Miter), + Some("round") => Ok(po::Join::Round), + Some("bevel") => Ok(po::Join::Bevel), + Some(_) => Err(bad(cmd, format!("`{key}` must be one of miter, round, bevel"))), } } fn offset_path(s: &mut Session, p: &Value) -> Result { - let delta = len_param(p, "offset").unwrap_or(10.0); + const C: &str = "object.path.offsetPath"; + let delta = length_given(p, "offset", C)?.unwrap_or(10.0); if delta.abs() > 1e5 { - return Err(bad("object.path.offsetPath", "offset out of range")); + return Err(bad(C, "offset out of range")); } - let join = join_param(p, "joins"); - let miter = num_param(p, "miterLimit").unwrap_or(4.0).clamp(1.0, 500.0); + let join = join_param(p, "joins", C)?; + let miter = number_given(p, "miterLimit", C)?.unwrap_or(4.0).clamp(1.0, 500.0); let roots = selected_roots(s)?; let ids = s.edit("Offset Path", |d, sel| { let (mut out, mut above) = (vec![], vec![]); @@ -1167,23 +1189,21 @@ pub fn auto_simplify_level(s: &Session) -> Result { } fn simplify(s: &mut Session, p: &Value) -> Result { + const C: &str = "object.path.simplify"; + let (auto, given_level, given_tolerance) = (switch_or(p, "auto", false, C)?, number_given(p, "level", C)?, length_given(p, "tolerance", C)?); + let corner_angle = number_given(p, "cornerAngle", C)?.unwrap_or(30.0).clamp(0.0, 180.0); + let (straight_lines, whole) = (switch_or(p, "straightLines", false, C)?, switch_or(p, "wholePaths", false, C)?); // With auto, the slider's level is Auto-Simplify's for the selection's size; otherwise it is the level given. - let level = if bool_or(p, "auto", false) { + let level = if auto { Some(auto_simplify_level(s)?) } else { - num_param(p, "level").map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL }) + given_level.map(|l| if l.is_finite() { l.round().clamp(0.0, 100.0) } else { po::SIMPLIFY_LEVEL }) }; let tolerance = match level { Some(l) => po::simplify_level_tolerance(l), - None => len_param(p, "tolerance").unwrap_or(1.0), + None => given_tolerance.unwrap_or(1.0), }; - let opts = po::SimplifyOptions { - tolerance: tolerance.clamp(1e-4, 1e4), - corner_angle_deg: num_param(p, "cornerAngle").unwrap_or(30.0).clamp(0.0, 180.0), - straight_lines: bool_or(p, "straightLines", false), - smooth: 0.0, - }; - let whole = bool_or(p, "wholePaths", false); + let opts = po::SimplifyOptions { tolerance: tolerance.clamp(1e-4, 1e4), corner_angle_deg: corner_angle, straight_lines, smooth: 0.0 }; // A path with segments direct-selected simplifies only their runs, and keeps those runs (and the // other anchors it had selected) direct-selected. let roots = selected_roots(s)?; @@ -1257,10 +1277,17 @@ fn grid_axis(p: &Value, n: f64, [size, gutter, total]: [&str; 3], extent: f64) - } fn split_into_grid(s: &mut Session, p: &Value) -> Result { - let rows = num_param(p, "rows").unwrap_or(2.0).round(); - let cols = num_param(p, "columns").unwrap_or(2.0).round(); + const C: &str = "object.path.splitIntoGrid"; + let rows = number_given(p, "rows", C)?.unwrap_or(2.0).round(); + let cols = number_given(p, "columns", C)?.unwrap_or(2.0).round(); if !(1.0..=500.0).contains(&rows) || !(1.0..=500.0).contains(&cols) { - return Err(bad("object.path.splitIntoGrid", "rows and columns must be 1..500")); + return Err(bad(C, "rows and columns must be 1..500")); + } + let add_guides = switch_or(p, "addGuides", false, C)?; + // Each distance [`grid_axis`] reads is a number, a string with a unit or null, checked before the + // selection, so a bad one is an error whatever is selected. + for key in ["height", "rowGutter", "totalHeight", "width", "columnGutter", "totalWidth", "gutter"] { + length_given(p, key, C)?; } let too_small = || EngineError::Other("Split Into Grid: select paths large enough for the grid".into()); // The selected paths, back to front: one grid over them all replaces them, where the topmost @@ -1281,7 +1308,7 @@ fn split_into_grid(s: &mut Session, p: &Value) -> Result { return Err(too_small()); } let mut edges: Vec<(bool, f64)> = Vec::new(); - if bool_or(p, "addGuides", false) { + if add_guides { // Row-major cells: the first row has the column edges, each row's first cell the row edges. let bounds = cells.iter().filter_map(PathData::bounds); edges.extend(bounds.clone().take(cols).flat_map(|c| [(true, c.x0), (true, c.x1)])); @@ -1316,9 +1343,10 @@ fn is_painted(a: &Appearance) -> bool { } fn clean_up(s: &mut Session, p: &Value) -> Result { - let stray = bool_or(p, "strayPoints", true); - let unpainted = bool_or(p, "unpaintedObjects", true); - let empty_text = bool_or(p, "emptyTextPaths", true); + const C: &str = "object.path.cleanUp"; + let stray = switch_or(p, "strayPoints", true, C)?; + let unpainted = switch_or(p, "unpaintedObjects", true, C)?; + let empty_text = switch_or(p, "emptyTextPaths", true, C)?; let found = { let d = &s.doc()?.doc; let mut v = vec![]; diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 1cd137bddb..d583f6fe34 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -88,6 +88,9 @@ pub fn describe(p: &Plugin) -> Value { if m.paint_output { v["paintOutput"] = json!(true); } + if !m.command_allowlist.is_empty() { + v["commandAllowlist"] = json!(m.command_allowlist); + } if !m.commands.is_empty() { let commands: Vec = m .commands @@ -258,6 +261,37 @@ impl FilterRun { self.plugin.run(&self.input, &self.params).map_err(err) } + /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the + /// session ([`FilterRun::run_with_calls`]). + pub fn calls(&self) -> bool { + !self.plugin.manifest().command_allowlist.is_empty() + } + + /// Runs the plug-in in `s`, making the command calls it asks for on the active document + /// ([`super::plugin_call::call`]) → its output. + fn run_calling(&self, s: &mut Session) -> Result> { + let may = self.plugin.manifest().permissions(); + let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); + let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); + self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + } + + /// Runs a plug-in that calls commands and applies its output: the calls and the output are one + /// undo step, and a run that fails changes nothing ([`super::plugin_call::transaction`]). + fn run_with_calls(self, s: &mut Session) -> Result { + let label = self.label(); + super::plugin_call::transaction(s, &label, |s| { + let output = self.run_calling(s)?; + self.finish(s, &output) + }) + } + + /// The name of its undo step: the plug-in's, or its command's. + fn label(&self) -> String { + let m = self.plugin.manifest(); + self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label) + } + /// Hands in `output`, which [`FilterRun::run`] returned: the next `plugin.run` that makes this /// same run (same plug-in, `ids` and parameters, the document unchanged) applies it instead of /// running the plug-in. Any other run drops it. @@ -277,9 +311,9 @@ impl FilterRun { return Err(not_granted(&m.name, Permission::State)); } let may_write = may.contains(&Permission::DocWrite); - let (inputs, parent) = (self.inputs, self.parent); // A command's undo step is named after the command. - let label = self.command.as_ref().map_or_else(|| m.name.trim_end_matches('…').to_string(), Command::shown_label); + let label = self.label(); + let (inputs, parent) = (self.inputs, self.parent); let ids = s.edit(&label, |d, sel| { let before = (!may_write).then(|| d.layers.clone()); let ids = objects::apply_output(d, &inputs, out.objects, parent, &admit_effects).map_err(err)?; @@ -316,6 +350,12 @@ fn run(s: &mut Session, p: &Value) -> Result { // An output handed in is for this run only (the app hands it in just before), whatever it does. let handed = s.plugin_output.take(); let r = FilterRun::prepare(s, p)?; + // One that calls commands runs here, where it can make them, on the document with any edit in + // progress committed. + if r.calls() { + let r = if super::plugin_call::settle(s)? { FilterRun::prepare(s, p)? } else { r }; + return r.run_with_calls(s); + } // Handed in for this very run (the app ran it in the background), it is what running the // plug-in again would return. let handed = handed.filter(|h| (h.serial, &h.input, &h.params) == (r.plugin.serial(), &r.input, &r.params)); @@ -463,6 +503,16 @@ pub(crate) fn run_command(s: &mut Session, id: &str, p: &Value) -> Result } }; let r = FilterRun::prepare_with(s, plugin, Some(command), id, p)?; + if r.calls() { + let r = match super::plugin_call::settle(s)? { + true => { + let (plugin, command) = command_of(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?; + FilterRun::prepare_with(s, plugin, Some(command), id, p)? + } + false => r, + }; + return r.run_with_calls(s).map_err(failed); + } let output = r.run().map_err(&failed)?; r.finish(s, &output).map_err(failed) } @@ -654,6 +704,16 @@ fn install(s: &mut Session, p: &Value) -> Result { "`grant` and `allowHeavy` take effect only in a session started with --allow-plugin-grants: approve the plug-in in the desktop app", )); } + // A plug-in never calls a command no plug-in may call, whatever its manifest lists. + let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest()); + if let Some(id) = refused.first() { + let (name, id) = ( + permissions::display_text(&plugin.manifest().name, permissions::MAX_SHOWN_NAME), + permissions::display_text(id, permissions::MAX_SHOWN_FIELD), + ); + return Err(bad(C, format!("“{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call"))); + } + let unknown: Vec = unknown.into_iter().map(str::to_string).collect(); // A heavy plug-in is installed once a person agrees. if plugin.manifest().budget == Budget::Heavy && !allow_heavy { let (minutes, times) = vectorcraft_plugins::heavy_terms(); @@ -726,7 +786,11 @@ fn install(s: &mut Session, p: &Value) -> Result { if changed { s.store_disabled_plugins(); } - Ok(describe_installed(®istry::install(plugin))) + let mut v = describe_installed(®istry::install(plugin)); + if !unknown.is_empty() { + v["unknownCommands"] = json!(unknown); + } + Ok(v) } /// `plugin.inspect`: what installing the module would install, without installing it, whether that @@ -737,6 +801,13 @@ fn inspect(s: &mut Session, p: &Value) -> Result { let mut v = describe(&plugin); v["needsApproval"] = json!(!s.plugin_approved(&plugin)); v["needsReplace"] = json!(takes_over(s, &plugin)); + let (unknown, refused) = super::plugin_call::check_allowlist(plugin.manifest()); + if !unknown.is_empty() { + v["unknownCommands"] = json!(unknown); + } + if !refused.is_empty() { + v["refusedCommands"] = json!(refused); + } v }) } @@ -971,7 +1042,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), 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}]} | null, safeMode: bool (no plug-in loads or runs, see plugin.safeMode), disabled: [{id, file, name, label}] (turned off for the next launch, see plugin.setEnabled)}", + "{} → {plugins: [{id, name, version, kind: \"filter\"|\"effect\"|\"exporter\"|\"importer\", author, description, params (doc), paramsSchema, effect? (the effect id of a live effect: plugin.), format? and extensions? (an exporter's or importer's format id, plugin., for document.export or document.open's importer, and its file extensions), budget?: \"heavy\" (a filter that may compute for longer, see plugin.install's allowHeavy), inputs?: [\"type\"|\"image\"|\"symbolInstance\"] (the objects besides paths a filter reads, see plugin.run), size, source, permissions: [name] (what it may do: the ones its manifest lists, else the ones its kind implies; progress: it may report its progress, see Cancel and write log lines; settings: it may keep settings of its own; cache: it may keep a cache of its own; commands: a filter may run the commands its commandAllowlist names, see docs/plugins.md), commandAllowlist?: [command id] (the commands a filter with the commands permission may run while it runs, with vc_call), hash (the module's SHA-256), api (the plug-in API level it was built for, 1 or 2), paintOutput?: true (a live effect whose pieces have paints of their own, see docs/plugins.md), cacheBytes (the bytes its cache holds; see plugin.clearCache), commands?: [{id, command (its command id, plugin.., which runs it), label, params (doc), paramsSchema}] (the menu commands a filter or live effect adds)}], folder: the Additional Plug-ins Folder load report {folder, loaded, failed: [{file, error}]} | null, 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 ), @@ -989,7 +1060,7 @@ pub fn specs() -> Vec { "Run Plug-in", [], None, - "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer) → {plugin, ids}", + "{id, params?: {…} (the plug-in's parameters; or give them as top-level keys; missing ones take their defaults, see plugin.info), ids?: [object id] (left out or null: the selection), …the plug-in's parameters as top-level keys} run an object filter on the selected paths and compound paths (inside selected groups and layers too; hidden, locked, guide and clipping paths, compound paths that clip a clip group and paths inside a group that clips one are left out): it may change, delete or add objects, as one undo step; the result is selected, except the objects it locked or made guides. A filter whose manifest lists inputs (type, image, symbolInstance; it lists doc.read in permissions, so plugin.install needs grant) is also given the selected objects of those kinds to read, in paint order from the bottom, with at most 16 MiB of pixels and 16 MiB of type runs per run (an object that doesn't fit what the objects before it left comes with pixelsOmitted or truncated; an image that reaches the decoder counts toward the pixels even when decoding fails); every object counts toward the input's half of the plug-in's memory cap, ids, bounds, transforms and names included, and an object whose fields besides its pixels and runs don't fit fails the run with a memory-budget error naming it and its size (a path or compound path fails it with the memory-budget error for a selection too large to hand over), and more than 100,000 of these objects fail it with an object-budget error: its output returns each as {id} or exactly as given, or the run is refused and nothing changes. With nothing selected it gets no objects (generators add theirs to the current layer). A filter with a commandAllowlist runs the commands it names while it runs (vc_call, see docs/plugins.md): its calls and its output are one undo step, and a run that fails or makes a call that fails changes nothing → {plugin, ids}", has_doc, run ), @@ -998,7 +1069,7 @@ pub fn specs() -> Vec { "Install Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session → its plugin.list entry", + "{path: a .wasm file (desktop) | dataBase64: the module (+ name?: shown as its source), replace?: bool (true once the user agreed: a module with other bytes than the plug-in installed with its id, or with none installed, one whose id has settings or a cache in the plug-in store, installs only with it, takes that plug-in's place and gets its settings and cache; false: one whose id is installed is refused; left out, the same module installs again), name?: file name (with dataBase64), allowHeavy?: bool (a filter whose manifest asks for a heavy budget, budget \"heavy\" in plugin.inspect, installs only with it), grant?: [permission] (a plug-in whose manifest lists permissions, needsApproval in plugin.inspect, installs only when grant holds every one of them; the grant is recorded with the module's hash and covers only that module, so a module with other bytes needs a new grant even when it lists the same permissions; installing a module that lists no permissions forgets the grant held for its id; a refused install keeps the grant, a failed write of the module to the plug-in store leaves the grant in the store, and a stored module that is disabled or not read in Safe Mode keeps the grant for its id; with a plug-in store attached, only the grants kept there count; a request's allowHeavy and grant are refused unless the session was started with vectorcraft-cli --allow-plugin-grants: in the desktop app a person approves the install, see ui.installPlugin, and a module whose hash is already recorded, by a person's approval or by a grant accepted under that flag, needs no grant), hash?: string (the module's SHA-256 as plugin.inspect gave it: a module with other bytes is refused)} validate and install a WebAssembly plug-in for this session (a module whose commandAllowlist names a command no plug-in may call, such as one that reads or writes files, is refused) → its plugin.list entry, plus unknownCommands?: [id] (commandAllowlist ids no command has; a call of one fails)", always, install ), @@ -1007,7 +1078,7 @@ pub fn specs() -> Vec { "Inspect Plug-in", [], None, - "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true)", + "{path: a .wasm file (desktop) | dataBase64: the module, name?: the file name shown as its source (with dataBase64)} validate a WebAssembly plug-in without installing it → the plugin.list entry it would have, plus needsApproval: bool (true when it lists permissions no person has granted this very module, its bytes included: it then needs a person's approval, see plugin.install) and needsReplace: bool (true when it would take the place of another module with its id: plugin.install then needs replace: true), unknownCommands?: [id] (commandAllowlist ids no command has) and refusedCommands?: [id] (commandAllowlist ids no plug-in may call: plugin.install refuses the module)", always, inspect ), diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs new file mode 100644 index 0000000000..b151adcea2 --- /dev/null +++ b/crates/engine/src/cmd/plugin_call.rs @@ -0,0 +1,577 @@ +//! Commands a filter plug-in calls with `vc_call` ([`vectorcraft_plugins::host`]): which commands a +//! plug-in may never call ([`denied`]), the call itself ([`call`]), and the run around the calls +//! ([`transaction`]). +//! +//! A filter whose manifest's `commandAllowlist` names commands runs on the session's thread. Each +//! call it makes runs that command on the document the run is for, through [`Session::execute`] with +//! its params checked as any request's are, and sees the selection the calls before it left. The +//! calls and the filter's output are one undo step, named after the plug-in or its command; a run +//! that fails, traps, runs out of budget or is canceled, or makes a call that fails, leaves every +//! document, its selection and its history as they were. +//! +//! A plug-in never calls a command that reads or writes a file or folder, uses the clipboard, +//! changes preferences, runs a script, an action or a plug-in (a plug-in command, or an effect a +//! plug-in adds), opens, closes or switches documents, or undoes or redoes, whatever its manifest +//! lists. A command whose params name a file or folder is refused unless [`NOT_FILES`] says that +//! key names part of the document in it, and so is a call whose arguments carry such a key at any +//! depth ([`names_file`]); a call runs with no file or folder readable or writable +//! ([`execute_confined`]). Every other command is refused too unless +//! [`reviewed::ALLOWED`] lists it, so a command added to the registry later is refused until +//! someone decides. + +mod reviewed; + +use std::sync::Arc; + +use serde_json::Value; +use vectorcraft_plugins::host::{CALL_COMMAND_FAILED, CALL_DENIED_COMMAND, CALL_DISABLED, CALL_UNKNOWN_COMMAND, CallFailure}; + +use super::CommandSpec; +use crate::{EngineError, Result, Session}; + +/// Command ids a plug-in may never call, by their start: plug-ins, scripts and actions, files, +/// documents and links, the clipboard, preferences, the view and the app, and the undo history. +const DENIED_PREFIXES: &[&str] = &[ + "plugin.", + "script.", + "action.", + "actionSet.", + "command.", + "prefs.", + "help.", + "engine.", + "file.", + "document.", + "addon.document.", + "library.", + "links.", + "recovery.", + "shortcutSet.", + "clipboard.", + "view.", + "print.", + "pdf.", + "webExport.", + "css.", + "assets.", + "importMatches.", + "edit.undo", + "edit.redo", + "edit.clearHistory", + "edit.copy", + "edit.cut", + "edit.paste", + "edit.newDocument", + "edit.colorSettings", + "edit.dropSelection", + "artboard.copy", + "artboard.cut", + "text.rescanFonts", + "text.fontList", + "text.spelling.", + "colorTheme.", + "magicWand.", + "eyedropper.", + "layer.pasteRemembersLayers", + "type.systemLayout", + "type.fractionalWidths", + "appearance.setNewArtBasic", + "appearance.newArt", + "perspective.widget", + "transparency.toggleNewMasks", +]; + +/// Words in a command id that name a file or the clipboard (any case): a command with one of them +/// in its id may read or write a file a plug-in can't see. +const FILE_WORDS: &[&str] = &[ + "export", + "import", + "save", + "load", + "open", + "file", + "folder", + "link", + "librar", + "preset", + "recover", + "package", + "print", + "profile", + "clipboard", +]; + +/// Param keys that name a file or a folder. +const FILE_KEYS: &[&str] = &["path", "paths", "file", "files", "folder", "folders", "dir", "directory", "destinationFolder", "sourceFolder", "url"]; + +/// Commands and the param key in [`FILE_KEYS`] that, in them, names part of the document (a path of +/// its art, a setting, an attribute it stores or a result field), not a file. +pub(crate) const NOT_FILES: &[(&str, &str)] = &[ + ("object.setLiveShape", "path"), + ("path.reverse", "paths"), + ("object.pathfinder.options", "paths"), + ("object.maskImage", "path"), + ("text.createInPath", "path"), + ("imageTrace.make", "paths"), + ("symbol.instance.setAppearance", "path"), + ("symbol.instance.selectPart", "path"), + ("object.objectsOnPath.attach", "path"), + ("attributes.set", "url"), + ("svgInteractivity.info", "files"), + ("addon.cleanup.rejoin", "paths"), +]; + +/// Is command id `id` one a plug-in may never call, from its id alone ([`DENIED_PREFIXES`], +/// [`FILE_WORDS`])? +fn denied_id(id: &str) -> bool { + let lower = id.to_ascii_lowercase(); + DENIED_PREFIXES.iter().any(|p| id.starts_with(p)) || FILE_WORDS.iter().any(|w| lower.contains(w)) +} + +/// Why a plug-in may never call `spec`, or `None` when it may (when its manifest lists it): its id +/// or a file key ([`denied_by_rule`]), [`reviewed::DENIED`], or no place in [`reviewed::ALLOWED`]. +pub(crate) fn denied(spec: &CommandSpec) -> Option<&'static str> { + if let Some(why) = denied_by_rule(spec) { + return Some(why); + } + if reviewed::DENIED.binary_search(&spec.id).is_ok() { + return Some("reviewed"); + } + if reviewed::ALLOWED.binary_search(&spec.id).is_err() { + return Some("not reviewed"); + } + None +} + +/// Why a plug-in may never call `spec` from its id ([`denied_id`]) or its params (a key in +/// [`FILE_KEYS`] that [`NOT_FILES`] doesn't name for it), or `None`. +fn denied_by_rule(spec: &CommandSpec) -> Option<&'static str> { + let id = spec.id; + if denied_id(id) { + return Some("id"); + } + let mut keys = FILE_KEYS.iter().filter(|k| !NOT_FILES.contains(&(id, **k))); + let in_schema = |k: &str| spec.schema.is_some_and(|s| s.params.iter().any(|p| p.name == k)); + if keys.any(|k| names_key(spec.params, k) || in_schema(k)) { + return Some("file key"); + } + None +} + +/// The ids `m`'s `commandAllowlist` names that no command has (a later version may add them; a +/// call of one fails), and those a plug-in may never call ([`denied`]). +pub(crate) fn check_allowlist(m: &vectorcraft_plugins::Manifest) -> (Vec<&str>, Vec<&str>) { + let (mut unknown, mut refused) = (Vec::new(), Vec::new()); + for id in &m.command_allowlist { + match super::find_command(id) { + Some(spec) if denied(spec).is_some() => refused.push(id.as_str()), + Some(_) => {} + None if denied_id(id) => refused.push(id.as_str()), + None => unknown.push(id.as_str()), + } + } + (unknown, refused) +} + +/// Does params text `text` name the key `key`: `key:` or `key?:`, not as the end of a longer word? +pub(crate) fn names_key(text: &str, key: &str) -> bool { + text.match_indices(key).any(|(at, _)| { + let before = text[..at].chars().next_back(); + let after = &text[at + key.len()..]; + before.is_none_or(|c| !(c.is_alphanumeric() || c == '_' || c == '.')) && (after.starts_with(':') || after.starts_with("?:")) + }) +} + +/// Does `args`, the arguments of a call of command `id`, carry a key in [`FILE_KEYS`] at any depth +/// (in objects and in arrays), such as an effect's `textureImage.path`? Only a key [`NOT_FILES`] +/// names for `id`, at the top level, isn't counted. The walk keeps its own stack, so deep +/// arguments can't overflow the thread's. +fn names_file(id: &str, args: &Value) -> bool { + let mut stack = vec![(args, true)]; + while let Some((v, top)) = stack.pop() { + match v { + Value::Array(a) => stack.extend(a.iter().map(|x| (x, false))), + Value::Object(o) => { + for (k, x) in o { + let k = k.as_str(); + if FILE_KEYS.contains(&k) && !(top && NOT_FILES.contains(&(id, k))) { + return true; + } + stack.push((x, false)); + } + } + _ => {} + } + } + false +} + +/// Param keys whose value names an effect or a command (`id` is `effect.apply`'s other name for +/// `effect`). +const PLUGIN_KEYS: &[&str] = &["effect", "effects", "id", "command", "commands"]; + +/// Does `v` name a plug-in anywhere: an effect or a command ([`PLUGIN_KEYS`]) whose id starts with +/// `plugin.`, at any depth? A call that does is refused, so a plug-in never runs another, or +/// itself. Other strings, such as text, may start with `plugin.`. +fn names_plugin(v: &Value) -> bool { + names_plugin_in(v, false) +} + +/// [`names_plugin`] for `v`, the value of a key in [`PLUGIN_KEYS`] (or an item of one) when +/// `named`. +fn names_plugin_in(v: &Value, named: bool) -> bool { + match v { + Value::String(s) => named && s.starts_with(vectorcraft_plugins::PREFIX), + Value::Array(a) => a.iter().any(|x| names_plugin_in(x, named)), + Value::Object(o) => o.iter().any(|(k, x)| names_plugin_in(x, PLUGIN_KEYS.contains(&k.as_str()))), + _ => false, + } +} + +/// Commits an edit in progress in the active document (not a preview's), as [`transaction`] does → +/// whether that changed the document or its selection. A run that calls commands is prepared again +/// then, so its input is the document its calls change. +pub(crate) fn settle(s: &mut Session) -> Result { + if s.previewing { + return Ok(false); + } + let Some(before) = s.active().map(|d| (d.doc.clone(), d.selection.clone())) else { return Ok(false) }; + super::edit::settle_interaction(s)?; + Ok(s.active().is_none_or(|d| !Arc::ptr_eq(&before.0, &d.doc) || before.1 != d.selection)) +} + +/// What a run that makes command calls keeps fixed: the document it runs in, the documents open, +/// whether an interaction holds its changes (its own, or a preview's), and whether the plug-in may +/// read and change the document. +pub(crate) struct Calls { + document: Option, + open: Vec, + interaction: bool, + may_read: bool, + may_write: bool, +} + +impl Calls { + /// The run's fixed state in `s` as it is now; `may_read` and `may_write` are whether it has + /// `doc.read` and `doc.write`. + pub(crate) fn of(s: &Session, may_read: bool, may_write: bool) -> Calls { + let (document, open) = (s.active().map(|d| d.uid), s.docs.iter().map(|d| d.uid).collect()); + Calls { document, open, interaction: s.in_interaction(), may_read, may_write } + } + + /// Is `s` still as the run needs it: the same documents open, the same one active and the + /// interaction holding the run's changes still open? + fn kept(&self, s: &Session) -> bool { + s.active().map(|d| d.uid) == self.document + && s.docs.iter().map(|d| d.uid).eq(self.open.iter().copied()) + && (!self.interaction || s.in_interaction()) + } +} + +/// Makes plug-in call `id` with `args` in `s` → its result, or why it didn't run or failed. A +/// command a plug-in may never call ([`denied`]), one whose args name a plug-in, one that changes +/// which documents are open or active or ends the run's edit, and one that changes the document for +/// a plug-in without `doc.write` are refused, and so is every call of a plug-in without `doc.read`: +/// a command's result describes the document. +pub(crate) fn call(s: &mut Session, run: &Calls, id: &str, args: &Value) -> std::result::Result { + let refused = || CallFailure { code: CALL_DENIED_COMMAND, why: EngineError::Other("a plug-in may not call this command".into()).to_string() }; + if !run.may_read { + return Err(refused()); + } + let Some(spec) = super::find_command(id) else { + return Err(CallFailure { code: CALL_UNKNOWN_COMMAND, why: super::params::unknown_command(id).to_string() }); + }; + if denied(spec).is_some() || names_plugin(args) || names_file(id, args) { + return Err(refused()); + } + let before = s.active().map(|d| d.doc.clone()); + let r = execute_confined(s, id, args); + let value = match r { + Ok(v) => v, + Err(e @ EngineError::Disabled(..)) => return Err(CallFailure { code: CALL_DISABLED, why: e.to_string() }), + Err(e) => return Err(CallFailure { code: CALL_COMMAND_FAILED, why: e.to_string() }), + }; + let changed = before.is_some_and(|b| s.active().is_some_and(|d| !Arc::ptr_eq(&b, &d.doc))); + if !run.kept(s) || (changed && !run.may_write) { + return Err(refused()); + } + Ok(value) +} + +/// Runs command `id` with `args` in `s` with no file or folder readable or writable: every path the +/// command reaches through the checked file access ([`crate::file_access`]) is refused, whatever +/// param carries it. +fn execute_confined(s: &mut Session, id: &str, args: &Value) -> Result { + crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || s.execute(id, args)) +} + +/// Runs `f`, a plug-in run that makes command calls, as one undo step named `label` in the active +/// document: the commands it calls and the output it applies change the document inside one +/// interaction, which is kept when `f` succeeds. When `f` fails, every document goes back to how it +/// was (its art, selection, interaction and history), and so does the session state the commands a +/// plug-in may call change ([`Saved`]). During a preview the preview's own interaction holds the +/// changes. A trace handed in for the next Image Trace is set aside while `f` runs, so a call +/// traces anew, and handed back after; the next Image Trace still checks it was made of its inputs. +pub(crate) fn transaction(s: &mut Session, label: &str, f: impl FnOnce(&mut Session) -> Result) -> Result { + if s.active().is_some() && !s.previewing { + super::edit::settle_interaction(s)?; + } + let own = s.active().is_some() && !s.previewing && !s.in_interaction(); + if own { + s.begin_interaction(label)?; + } + let saved = Saved::of(s); + let start = s.docs.clone(); + let active = s.active; + let trace = s.trace_hand_off.take(); + let r = f(s); + s.trace_hand_off = trace; + match r { + Ok(v) => { + if own + && let Some(st) = s.active_mut() + && let Some(it) = st.interaction.take() + { + st.keep_interaction(it); + } + Ok(v) + } + Err(e) => { + let open = std::mem::replace(&mut s.docs, start); + for st in &mut s.docs { + // Past the newest revision the document reached, so the restored one redraws. + let newest = open.iter().filter(|d| d.uid == st.uid).map(|d| d.revision).max().unwrap_or(st.revision); + st.revision = newest.max(st.revision).saturating_add(1); + crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection); + } + s.active = active; + if own && let Some(st) = s.active_mut() { + st.interaction = None; + } + saved.restore(s); + Err(e) + } + } +} + +/// The session state outside the documents that a command a plug-in may call changes: the paint +/// defaults and the colors it remembers, the drawing mode, the clipboard, the undo group, the +/// preferences and menu checks, the selected gradient stop, mesh point and Appearance item, and the +/// options a command keeps for its next run. [`transaction`] puts it back when a run fails. +struct Saved { + paint: crate::PaintDefaults, + fill_active: bool, + draw_mode: crate::DrawMode, + draw_inside: Option, + clipboard: crate::Clipboard, + untitled_counter: u32, + explicit_undo_group: Option>, + prefs: crate::Prefs, + menu: super::menucmds::MenuState, + gradient_stop: Option<(usize, super::gradient::StopOwner)>, + freeform_point: Option<(usize, super::gradient::StopOwner)>, + active_appearance_item: Option, + eyedropper_sample: Option>, + last_solid: vectorcraft_color::Color, + last_gradient: vectorcraft_color::GradientPaint, + recent_colors: Vec, + recent_urls: Vec, + global_edit_options: super::globaledit::Options, + envelope_defaults: Option<(vectorcraft_doc::live::EnvelopeOptions, f64)>, +} + +impl Saved { + fn of(s: &Session) -> Saved { + Saved { + paint: s.paint.clone(), + fill_active: s.fill_active, + draw_mode: s.draw_mode, + draw_inside: s.draw_inside, + clipboard: s.clipboard.clone(), + untitled_counter: s.untitled_counter, + explicit_undo_group: s.explicit_undo_group.clone(), + prefs: s.prefs.clone(), + menu: s.menu.clone(), + gradient_stop: s.gradient_stop, + freeform_point: s.freeform_point, + active_appearance_item: s.active_appearance_item.clone(), + eyedropper_sample: s.eyedropper_sample.clone(), + last_solid: s.last_solid, + last_gradient: s.last_gradient.clone(), + recent_colors: s.recent_colors.clone(), + recent_urls: s.recent_urls.clone(), + global_edit_options: s.global_edit_options.clone(), + envelope_defaults: s.envelope_defaults, + } + } + + fn restore(self, s: &mut Session) { + s.paint = self.paint; + s.fill_active = self.fill_active; + s.draw_mode = self.draw_mode; + s.draw_inside = self.draw_inside; + s.clipboard = self.clipboard; + s.untitled_counter = self.untitled_counter; + s.explicit_undo_group = self.explicit_undo_group; + s.prefs = self.prefs; + s.menu = self.menu; + s.gradient_stop = self.gradient_stop; + s.freeform_point = self.freeform_point; + s.active_appearance_item = self.active_appearance_item; + s.eyedropper_sample = self.eyedropper_sample; + s.last_solid = self.last_solid; + s.last_gradient = self.last_gradient; + s.recent_colors = self.recent_colors; + s.recent_urls = self.recent_urls; + s.global_edit_options = self.global_edit_options; + s.envelope_defaults = self.envelope_defaults; + s.pending_paint = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every command in the registry is sorted: the ones a plug-in may call name no file, folder, + /// clipboard, preference or script in their params text, and the known file, document, script + /// and history commands are refused. + #[test] + fn every_command_is_sorted() { + let specs = crate::cmd::command_specs(); + for id in [ + "document.save", + "file.revert", + "document.serialize", + "links.update", + "graphicStyle.libraries", + "symbol.libraries", + "brush.libraries", + "text.findFontFiles", + "plugin.run", + "plugin.install", + "command.batch", + "edit.undo", + "edit.redo", + "edit.copy", + "edit.paste", + "prefs.set", + ] { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert!(denied(spec).is_some(), "{id} is allowed"); + } + for id in ["select.all", "object.transform", "path.reverse", "symbol.instance.selectPart"] { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert_eq!(denied(spec), None, "{id} is refused"); + } + for (id, key) in NOT_FILES { + let Some(spec) = crate::cmd::find_command(id) else { panic!("no command {id}") }; + assert!(names_key(spec.params, key), "{id} has no `{key}` param"); + } + let leaks: Vec<&str> = specs + .iter() + .filter(|c| denied(c).is_none()) + .filter(|c| { + let lower = c.id.to_ascii_lowercase(); + FILE_WORDS.iter().any(|w| lower.contains(w)) + || FILE_KEYS.iter().any(|k| names_key(c.params, k) && !NOT_FILES.contains(&(c.id, *k))) + || names_key(c.params, "sourceDocument") + }) + .map(|c| c.id) + .collect(); + assert!(leaks.is_empty(), "allowed commands that name a file or another document: {leaks:?}"); + let allowed = specs.iter().filter(|c| denied(c).is_none()).count(); + assert!(allowed > 0 && allowed < specs.len()); + } + + /// Every command no rule refuses is in exactly one of [`reviewed::ALLOWED`] and + /// [`reviewed::DENIED`], and they name only such commands, in order: a command added to the + /// registry fails here until someone puts it in one. + #[test] + fn every_command_is_reviewed() { + for list in [reviewed::ALLOWED, reviewed::DENIED] { + assert!(list.windows(2).all(|w| w[0] < w[1]), "a reviewed list is out of order or names a command twice"); + } + let (allowed, refused) = (|id: &str| reviewed::ALLOWED.binary_search(&id).is_ok(), |id: &str| reviewed::DENIED.binary_search(&id).is_ok()); + let unreviewed: Vec<&str> = + crate::cmd::command_specs().iter().filter(|c| denied_by_rule(c).is_none() && allowed(c.id) == refused(c.id)).map(|c| c.id).collect(); + assert!(unreviewed.is_empty(), "commands in neither or both of reviewed::ALLOWED and reviewed::DENIED: {unreviewed:?}"); + let stale: Vec<&str> = reviewed::ALLOWED + .iter() + .chain(reviewed::DENIED) + .copied() + .filter(|id| crate::cmd::find_command(id).is_none_or(|c| denied_by_rule(c).is_some())) + .collect(); + assert!(stale.is_empty(), "reviewed commands that no command has or a rule refuses: {stale:?}"); + } + + /// Only an effect or a command naming a plug-in counts, at any depth; text that happens to + /// start with `plugin.` doesn't. + #[test] + fn a_plugin_is_named_only_as_an_effect_or_a_command() { + use serde_json::json; + assert!(names_plugin(&json!({"effect": "plugin.test.fx"}))); + assert!(names_plugin(&json!({"id": "plugin.test.fx"}))); + assert!(names_plugin(&json!({"effects": ["builtin.blur", "plugin.test.fx"]}))); + assert!(names_plugin(&json!({"items": [{"effect": "plugin.test.fx", "params": {}}]}))); + assert!(names_plugin(&json!({"command": "plugin.test.run"}))); + assert!(!names_plugin(&json!({"text": "plugin.example"}))); + assert!(!names_plugin(&json!({"name": "plugin.style", "effect": "drop-shadow"}))); + assert!(!names_plugin(&json!({"effect": {"name": "plugin.style"}}))); + } + + /// A file or folder key counts at any depth, in objects and in arrays; a key [`NOT_FILES`] names + /// for the command only at the top level; ordinary nested params don't count. + #[test] + fn a_file_key_counts_at_any_depth() { + use serde_json::json; + let texture = json!({"effect": "distort.glass", "params": {"textureImage": {"path": "/tmp/t.png"}}}); + assert!(names_file("effect.apply", &texture)); + assert!(names_file("effect.setParams", &texture)); + assert!(names_file("effect.apply", &json!({"params": {"layers": [{"name": "a"}, {"folder": "/tmp"}]}}))); + assert!(names_file("select.all", &json!([[[{"url": "file:///etc/hosts"}]]]))); + assert!(!names_file("effect.apply", &json!({"effect": "distort.glass", "params": {"distortion": 5, "textureImage": "frosted"}}))); + assert!(!names_file("object.move", &json!({"dx": 5, "dy": 0, "ids": [1, 2], "opts": {"copy": false}}))); + // `path` is a shape's path in object.setLiveShape, but only as its own param. + assert!(!names_file("object.setLiveShape", &json!({"path": [[0, 0], [1, 1]]}))); + assert!(names_file("object.setLiveShape", &json!({"options": {"path": "/tmp/x"}}))); + assert!(names_file("object.move", &json!({"path": [[0, 0]]}))); + // Deep nesting is walked without recursion. + let mut deep = json!({"file": "/tmp/x"}); + for _ in 0..10_000 { + deep = Value::Array(vec![deep]); + } + assert!(names_file("select.all", &deep)); + std::mem::forget(deep); + } + + /// A call reads no file even when a param the checks above don't know carries its path: the + /// command runs with no file readable. Run as an ordinary request, the same texture loads. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_confined_call_reads_no_file() { + use serde_json::json; + let file = std::env::temp_dir().join(format!("vc-plugin-call-texture-{}.png", std::process::id())); + let png = vectorcraft_trace::Raster::from_fn(8, 8, |x, y| if (x + y) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }).encode_png(); + std::fs::write(&file, png).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let p = json!({"effect": "distort.glass", "params": {"textureImage": {"path": file.to_string_lossy()}}}); + let e = execute_confined(&mut s, "effect.apply", &p).map(|_| ()).unwrap_err().to_string(); + let read = s.execute("effect.apply", &p).map(|_| ()); + let _ = std::fs::remove_file(&file); + assert!(e.contains("read authority is absent"), "{e}"); + read.unwrap(); + } + + #[test] + fn keys_are_found_as_whole_keys() { + assert!(names_key("{path: a .wasm file}", "path")); + assert!(names_key("{ids?: [id], path?: string}", "path")); + assert!(!names_key("{subpath: 1}", "path")); + assert!(!names_key("{x} on the path: the art", "the")); + assert!(!names_key("{pathData: 1}", "path")); + assert!(names_key("path: x", "path")); + } +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs new file mode 100644 index 0000000000..7759a57f00 --- /dev/null +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -0,0 +1,675 @@ +//! The commands no rule in [`super::denied`] refuses, each placed in one list: those a plug-in may +//! call ([`ALLOWED`]) and those it may not ([`DENIED`]). A command in neither is refused, and the +//! test `every_command_is_reviewed` fails until it is placed. + +/// Commands a plug-in may call when its manifest lists them, in order. +pub(super) const ALLOWED: &[&str] = &[ + "addon.arrange.grid", + "addon.arrange.groupOverlapping", + "addon.arrange.randomizeOpacity", + "addon.arrange.replace", + "addon.arrange.size", + "addon.arrange.sort", + "addon.arrange.swap", + "addon.cleanup.alignInPlace", + "addon.cleanup.breakText", + "addon.cleanup.check", + "addon.cleanup.combineText", + "addon.cleanup.deepUngroup", + "addon.cleanup.fix", + "addon.cleanup.joinText", + "addon.cleanup.rejoin", + "addon.cleanup.removeBreaks", + "addon.cleanup.replaceFonts", + "addon.cleanup.resetTextTransform", + "addon.cleanup.show", + "addon.cleanup.simplify", + "addon.color.applyNearestSwatch", + "addon.color.fillToStroke", + "addon.color.filter", + "addon.color.nearestSwatch", + "addon.color.select", + "addon.color.strokeToFill", + "addon.color.swatchLegend", + "addon.contour.set", + "addon.pathtools.addPoints", + "addon.pathtools.close", + "addon.pathtools.corner", + "addon.pathtools.cornerRemove", + "addon.pathtools.cornerSet", + "addon.pathtools.crossings", + "addon.pathtools.divideDashes", + "addon.pathtools.equalize", + "addon.pathtools.erase", + "addon.pathtools.expandDashes", + "addon.pathtools.extend", + "addon.pathtools.inspect", + "addon.pathtools.mergeEdge", + "addon.pathtools.removeKeepShape", + "addon.pathtools.setAnchor", + "addon.pathtools.shape.convert", + "addon.pathtools.shape.create", + "addon.pathtools.shape.set", + "addon.pathtools.slideAnchor", + "addon.pathtools.smooth", + "addon.pen.append", + "addon.pen.close", + "addon.pen.closeJoin", + "addon.pen.removePoint", + "addon.pen.reshape", + "addon.pen.segment", + "addon.pen.togglePoint", + "addon.select.byArtboards", + "addon.shapes.box3d", + "addon.shapes.configure", + "addon.shapes.ellipse", + "addon.shapes.polygon", + "addon.shapes.rectangle", + "addon.shapes.spiral", + "addon.shapes.star", + "addon.type.releasePath", + "addon.type.textTweaker", + "appearance.addEffect", + "appearance.addFill", + "appearance.addStroke", + "appearance.clear", + "appearance.copyFrom", + "appearance.duplicateItem", + "appearance.moveItem", + "appearance.reduceToBasic", + "appearance.removeItem", + "appearance.setActiveItem", + "appearance.setItem", + "appearance.showAllHidden", + "appearance.targetContents", + "appearance.transfer", + "artboard.convertToArtboards", + "artboard.delete", + "artboard.deleteEmpty", + "artboard.duplicate", + "artboard.fitToArt", + "artboard.fitToSelection", + "artboard.move", + "artboard.new", + "artboard.rearrange", + "artboard.rename", + "artboard.reorder", + "artboard.setProps", + "artboard.switchOrientation", + "attributes.info", + "attributes.set", + "brush.apply", + "brush.delete", + "brush.duplicate", + "brush.freehand", + "brush.get", + "brush.list", + "brush.move", + "brush.new", + "brush.options", + "brush.remove", + "brush.selectionArt", + "brush.setCurrent", + "brush.unused", + "charStyle.apply", + "charStyle.delete", + "charStyle.duplicate", + "charStyle.edit", + "charStyle.list", + "charStyle.new", + "charStyle.redefine", + "charStyle.rename", + "charStyle.setAttrs", + "charStyle.unused", + "color.convert", + "color.gamutCheck", + "color.harmony", + "color.plates", + "dataset.capture", + "dataset.delete", + "dataset.list", + "dataset.new", + "dataset.next", + "dataset.prev", + "dataset.rename", + "dataset.select", + "dataset.set", + "dataset.update", + "dimension.applyToAll", + "dimension.create", + "dimension.update", + "edit.clear", + "edit.colors.adjustBalance", + "edit.colors.blendFrontToBack", + "edit.colors.blendHorizontally", + "edit.colors.blendVertically", + "edit.colors.invert", + "edit.colors.saturate", + "edit.colors.toCMYK", + "edit.colors.toGrayscale", + "edit.colors.toRGB", + "edit.duplicate", + "edit.findNext", + "edit.findReplace", + "effect.apply", + "effect.duplicate", + "effect.expandAppearance", + "effect.list", + "effect.move", + "effect.remove", + "effect.setParams", + "flattener.preview", + "gradient.selectStop", + "graph.column", + "graph.create", + "graph.design", + "graph.marker", + "graph.setData", + "graph.setType", + "graphicStyle.apply", + "graphicStyle.delete", + "graphicStyle.duplicate", + "graphicStyle.list", + "graphicStyle.merge", + "graphicStyle.move", + "graphicStyle.new", + "graphicStyle.redefine", + "graphicStyle.rename", + "graphicStyle.sortByName", + "graphicStyle.unused", + "guide.add", + "guide.list", + "guide.move", + "guide.remove", + "guide.select", + "guide.setLayer", + "image.info", + "imageTrace.expand", + "imageTrace.make", + "imageTrace.makeAndExpand", + "imageTrace.release", + "imageTrace.setView", + "layer.clippingMask.toggle", + "layer.collectInNew", + "layer.delete", + "layer.duplicate", + "layer.flatten", + "layer.hideOthers", + "layer.highlight", + "layer.locate", + "layer.lockOthers", + "layer.merge", + "layer.move", + "layer.new", + "layer.newSublayer", + "layer.outlineOthers", + "layer.previewAll", + "layer.releaseToLayers", + "layer.releaseToLayersBuild", + "layer.reverse", + "layer.selectAll", + "layer.setCurrent", + "layer.setProps", + "layer.showAll", + "layer.target", + "layer.template", + "layer.unlockAll", + "livePaint.expand", + "livePaint.fill", + "livePaint.gapOptions", + "livePaint.info", + "livePaint.make", + "livePaint.merge", + "livePaint.release", + "livePaint.strokeEdge", + "node.move", + "object.align", + "object.arrange.bringForward", + "object.arrange.bringToFront", + "object.arrange.sendBackward", + "object.arrange.sendToBack", + "object.arrange.sendToCurrentLayer", + "object.blend.expand", + "object.blend.info", + "object.blend.make", + "object.blend.release", + "object.blend.replaceSpine", + "object.blend.reverseFrontToBack", + "object.blend.reverseSpine", + "object.blend.spine.addAnchor", + "object.blend.spine.convertAnchor", + "object.blend.spine.moveAnchor", + "object.blend.spine.removeAnchor", + "object.blend.spine.reshapeSegment", + "object.clippingMask.editContents", + "object.clippingMask.editMask", + "object.clippingMask.make", + "object.clippingMask.release", + "object.compoundPath.make", + "object.compoundPath.release", + "object.compoundShape.expand", + "object.compoundShape.make", + "object.compoundShape.release", + "object.compoundShape.setMode", + "object.convertDocumentColorMode", + "object.createObjectMosaic", + "object.createTrimMarks", + "object.cropImage", + "object.distort", + "object.distribute", + "object.distributeSpacing", + "object.envelope.editContents", + "object.envelope.expand", + "object.envelope.info", + "object.envelope.makeWithMesh", + "object.envelope.makeWithTopObject", + "object.envelope.makeWithWarp", + "object.envelope.options", + "object.envelope.release", + "object.envelope.resetWithMesh", + "object.envelope.resetWithWarp", + "object.envelope.setMeshPoint", + "object.exitIsolation", + "object.expand", + "object.expand.info", + "object.expandBrush", + "object.expandShape", + "object.flattenTransparency", + "object.group", + "object.hide", + "object.hide.above", + "object.hide.otherLayers", + "object.hide.unselected", + "object.intertwine.arrange", + "object.intertwine.edit", + "object.intertwine.make", + "object.intertwine.release", + "object.isolate", + "object.lock", + "object.lock.above", + "object.lock.otherLayers", + "object.lock.unselected", + "object.makePixelPerfect", + "object.maskImage", + "object.mesh.addLine", + "object.mesh.create", + "object.mesh.deletePoint", + "object.mesh.expand", + "object.mesh.movePoint", + "object.mesh.movePoints", + "object.mesh.setPointColor", + "object.move", + "object.nudge", + "object.objectsOnPath.attach", + "object.objectsOnPath.expand", + "object.objectsOnPath.options", + "object.path.addAnchorPoints", + "object.path.cleanUp", + "object.path.divideObjectsBelow", + "object.path.offsetPath", + "object.path.outlineStroke", + "object.path.simplify", + "object.path.smooth", + "object.path.splitIntoGrid", + "object.pathfinder.crop", + "object.pathfinder.divide", + "object.pathfinder.exclude", + "object.pathfinder.intersect", + "object.pathfinder.merge", + "object.pathfinder.minusBack", + "object.pathfinder.minusFront", + "object.pathfinder.outline", + "object.pathfinder.trap", + "object.pathfinder.trim", + "object.pathfinder.unite", + "object.pattern.cancel", + "object.pattern.done", + "object.pattern.edit", + "object.pattern.make", + "object.puppetWarp", + "object.puppetWarp.pins", + "object.rasterize", + "object.reflect", + "object.repeat.expand", + "object.repeat.grid", + "object.repeat.mirror", + "object.repeat.options", + "object.repeat.radial", + "object.repeat.release", + "object.resetBoundingBox", + "object.rotate", + "object.scale", + "object.setBounds", + "object.setLiveShape", + "object.setPixelAligned", + "object.setProps", + "object.shape.convertToShape", + "object.shear", + "object.showAll", + "object.slice.clipToArtboard", + "object.slice.combine", + "object.slice.create", + "object.slice.delete", + "object.slice.deleteAll", + "object.slice.divide", + "object.slice.duplicate", + "object.slice.fromGuides", + "object.slice.fromSelection", + "object.slice.make", + "object.slice.move", + "object.slice.options", + "object.slice.release", + "object.slice.select", + "object.slice.setRect", + "object.textWrap.make", + "object.textWrap.options", + "object.textWrap.release", + "object.transform", + "object.transformAgain", + "object.transformEach", + "object.ungroup", + "object.unlockAll", + "object.vectorHalftone", + "paint.complement", + "paint.default", + "paint.editGradient", + "paint.freeform.addLine", + "paint.freeform.addPoint", + "paint.freeform.deletePoint", + "paint.freeform.get", + "paint.freeform.selectPoint", + "paint.freeform.setPoint", + "paint.freeform.splitLine", + "paint.invert", + "paint.lastColor", + "paint.lastGradient", + "paint.none", + "paint.proxies", + "paint.recent", + "paint.sampleColor", + "paint.setFill", + "paint.setGradientGeom", + "paint.setStroke", + "paint.swap", + "paint.toggleActive", + "paraStyle.apply", + "paraStyle.delete", + "paraStyle.duplicate", + "paraStyle.list", + "paraStyle.new", + "paraStyle.redefine", + "paraStyle.rename", + "paraStyle.setAttrs", + "paraStyle.unused", + "path.appendAnchor", + "path.average", + "path.averageJoin", + "path.blob", + "path.close", + "path.convertAnchor", + "path.convertAnchors", + "path.create", + "path.curvature", + "path.curvatureEdit", + "path.cutAtAnchors", + "path.deleteAnchors", + "path.eraseRegion", + "path.eraseSegments", + "path.freehand", + "path.insertAnchor", + "path.join", + "path.joinScrub", + "path.knife", + "path.lineCut", + "path.mirrorCut", + "path.moveAnchor", + "path.moveAnchors", + "path.rectCut", + "path.removeAnchor", + "path.removeAnchors", + "path.reshape", + "path.reshapeSegment", + "path.reverse", + "path.setAnchors", + "path.setFillRule", + "path.setHandle", + "path.smoothRegion", + "path.split", + "pattern.delete", + "pattern.list", + "pattern.options", + "pattern.transform", + "perspective.attach", + "perspective.draw", + "perspective.editText", + "perspective.grid.define", + "perspective.grid.get", + "perspective.grid.lock", + "perspective.grid.lockStation", + "perspective.grid.rulers", + "perspective.grid.set", + "perspective.grid.show", + "perspective.grid.snap", + "perspective.move", + "perspective.nudge", + "perspective.plane.matchObject", + "perspective.plane.move", + "perspective.plane.set", + "perspective.release", + "perspective.transform", + "recolor.apply", + "recolor.colors", + "recolor.randomize", + "recolor.reduce", + "select.add", + "select.all", + "select.allOnArtboard", + "select.anchors", + "select.anchorsMany", + "select.color", + "select.font", + "select.globalEdit", + "select.globalEditExclude", + "select.globalEditOptions", + "select.inverse", + "select.key", + "select.magicWand", + "select.nextAbove", + "select.nextBelow", + "select.none", + "select.object.allOnSameLayers", + "select.object.areaText", + "select.object.bristleBrushStrokes", + "select.object.brushStrokes", + "select.object.clippingMasks", + "select.object.directionHandles", + "select.object.pointText", + "select.object.slices", + "select.object.strayPoints", + "select.object.textObjects", + "select.recall", + "select.reselect", + "select.same.appearance", + "select.same.appearanceAttribute", + "select.same.blendingMode", + "select.same.fillAndStroke", + "select.same.fillColor", + "select.same.fontFamily", + "select.same.fontFamilyStyle", + "select.same.fontFamilyStyleSize", + "select.same.fontSize", + "select.same.graphicStyle", + "select.same.opacity", + "select.same.shapeType", + "select.same.strokeColor", + "select.same.strokeWeight", + "select.same.symbolInstance", + "select.same.textFillAndStrokeColor", + "select.same.textFillColor", + "select.same.textStrokeColor", + "select.segments", + "select.set", + "select.toggle", + "select.update", + "shape.arc", + "shape.ellipse", + "shape.flare", + "shape.line", + "shape.polarGrid", + "shape.polygon", + "shape.rectangle", + "shape.rectangularGrid", + "shape.spiral", + "shape.star", + "shapeBuilder.merge", + "shapeBuilder.regions", + "shaper.expand", + "shaper.release", + "shaper.releaseSource", + "shaper.scribble", + "shaper.select", + "slice.list", + "stroke.set", + "stroke.setAdvanced", + "stroke.weightDown", + "stroke.weightUp", + "stroke.widthPoint.copy", + "stroke.widthPoint.remove", + "stroke.widthPoint.set", + "svgFilter.apply", + "svgFilter.define", + "svgFilter.delete", + "svgFilter.list", + "svgInteractivity.clearEvents", + "svgInteractivity.info", + "svgInteractivity.removeEvent", + "svgInteractivity.setEvent", + "swatch.addUsedColors", + "swatch.delete", + "swatch.duplicate", + "swatch.edit", + "swatch.editGroup", + "swatch.list", + "swatch.merge", + "swatch.move", + "swatch.new", + "swatch.newGroup", + "swatch.resetDefaults", + "swatch.setSpot", + "swatch.sortByKind", + "swatch.sortByName", + "swatch.spotOptions", + "swatch.ungroup", + "swatch.unused", + "symbol.adjust", + "symbol.delete", + "symbol.duplicate", + "symbol.edit", + "symbol.exitEditing", + "symbol.instance.reset", + "symbol.instance.resetTransform", + "symbol.instance.selectPart", + "symbol.instance.setAppearance", + "symbol.list", + "symbol.new", + "symbol.options", + "symbol.place", + "symbol.replace", + "symbol.selectInstances", + "symbol.setCurrent", + "symbol.spray", + "symbol.unused", + "symbol.update", + "text.areaOptions", + "text.convertListToText", + "text.create", + "text.createInPath", + "text.discardEmpty", + "text.editRange", + "text.fitHeadline", + "text.fonts", + "text.getRange", + "text.glyphAlternates", + "text.insertInline", + "text.missingFonts", + "text.replaceFont", + "text.reshapeArea", + "text.reshapePath", + "text.setFormat", + "text.setGlyphAlternate", + "text.setPathHandle", + "text.setRangeStyle", + "text.setStyle", + "text.setText", + "text.startList", + "text.tabs.clear", + "text.tabs.get", + "text.tabs.set", + "text.thread.add", + "text.thread.break", + "text.thread.create", + "text.thread.info", + "text.thread.releaseSelection", + "text.thread.remove", + "text.touchType", + "transparency.disableOpacityMask", + "transparency.editOpacityMask", + "transparency.enableOpacityMask", + "transparency.info", + "transparency.makeOpacityMask", + "transparency.opacityMaskInfo", + "transparency.releaseOpacityMask", + "transparency.set", + "transparency.setOpacityMask", + "transparency.stopEditingOpacityMask", + "transparency.togglePageIsolatedBlending", + "transparency.togglePageKnockoutGroup", + "transparency.viewOpacityMask", + "type.changeCase", + "type.compositeFonts.list", + "type.convertToAreaType", + "type.convertToPointType", + "type.createOutlines", + "type.fillPlaceholder", + "type.fitHeadline", + "type.insert", + "type.opticalMarginAlignment", + "type.orientation.horizontal", + "type.orientation.vertical", + "type.pathOptions", + "type.resetHorizontalScale", + "type.resetTracking", + "type.ruby", + "type.scaleTextAttributes", + "type.size.decrease", + "type.size.decreaseByFive", + "type.size.increase", + "type.size.increaseByFive", + "type.smartPunctuation", + "type.step", + "variable.bind", + "variable.define", + "variable.delete", + "variable.highlight", + "variable.list", + "variable.lock", + "variable.makeGraphDynamic", + "variable.makeImageDynamic", + "variable.makeTextDynamic", + "variable.makeVisibilityDynamic", + "variable.rename", + "variable.unbind", +]; + +/// Commands a plug-in may not call although no rule refuses them, in order: they change the +/// preferences, a tool's options, a drag's state or the font names the whole app knows. +pub(super) const DENIED: &[&str] = &[ + "addon.cleanup.splitText", + "addon.pathtools.movePointsTogether", + "addon.pen.nextSegment", + "graphicStyle.setOptions", + "object.blend.options", + "object.liquify", + "object.pathfinder.options", + "type.compositeFonts.set", +]; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index cdea7ac5bb..c6daff9e41 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -85,6 +85,12 @@ impl AutomationRoots { Ok(Some(Arc::new(Self { read: open(read, Access::Read)?, write: open(write, Access::Write)? }))) } + /// Roots that grant no access of either kind: inside [`confine`] with them, every path a + /// command reads or writes is refused. + pub(crate) fn none() -> Arc { + Arc::new(Self { read: Vec::new(), write: Vec::new() }) + } + /// May the file or folder at `path` be read (or written)? It must lie inside one of the roots /// of that kind. `Err` says why not. pub fn check(&self, path: &str, access: Access) -> Result<(), String> { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index c1f438e807..043158c582 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -162,6 +162,9 @@ pub struct Session { /// Where the ICC profiles `color.loadProfile` loads are kept; `None`: only for the process /// ([`Session::attach_profile_store`]). profile_dir: Option, + /// The file Edit › Color Settings are kept in; `None`: only for the process + /// ([`Session::attach_color_settings`]). + color_settings_file: Option, /// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process /// ([`Session::attach_plugin_store`]). plugin_dir: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7a187b197b..54d84507c5 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -84,6 +84,7 @@ impl Session { pdf_preset_dir: None, dictionary_file: None, profile_dir: None, + color_settings_file: None, plugin_dir: None, ignored_plugin_grants: Default::default(), plugin_output: None, diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index ae98bdf4fa..f6fe8ff5bc 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -11,6 +11,9 @@ //! * **ICC profiles**: the bytes of each profile `color.loadProfile` registered, as `.icc` files //! named after the profile, never the path they came from (a profile in a system folder may //! move or go away). Attaching the folder registers them again. +//! * **Color Settings**: the working spaces, intent and black point compensation +//! `edit.colorSettings` sets, as one JSON file (#6335). Attaching it, after the profiles, makes +//! them the active settings again. //! * **Plug-ins**: the module of each plug-in `plugin.install` installs, as a `.wasm` file named //! after its id (as Illustrator keeps plug-ins in its Plug-ins folder); `plugin.remove` deletes it. //! Attaching the folder installs them again, except in Safe Mode and except the ones the user @@ -293,6 +296,31 @@ impl Session { } } + /// Keep Edit › Color Settings (the working spaces, intent and black point compensation) in the + /// file `path`, and make the settings saved there the active ones (#6335). After + /// [`Session::attach_profile_store`]: they may name a profile it registers. Settings that can't be + /// read, or that name a profile that is gone, leave the defaults with a log record, and the file + /// as it is until the settings change. + pub fn attach_color_settings(&mut self, path: PathBuf) { + if path.exists() { + let restored = read_capped(&path, MAX_PRESET_FILE) + .and_then(|bytes| serde_json::from_slice::(&bytes).map_err(|e| e.to_string())) + .and_then(|settings| vectorcraft_color::cms::set_active(&settings).map_err(|e| e.to_string())); + if let Err(e) = restored { + log::warn!("not using the saved color settings {}: {e}", path.display()); + } + } + self.color_settings_file = Some(path); + } + + /// Write `settings` to the file [`Session::attach_color_settings`] named; `false` when they + /// didn't go there. + pub(crate) fn store_color_settings(&self, settings: &vectorcraft_color::cms::ColorSettings) -> bool { + let Some(path) = &self.color_settings_file else { return false }; + let (Some(dir), Some(file)) = (path.parent(), path.file_name().and_then(|f| f.to_str())) else { return false }; + serde_json::to_vec_pretty(settings).is_ok_and(|bytes| put(dir, file, &bytes)) + } + /// Keep the plug-ins this session installs in `dir`, take the disabled plug-ins saved there /// ([`DISABLED_FILE`]), and install the stored ones ([`Session::load_stored_plugins`]). pub fn attach_plugin_store(&mut self, dir: PathBuf) { diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 158cf21ad0..3ed51e3c38 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3584,6 +3584,37 @@ fn a_trace_run_hands_its_trace_to_the_command() { assert!((bb.center().x - 160.0).abs() < 1.5, "traced where the image is now: {bb:?}"); } +/// A plug-in run that calls Image Trace and then fails leaves a trace handed in for the command in +/// place, as it leaves the document. +#[test] +fn a_failed_plugin_run_keeps_a_handed_in_trace() { + use vectorcraft_plugins::wat as tpl; + let (id, cmd, args) = ("test.engine.calltrace", "imageTrace.make", r#"{"params":{"ignoreWhite":true}}"#); + let mut s = session(); + s.allow_plugin_grants_from_requests(); + image_doc(&mut s); + let p: Value = serde_json::from_str(args).unwrap(); + let run = cmd::TraceRun::prepare(&s, cmd, &p).unwrap(); + run.run(&|_, _| true).unwrap().hand_in(&mut s); + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["{cmd}"]}}"#); + let imports = format!( + r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (data (i32.const 0x2000) "{}") (data (i32.const 0x2100) "{}")"#, + tpl::string(cmd), + tpl::string(args) + ); + let first = + format!("(drop (call $vc_call (i32.const 0x2000) (i32.const {}) (i32.const 0x2100) (i32.const {}))) unreachable", cmd.len(), args.len()); + let wasm = wat::parse_str(tpl::with_imports(&manifest, &imports, &first, "{}")).unwrap(); + s.execute("plugin.install", &json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})).unwrap(); + assert!(s.execute("plugin.run", &json!({"id": id, "ids": []})).is_err()); + assert!(s.trace_hand_off.is_some(), "the trace is still handed in"); + assert!(s.execute(cmd, &p).is_ok()); + assert!(s.trace_hand_off.is_none(), "taken"); + s.execute("plugin.remove", &json!({"id": id})).unwrap(); +} + #[test] fn image_trace_ignore_background_keeps_the_color_inside_the_art() { // A black field, a light panel on it and a black ring on the panel. diff --git a/crates/engine/src/tests/objexpand.rs b/crates/engine/src/tests/objexpand.rs index b9ccac12d5..2930bf1721 100644 --- a/crates/engine/src/tests/objexpand.rs +++ b/crates/engine/src/tests/objexpand.rs @@ -1086,6 +1086,43 @@ fn defaults_match_the_dialog_and_info_tells_what_applies() { assert!(matches!(selected(&s).kind, NodeKind::Path { live: Some(_), .. })); } +/// Expand refuses an option of the wrong type with an error naming it, and leaves the art, the +/// selection and the undo history as they were. Null counts as an option left out, which keeps its +/// default. +#[test] +fn expand_refuses_an_option_of_the_wrong_type() { + let mut s = session(); + let id = gradient_rect(&mut s, Rect::new(20.0, 20.0, 180.0, 120.0), white_black(), true); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone()) + }; + let before = (state(&s), node(&s, id)); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (p, want) in [ + (json!({"object": "yes"}), switch("object")), + (json!({"object": 0}), switch("object")), + (json!({"fill": "false"}), switch("fill")), + (json!({"stroke": 1}), switch("stroke")), + (json!({"gradient": 3}), "`gradient` must be a string".to_string()), + (json!({"gradient": true}), "`gradient` must be a string".to_string()), + (json!({"steps": "16"}), "`steps` must be a number, not \"16\"".to_string()), + (json!({"steps": [16]}), "`steps` must be a number, not [16]".to_string()), + ] { + let r = s.execute("object.expand", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{p}: {r:?}"); + assert_eq!((state(&s), node(&s, id)), before, "{p}"); + } + // Null options take their defaults: Object, Fill and Stroke on, 255 solid strips. + run(&mut s, "object.expand", json!({"object": null, "fill": null, "stroke": null, "gradient": null, "steps": null})); + let g = selected(&s); + let NodeKind::Group { children, .. } = &g.kind else { panic!("{:?}", g.kind) }; + let (clip, strips) = clip_parts(&children[0]); + assert!(matches!(clip.kind, NodeKind::Path { live: None, .. })); + assert_eq!(strips.len(), 255); + assert!(children[1].appearance.stroke_paint().is_none(), "outlined stroke"); +} + /// A selected open line with a 2 pt black stroke, no fill and a Zig Zag effect (#3089). fn zig_zag_line(s: &mut Session) -> NodeId { let id = NodeId(run(s, "path.create", json!({"d": "M 20 100 L 180 100"}))["id"].as_u64().unwrap()); diff --git a/crates/engine/src/tests/opacitymask.rs b/crates/engine/src/tests/opacitymask.rs index 206ef7e66d..9327bdc02b 100644 --- a/crates/engine/src/tests/opacitymask.rs +++ b/crates/engine/src/tests/opacitymask.rs @@ -151,6 +151,59 @@ fn mask_options_already_set_record_no_undo_step() { assert!(s.execute("transparency.setOpacityMask", &json!({"id": a.0})).is_err(), "no flag given"); } +/// Make Opacity Mask, Opacity Mask Options and the New Opacity Masks and page toggles refuse a +/// param of the wrong type with an error naming it, and leave the document, the selection, the +/// undo history and the defaults for new masks as they were. Null counts as a param left out, +/// which keeps its default. +#[test] +fn mask_commands_refuse_a_param_of_the_wrong_type() { + let mut s = session(); + let (a, m) = (rect(&mut s, 0.0, 100.0), rect(&mut s, 0.0, 50.0)); + s.execute("select.set", &json!({"ids": [a.0, m.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let (b, c) = (rect(&mut s, 150.0, 100.0), rect(&mut s, 150.0, 50.0)); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.revision, history(s), st.selection.objects.clone(), s.new_mask_defaults()) + }; + let before = state(&s); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (cmd, p, want) in [ + ("transparency.makeOpacityMask", json!({"clip": "false"}), switch("clip")), + ("transparency.makeOpacityMask", json!({"clip": 0}), switch("clip")), + ("transparency.makeOpacityMask", json!({"invert": "true"}), switch("invert")), + ("transparency.makeOpacityMask", json!({"invert": [true]}), switch("invert")), + ("transparency.setOpacityMask", json!({"id": a.0, "clip": "no"}), switch("clip")), + ("transparency.setOpacityMask", json!({"id": a.0, "clip": false, "invert": "yes"}), switch("invert")), + ("transparency.setOpacityMask", json!({"id": a.0, "disabled": 1}), switch("disabled")), + ("transparency.setOpacityMask", json!({"id": a.0, "linked": "false"}), switch("linked")), + ("transparency.toggleNewMasksClipping", json!({"value": "true"}), switch("value")), + ("transparency.toggleNewMasksInverted", json!({"value": 1}), switch("value")), + ("transparency.togglePageKnockoutGroup", json!({"value": "on"}), switch("value")), + ("transparency.togglePageIsolatedBlending", json!({"value": 0}), switch("value")), + ] { + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}"); + assert!(state(&s) == before, "{cmd} {p}: nothing changes"); + } + // Null params take their defaults: a new mask clips and is not inverted, a null flag stays as + // it is, and a null value toggles. + let id = s.execute("transparency.makeOpacityMask", &json!({"clip": null, "invert": null})).unwrap()["id"].as_u64().unwrap(); + let made = mask(&s, NodeId(id)).unwrap(); + assert!(made.clip && !made.invert); + s.execute("transparency.setOpacityMask", &json!({"id": a.0, "clip": null, "invert": true, "disabled": null, "linked": null})).unwrap(); + let set = mask(&s, a).unwrap(); + assert!(set.clip && set.invert && !set.disabled && set.linked); + assert!(s.execute("transparency.setOpacityMask", &json!({"id": a.0, "clip": null})).is_err(), "no flag given"); + assert_eq!(s.execute("transparency.toggleNewMasksClipping", &json!({"value": null})).unwrap(), json!({"value": false})); + assert_eq!(s.execute("transparency.toggleNewMasksInverted", &json!({"value": null})).unwrap(), json!({"value": true})); + assert_eq!(s.new_mask_defaults(), (false, true)); + assert_eq!(s.execute("transparency.togglePageKnockoutGroup", &json!({"value": null})).unwrap(), json!({"value": true})); + assert_eq!(s.execute("transparency.togglePageIsolatedBlending", &json!({"value": null})).unwrap(), json!({"value": true})); + assert!(doc(&s).page_knockout && doc(&s).page_isolate); +} + /// #4538: while a mask is edited the Layers panel lists only the mask, so New Layer and New /// Sublayer are refused instead of adding layers no row shows; they work again afterwards. #[test] diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index a5bd60490b..57094355c0 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -844,6 +844,69 @@ fn clean_up_removes_junk() { assert!(d.node(unpainted).is_none() && d.node(stray).is_none() && d.node(empty).is_none()); } +/// Offset Path, Simplify, Split Into Grid and Clean Up refuse a param of the wrong type with an +/// error naming the param, and leave the document, the selection and the undo history as they were. +/// Null keeps a param's default, and a distance still takes a string with a unit. +#[test] +fn path_commands_refuse_a_param_of_the_wrong_type() { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 50.0, 40.0); + s.execute("path.create", &json!({"anchors": [{"x": 5, "y": 5}]})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.doc.clone(), st.selection.objects.clone(), st.history.undo.len()) + }; + let before = state(&s); + let number = |k: &str, v: &str| format!("`{k}` must be a number, not {v}"); + let switch = |k: &str| format!("`{k}` must be true or false"); + for (cmd, p, want) in [ + ("object.path.offsetPath", json!({"offset": true}), number("offset", "true")), + ("object.path.offsetPath", json!({"offset": "wide"}), number("offset", "\"wide\"")), + ("object.path.offsetPath", json!({"offset": 5, "joins": 3}), "`joins` must be a string".to_string()), + ("object.path.offsetPath", json!({"offset": 5, "joins": "pointy"}), "`joins` must be one of miter, round, bevel".to_string()), + ("object.path.offsetPath", json!({"offset": 5, "miterLimit": [4]}), number("miterLimit", "[4]")), + ("object.path.simplify", json!({"auto": "true"}), switch("auto")), + ("object.path.simplify", json!({"level": false}), number("level", "false")), + ("object.path.simplify", json!({"level": 50, "tolerance": {}}), number("tolerance", "{}")), + ("object.path.simplify", json!({"cornerAngle": "sharp"}), number("cornerAngle", "\"sharp\"")), + ("object.path.simplify", json!({"straightLines": 1}), switch("straightLines")), + ("object.path.simplify", json!({"wholePaths": "no"}), switch("wholePaths")), + ("object.path.splitIntoGrid", json!({"rows": "many"}), number("rows", "\"many\"")), + ("object.path.splitIntoGrid", json!({"columns": true}), number("columns", "true")), + ("object.path.splitIntoGrid", json!({"gutter": false}), number("gutter", "false")), + ("object.path.splitIntoGrid", json!({"rowGutter": 2, "gutter": "x"}), number("gutter", "\"x\"")), + ("object.path.splitIntoGrid", json!({"height": 5, "totalHeight": [1]}), number("totalHeight", "[1]")), + ("object.path.splitIntoGrid", json!({"width": "wide"}), number("width", "\"wide\"")), + ("object.path.splitIntoGrid", json!({"columnGutter": true}), number("columnGutter", "true")), + ("object.path.splitIntoGrid", json!({"totalWidth": {}}), number("totalWidth", "{}")), + ("object.path.splitIntoGrid", json!({"rowGutter": "a"}), number("rowGutter", "\"a\"")), + ("object.path.splitIntoGrid", json!({"addGuides": "yes"}), switch("addGuides")), + ("object.path.cleanUp", json!({"strayPoints": "false"}), switch("strayPoints")), + ("object.path.cleanUp", json!({"unpaintedObjects": 0}), switch("unpaintedObjects")), + ("object.path.cleanUp", json!({"emptyTextPaths": "no"}), switch("emptyTextPaths")), + ] { + let r = s.execute(cmd, &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if *msg == want), "{cmd} {p}: {r:?}"); + assert!(state(&s) == before, "{cmd} {p} changed the document, the selection or the undo history"); + } + // Null takes the default: a 10 pt offset with mitered joins. + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": null, "joins": null, "miterLimit": null})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(90.0, 90.0, 160.0, 150.0), 1e-2), "{:?}", bounds(&s, r[0])); + // A distance with a unit, and a join named in capitals. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.offsetPath", &json!({"offset": "0.1 in", "joins": "Bevel"})).unwrap()); + assert!(close(bounds(&s, r[0]), Rect::new(92.8, 92.8, 157.2, 147.2), 1e-2), "{:?}", bounds(&s, r[0])); + // Null switches keep Clean Up's defaults, which remove the stray point. + let r = s.execute("object.path.cleanUp", &json!({"strayPoints": null, "unpaintedObjects": null, "emptyTextPaths": null})).unwrap(); + assert_eq!(r["removed"], 1); + // Split Into Grid with null counts and a gutter with a unit: two by two, 0.5 in apart. + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let r = ids(&s.execute("object.path.splitIntoGrid", &json!({"rows": null, "columns": null, "gutter": "0.5 in", "addGuides": null})).unwrap()); + assert_eq!(r.len(), 4); + assert!(close(bounds(&s, r[0]), Rect::new(100.0, 100.0, 107.0, 102.0), 1e-9), "{:?}", bounds(&s, r[0])); +} + #[test] fn divide_objects_below_cuts() { let mut s = session(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a705f05b9b..aca18dee1e 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3407,3 +3407,29 @@ fn another_module_under_an_id_with_settings_needs_replace() { install(&mut s, json!({})).unwrap(); run(&mut s, "plugin.remove", json!({"id": id})); } + +/// A filter that calls commands runs on the document with the edit in progress kept first: a move +/// still being previewed is its own undo step, and the filter is given the moved rectangle, which +/// its empty output then removes. +#[test] +fn a_filter_that_calls_commands_is_given_the_edit_in_progress() { + let id = "test.engine.callsettle"; + let mut s = session(); + let grant = json!(["doc.read", "doc.write", "commands"]); + let manifest = format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["select.all"]}}"#); + let wasm = wat::parse_str(tpl::returning(&manifest, r#"{"objects":[]}"#)).unwrap(); + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true})); + let paths = |s: &Session| s.doc().unwrap().doc.layers.first().and_then(|l| l.children()).map_or(0, |c| c.len()); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})); + s.begin_interaction("Move").unwrap(); + s.preview("object.move", &json!({"dx": 7, "dy": 0})).unwrap(); + run(&mut s, "plugin.run", json!({"id": id})); + assert!(!s.in_interaction()); + assert_eq!(paths(&s), 0, "the filter was given the moved rectangle and removed it"); + let labels: Vec<&str> = s.doc().unwrap().history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, [format!("Test {id}").as_str(), "Move"]); + run(&mut s, "edit.undo", json!({})); + let x = run(&mut s, "document.inspect", json!({}))["layers"][0]["children"][0]["bounds"]["x"].clone(); + assert_eq!(x, json!(17.0), "undoing the filter brings back the moved rectangle"); + run(&mut s, "plugin.remove", json!({"id": id})); +} diff --git a/crates/engine/src/tests/trap.rs b/crates/engine/src/tests/trap.rs index b2ae099083..aa0a1a75d5 100644 --- a/crates/engine/src/tests/trap.rs +++ b/crates/engine/src/tests/trap.rs @@ -138,15 +138,35 @@ fn no_adjoining_edges_is_a_clear_error_that_changes_nothing() { } #[test] -fn out_of_range_and_unreadable_numbers_are_refused_or_defaulted() { +fn out_of_range_and_unreadable_numbers_are_refused() { let (mut s, _, _) = abutting(); + let before = s.doc().unwrap().doc.clone(); + let undo_len = s.doc().unwrap().history.undo.len(); for p in [json!({"thickness": 1e300}), json!({"thickness": 0}), json!({"heightWidth": 0}), json!({"tintReduction": 101})] { assert!(s.execute("object.pathfinder.trap", &p).is_err(), "{p}"); } - // A thickness that isn't a number falls back to the default. - let r = s.execute("object.pathfinder.trap", &json!({"thickness": "NaN", "tintReduction": 100})).unwrap(); + // A value of the wrong type is refused with an error naming the param, and changes nothing. + for (p, want) in [ + (json!({"thickness": "NaN"}), "`thickness` must be a number, not \"NaN\""), + (json!({"thickness": true}), "`thickness` must be a number, not true"), + (json!({"heightWidth": [100]}), "`heightWidth` must be a number, not [100]"), + (json!({"tintReduction": false}), "`tintReduction` must be a number, not false"), + (json!({"trapsWithProcessColor": "yes"}), "`trapsWithProcessColor` must be true or false"), + (json!({"reverseTraps": 1}), "`reverseTraps` must be true or false"), + ] { + let r = s.execute("object.pathfinder.trap", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == want), "{p}: {r:?}"); + } + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo_len); + // Null keeps the default thickness, 0.25 pt; a thickness with a unit is read as a distance. + let r = s.execute("object.pathfinder.trap", &json!({"thickness": null, "reverseTraps": null, "tintReduction": 100})).unwrap(); let bb = traps(&s, &r)[0].geometric_bounds().unwrap(); assert!(near(bb.x1, 50.25), "{bb:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + let r = s.execute("object.pathfinder.trap", &json!({"thickness": "0.1 in", "tintReduction": 100})).unwrap(); + let bb = traps(&s, &r)[0].geometric_bounds().unwrap(); + assert!(near(bb.x1, 57.2), "{bb:?}"); } #[test] diff --git a/crates/engine/tests/color_settings.rs b/crates/engine/tests/color_settings.rs index d97560af30..0cc0edc4d4 100644 --- a/crates/engine/tests/color_settings.rs +++ b/crates/engine/tests/color_settings.rs @@ -9,6 +9,7 @@ use serde_json::json; use vectorcraft_color::cms; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::colormgmt::{PROFILES_KEY, doc_profiles}; +use vectorcraft_engine::store::MAX_PRESET_FILE; use vectorcraft_geom::Affine; use vectorcraft_render::{RenderOptions, Renderer}; use vectorcraft_testkit::fixtures::{exec, id_of, rect, select, session}; @@ -426,3 +427,108 @@ fn loading_the_working_rgb_profile_again_takes_effect_at_once() { assert!(after.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-4), "after the reload {after:?}, want {want:?}"); assert!(redrawn, "the canvas redraws"); } + +/// A folder of its own for the test `tag`, empty. +fn fresh_dir(tag: &str) -> std::path::PathBuf { + let dir = vectorcraft_testkit::temp_dir(&format!("color-settings-{tag}")); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +/// An ICC file of an RGB profile named `name` (a built-in one with its description replaced by a +/// name of the same length). +#[allow(clippy::unwrap_used, reason = "a test helper: a missing built-in profile fails the test")] +fn icc_named(name: &str) -> Vec { + let builtin = cms::DISPLAY_P3; + assert_eq!(builtin.len(), name.len()); + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::>(); + let mut bytes = cms::icc_bytes(builtin).unwrap().to_vec(); + let (from, to) = (utf16(builtin), utf16(name)); + let at = bytes.windows(from.len()).position(|w| w == from).unwrap(); + bytes[at..at + to.len()].copy_from_slice(&to); + bytes +} + +/// Puts the default Color Settings back, unregisters `profile` and deletes `paths` when dropped, +/// also after a failed assertion, so the next test starts from the defaults. +struct ColorSettingsReset { + profile: Option<&'static str>, + paths: Vec, +} + +impl Drop for ColorSettingsReset { + /// The defaults back, the profile unregistered and the paths deleted. + fn drop(&mut self) { + let _ = cms::set_active(&cms::ColorSettings::default()); + if let Some(name) = self.profile { + cms::unregister_icc(name); + } + for path in &self.paths { + let _ = std::fs::remove_dir_all(path).or_else(|_| std::fs::remove_file(path)); + } + } +} + +/// #6335: Edit › Color Settings come back in the next session: the working spaces (a loaded +/// profile among them, registered again by the profile store first), the intent and black point +/// compensation. A session nobody attached a file to keeps nothing, and nothing is written before +/// the settings change. +#[test] +fn color_settings_come_back_in_the_next_session() { + let _g = settings(); + let root = fresh_dir("color-settings"); + let (profiles, file) = (root.join("Color Profiles"), root.join("Color Settings.json")); + let loaded = "StoreRGB-6"; + let icc = vectorcraft_testkit::temp_dir("store-color-settings").join("loaded.icc"); + let _reset = ColorSettingsReset { profile: Some(loaded), paths: vec![root.clone(), icc.clone()] }; + std::fs::write(&icc, icc_named(loaded)).unwrap(); + + let mut a = Session::new(); + a.attach_profile_store(profiles.clone()); + a.attach_color_settings(file.clone()); + a.execute("color.loadProfile", &json!({"path": icc.to_str().unwrap()})).unwrap(); + a.execute("edit.colorSettings", &json!({})).unwrap(); + assert!(!file.exists(), "nothing to keep before the settings change"); + a.execute("edit.colorSettings", &json!({"rgb": loaded, "cmyk": cms::DEVICE_CMYK, "intent": "perceptual", "bpc": false})).unwrap(); + let chosen = cms::ColorSettings { rgb: loaded.into(), cmyk: cms::DEVICE_CMYK.into(), intent: cms::Intent::Perceptual, bpc: false }; + assert_eq!(cms::active_settings(), chosen); + + // The next start begins with the defaults and without the loaded profile, which the profile + // store registers again before the settings name it. + cms::set_active(&cms::ColorSettings::default()).unwrap(); + assert!(cms::unregister_icc(loaded)); + let mut b = Session::new(); + b.attach_profile_store(profiles); + b.attach_color_settings(file.clone()); + assert_eq!(cms::active_settings(), chosen, "the saved settings are the active ones again"); + + // Without a file, a change is kept only for the process. + let mut c = Session::new(); + c.execute("edit.colorSettings", &json!({"bpc": true})).unwrap(); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert_eq!(saved, chosen, "the file is left alone"); +} + +/// #6335: saved Color Settings that can't be used (a profile that is gone, a damaged or oversized +/// file) leave the defaults and the file as it is; the next change writes over it. +#[test] +fn saved_color_settings_that_cannot_be_used_leave_the_defaults() { + let _g = settings(); + let dir = fresh_dir("color-settings-bad"); + let _reset = ColorSettingsReset { profile: None, paths: vec![dir.clone()] }; + let file = dir.join("Color Settings.json"); + std::fs::create_dir_all(&dir).unwrap(); + let gone = json!({"rgb": cms::SRGB, "cmyk": "A Profile That Is Gone", "intent": "perceptual", "bpc": false}).to_string().into_bytes(); + let oversized = vec![b' '; MAX_PRESET_FILE as usize + 1]; + for bytes in [gone, b"not json".to_vec(), oversized] { + cms::set_active(&cms::ColorSettings::default()).unwrap(); + std::fs::write(&file, &bytes).unwrap(); + let mut s = Session::new(); + s.attach_color_settings(file.clone()); + assert_eq!(cms::active_settings(), cms::ColorSettings::default()); + assert_eq!(std::fs::read(&file).unwrap(), bytes, "left as it is"); + s.execute("edit.colorSettings", &json!({"bpc": false})).unwrap(); + let saved: cms::ColorSettings = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(!saved.bpc && saved.cmyk == cms::GENERIC_CMYK, "written over by the next change: {saved:?}"); + } +} diff --git a/crates/engine/tests/it/copy_direct_selection.rs b/crates/engine/tests/it/copy_direct_selection.rs index c41a813eec..14c2a45b18 100644 --- a/crates/engine/tests/it/copy_direct_selection.rs +++ b/crates/engine/tests/it/copy_direct_selection.rs @@ -604,6 +604,66 @@ fn a_copied_member_with_its_own_appearance_takes_the_compounds() { assert_eq!(s.clipboard.nodes[0].appearance, compound_look); } +/// A member copied or cut on its own, whole or in part, takes the compound's graphic style link +/// with its look, or no link when the compound has none or the member no longer has the style's +/// look (a gradient pinned to the compound's bounds); the style the member had before Make Compound +/// Path does not go with it. +#[test] +fn a_copied_member_takes_the_compounds_graphic_style() { + let style_of = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().extras().graphic_style; + let clipboard_styles = |s: &Session| s.clipboard.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + for (compound_styled, gradient) in [(false, false), (true, false), (true, true)] { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 200, "height": 200})); + let m0 = rect(&mut s, 10.0, 10.0, 40.0, 40.0); + run(&mut s, "paint.setFill", json!({"ids": [m0.0], "color": "#00ff00"})); + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Member"})); + let member_style = style_of(&s, m0); + assert!(member_style.is_some(), "the path is linked to the style made from it"); + let m1 = rect(&mut s, 60.0, 10.0, 40.0, 40.0); + run(&mut s, "select.set", json!({"ids": [m0.0, m1.0]})); + let compound = NodeId(run(&mut s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let fill = + if gradient { json!({"ids": [compound.0], "gradient": {"kind": "linear"}}) } else { json!({"ids": [compound.0], "color": "#ff0000"}) }; + run(&mut s, "paint.setFill", fill); + assert_eq!(style_of(&s, m0), member_style, "the member keeps its old link inside the compound"); + let compound_style = if compound_styled { + run(&mut s, "select.set", json!({"ids": [compound.0]})); + run(&mut s, "graphicStyle.new", json!({"name": "Compound"})); + style_of(&s, compound) + } else { + None + }; + assert_eq!(compound_style.is_some(), compound_styled); + // A gradient fitted to the compound is pinned to its bounds on the copy, which is no longer + // the style's look. + let link = compound_style.filter(|_| !gradient); + let expected: Vec = if link.is_some() { vec!["Compound".into()] } else { vec![] }; + let case = format!("compound styled: {compound_styled}, gradient: {gradient}"); + + s.select_tool("groupSelection", vectorcraft_engine::ViewInfo::default()).unwrap(); + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes[0].id, m0); + assert_eq!(s.clipboard.nodes[0].extras().graphic_style, link, "whole member, {case}"); + assert_eq!(clipboard_styles(&s), expected, "whole member, {case}"); + + run(&mut s, "select.segments", json!({"id": m0.0, "segments": [[0, 0]]})); + run(&mut s, "edit.copy", json!({})); + assert_eq!(s.clipboard.nodes.len(), 1); + assert_eq!(s.clipboard.nodes[0].extras().graphic_style, link, "one segment, {case}"); + assert_eq!(clipboard_styles(&s), expected, "one segment, {case}"); + + run(&mut s, "select.set", json!({"ids": [m0.0]})); + run(&mut s, "edit.cut", json!({})); + assert_eq!(members_of(&s, compound), Some(vec![m1])); + let pasted = NodeId(run(&mut s, "edit.pasteInPlace", json!({}))["ids"][0].as_u64().unwrap()); + assert_eq!(style_of(&s, pasted), link, "Cut and Paste in Place, {case}"); + check_session(&s).unwrap(); + } +} + #[test] fn every_segment_of_every_member_picked_copies_and_cuts_the_compound() { let mut s = Session::new(); diff --git a/crates/engine/tests/plugin_call.rs b/crates/engine/tests/plugin_call.rs new file mode 100644 index 0000000000..71f2619a30 --- /dev/null +++ b/crates/engine/tests/plugin_call.rs @@ -0,0 +1,239 @@ +//! A filter plug-in whose manifest's `commandAllowlist` names commands calls them with `vc_call`: +//! each call sees what the calls before it left, the calls and the filter's output are one undo +//! step, and a run that fails leaves the document as it was. +// 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_engine::Session; +use vectorcraft_plugins::wat as tpl; + +/// The command imports and the strings the plug-ins pass: the ids "select.all" (0x2000, 10 bytes), +/// "object.move" (0x2010, 11), "no.such.cmd" (0x2020, 11), "effect.apply" (0x2030, 12) and +/// "select.globalEditOptions" (0x2040, 24), and the arguments `{"dx":5,"dy":0}` (0x2100, 15), +/// `{"dx":"x"}` (0x2200, 10), `{"effect":"plugin.test.call.fx"}` (0x2300, 32) and `{"size":true}` +/// (0x2400, 13). +const CALLS: &str = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32))) + (data (i32.const 0x2000) "select.all") + (data (i32.const 0x2010) "object.move") + (data (i32.const 0x2020) "no.such.cmd") + (data (i32.const 0x2030) "effect.apply") + (data (i32.const 0x2040) "select.globalEditOptions") + (data (i32.const 0x2100) "{\22dx\22:5,\22dy\22:0}") + (data (i32.const 0x2200) "{\22dx\22:\22x\22}") + (data (i32.const 0x2300) "{\22effect\22:\22plugin.test.call.fx\22}") + (data (i32.const 0x2400) "{\22size\22:true}")"#; + +/// Selects everything. +const SELECT_ALL: &str = "(drop (call $vc_call (i32.const 0x2000) (i32.const 10) (i32.const 0) (i32.const 0)))"; +/// Moves the selection 5 to the right. +const MOVE: &str = "(drop (call $vc_call (i32.const 0x2010) (i32.const 11) (i32.const 0x2100) (i32.const 15)))"; + +const EMPTY: &str = r#"{"objects":[]}"#; + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Installs filter `id` with `permissions` (a JSON list) and `allowlist` (a JSON list), whose +/// `vc_run` runs `first`, then returns `output` → what `plugin.install` returned, or why it refused. +fn install(s: &mut Session, id: &str, permissions: &str, allowlist: &str, first: &str, output: &str) -> Result { + let manifest = + format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{permissions},"commandAllowlist":{allowlist}}}"#); + let wasm = wat::parse_str(tpl::with_imports(&manifest, CALLS, first, output)).unwrap(); + let grant: Value = serde_json::from_str(permissions).unwrap(); + let data = vectorcraft_format::base64_encode(&wasm); + s.execute("plugin.install", &json!({"dataBase64": data, "grant": grant, "replace": true})).map_err(|e| e.to_string()) +} + +/// A filter `id` that may read and change the document and call `select.all` and `object.move`. +fn install_mover(s: &mut Session, id: &str, first: &str, output: &str) { + install(s, id, r#"["doc.read","doc.write","commands"]"#, r#"["select.all","object.move"]"#, first, output).unwrap(); +} + +/// A document with two rectangles and nothing selected. +fn document() -> Session { + let mut s = Session::new(); + s.allow_plugin_grants_from_requests(); + run(&mut s, "file.new", json!({"width": 400, "height": 200})); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 50})); + run(&mut s, "select.none", json!({})); + s +} + +/// The active document's layers, its undo and redo steps and how many objects are selected. +fn state(s: &mut Session) -> (Value, usize, usize, usize) { + let content = run(s, "document.inspect", json!({}))["layers"].take(); + let d = s.doc().unwrap(); + (content, d.history.undo.len(), d.history.redo.len(), d.selection.len()) +} + +/// Runs filter `id` on nothing, so only its calls change the document. +fn run_plugin(s: &mut Session, id: &str) -> Result { + s.execute("plugin.run", &json!({"id": id, "ids": []})).map_err(|e| e.to_string()) +} + +#[test] +fn calls_see_each_others_changes_and_make_one_undo_step() { + let mut s = document(); + let before = state(&mut s); + install_mover(&mut s, "test.call.mover", &[SELECT_ALL, MOVE].concat(), EMPTY); + run_plugin(&mut s, "test.call.mover").unwrap(); + let after = state(&mut s); + // `object.move` moved what `select.all` selected: both rectangles. + let xs: Vec<&Value> = after.0[0]["children"].as_array().unwrap().iter().map(|c| &c["bounds"]["x"]).collect(); + assert_eq!(xs, [&json!(105.0), &json!(15.0)]); + assert_eq!(after.1, before.1 + 1, "one undo step"); + assert_eq!(s.doc().unwrap().history.undo.last().map(|u| u.label.as_str()), Some("Test test.call.mover")); + run(&mut s, "edit.undo", json!({})); + assert_eq!(state(&mut s).0, before.0); + run(&mut s, "edit.redo", json!({})); + assert_eq!(state(&mut s).0, after.0); + // Without `select.all` nothing is selected, so `object.move` has nothing to move. + run(&mut s, "select.none", json!({})); + install_mover(&mut s, "test.call.mover", MOVE, EMPTY); + assert!(run_plugin(&mut s, "test.call.mover").is_err()); + run(&mut s, "plugin.remove", json!({"id": "test.call.mover"})); +} + +#[test] +fn a_run_that_fails_after_its_calls_changes_nothing() { + let mut s = document(); + let before = state(&mut s); + // A trap, an output that isn't JSON, and a command that fails, each after the move. + let bad_move = "(drop (call $vc_call (i32.const 0x2010) (i32.const 11) (i32.const 0x2200) (i32.const 10)))"; + for (first, output) in + [([SELECT_ALL, MOVE, "unreachable"].concat(), EMPTY), ([SELECT_ALL, MOVE].concat(), "nope"), ([SELECT_ALL, MOVE, bad_move].concat(), EMPTY)] + { + install_mover(&mut s, "test.call.fails", &first, output); + assert!(run_plugin(&mut s, "test.call.fails").is_err(), "{first} {output}"); + assert_eq!(state(&mut s), before, "{first} {output}"); + } + run(&mut s, "plugin.remove", json!({"id": "test.call.fails"})); + // Session state a call changed outside the document goes back too: Global Edit's options. + let options = "(drop (call $vc_call (i32.const 0x2040) (i32.const 24) (i32.const 0x2400) (i32.const 13))) unreachable"; + let allowlist = r#"["select.globalEditOptions"]"#; + install(&mut s, "test.call.options", r#"["doc.read","commands"]"#, allowlist, options, EMPTY).unwrap(); + assert!(run_plugin(&mut s, "test.call.options").is_err()); + assert_eq!(run(&mut s, "select.globalEditOptions", json!({}))["size"], json!(false)); + run(&mut s, "plugin.remove", json!({"id": "test.call.options"})); +} + +/// A command that changes state a failed run can't put back (the preferences, a tool's options, a +/// drag's state) is refused at install, by name. +#[test] +fn install_refuses_reviewed_denials() { + let mut s = document(); + for refused in ["object.liquify", "object.pathfinder.options", "addon.pen.nextSegment"] { + let allowlist = format!(r#"["select.all","{refused}"]"#); + let e = install(&mut s, "test.call.reviewed", r#"["doc.read","commands"]"#, &allowlist, "", EMPTY).unwrap_err(); + assert!(e.contains(refused) && e.contains("may not call"), "{e}"); + } +} + +#[test] +fn install_refuses_a_command_a_plugin_may_not_call_and_reports_unknown_ones() { + let mut s = document(); + let first = "(drop (call $vc_call (i32.const 0x2020) (i32.const 11) (i32.const 0) (i32.const 0)))"; + for refused in ["document.save", "edit.undo", "plugin.run", "script.run"] { + let allowlist = format!(r#"["select.all","{refused}"]"#); + let e = install(&mut s, "test.call.refused", r#"["doc.read","commands"]"#, &allowlist, "", EMPTY).unwrap_err(); + assert!(e.contains(refused) && e.contains("may not call"), "{e}"); + } + let r = install(&mut s, "test.call.unknown", r#"["doc.read","commands"]"#, r#"["select.all","no.such.cmd"]"#, first, EMPTY).unwrap(); + assert_eq!(r["unknownCommands"], json!(["no.such.cmd"])); + let e = run_plugin(&mut s, "test.call.unknown").unwrap_err(); + assert!(e.contains("no.such.cmd"), "{e}"); + run(&mut s, "plugin.remove", json!({"id": "test.call.unknown"})); +} + +#[test] +fn a_call_that_names_a_plugin_is_refused() { + let mut s = document(); + let before = state(&mut s); + let first = format!("{SELECT_ALL} (drop (call $vc_call (i32.const 0x2030) (i32.const 12) (i32.const 0x2300) (i32.const 32)))"); + install(&mut s, "test.call.fx", r#"["doc.read","doc.write","commands"]"#, r#"["select.all","effect.apply"]"#, &first, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.fx").unwrap_err(); + assert!(e.contains("may not call"), "{e}"); + assert_eq!(state(&mut s), before); + run(&mut s, "plugin.remove", json!({"id": "test.call.fx"})); +} + +#[test] +fn without_doc_write_a_call_that_edits_is_refused() { + let mut s = document(); + let before = state(&mut s); + let allowlist = r#"["select.all","object.move"]"#; + install(&mut s, "test.call.reader", r#"["doc.read","commands"]"#, allowlist, &[SELECT_ALL, MOVE].concat(), EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.reader").unwrap_err(); + assert!(e.contains("may not call"), "{e}"); + assert_eq!(state(&mut s), before); + // Selecting changes no art, so it runs. + install(&mut s, "test.call.reader", r#"["doc.read","commands"]"#, allowlist, SELECT_ALL, EMPTY).unwrap(); + run_plugin(&mut s, "test.call.reader").unwrap(); + run(&mut s, "plugin.remove", json!({"id": "test.call.reader"})); +} + +/// Installs filter `id` that may read and change the document and call `allowlist`, whose `vc_run` +/// makes `calls` (command id and arguments) in order, dropping their codes, then returns nothing. +fn install_calls(s: &mut Session, id: &str, allowlist: &str, calls: &[(&str, &str)]) { + let mut imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))"#.to_string(); + let mut first = String::new(); + for (i, (cmd, args)) in calls.iter().enumerate() { + let at = 0x3000 + i * 0x400; + imports += &format!(r#" (data (i32.const {at}) "{}") (data (i32.const {}) "{}")"#, tpl::string(cmd), at + 0x100, tpl::string(args)); + first += &format!("(drop (call $vc_call (i32.const {at}) (i32.const {}) (i32.const {}) (i32.const {})))", cmd.len(), at + 0x100, args.len()); + } + let manifest = format!( + r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":["doc.read","doc.write","commands"],"commandAllowlist":{allowlist}}}"# + ); + let wasm = wat::parse_str(tpl::with_imports(&manifest, &imports, &first, EMPTY)).unwrap(); + let data = vectorcraft_format::base64_encode(&wasm); + let grant = json!(["doc.read", "doc.write", "commands"]); + run(s, "plugin.install", json!({"dataBase64": data, "grant": grant, "replace": true})); +} + +/// Arguments that carry a file or folder key at any depth, such as an effect's +/// `textureImage.path`, are refused before the command runs, so no file is read; arguments nested +/// without one run. +#[test] +fn a_call_whose_arguments_name_a_file_is_refused() { + let mut s = document(); + let before = state(&mut s); + let allowlist = r#"["select.all","effect.apply","effect.setParams"]"#; + let select = ("select.all", ""); + for (cmd, args) in [ + ("effect.apply", r#"{"effect":"distort.glass","params":{"textureImage":{"path":"missing-texture.png"}}}"#), + ("effect.setParams", r#"{"index":0,"params":{"textureImage":{"path":"missing-texture.png"}}}"#), + ("effect.apply", r#"{"effect":"distort.glass","params":{"layers":[{"name":"a"},{"file":"missing-texture.png"}]}}"#), + ] { + install_calls(&mut s, "test.call.files", allowlist, &[select, (cmd, args)]); + let e = run_plugin(&mut s, "test.call.files").unwrap_err(); + assert!(e.contains("may not call") && e.contains(cmd), "{args}: {e}"); + assert_eq!(state(&mut s), before, "{args}"); + } + // The same effect with ordinary nested params runs. + install_calls(&mut s, "test.call.files", allowlist, &[select, ("effect.apply", r#"{"effect":"distort.glass","params":{"distortion":5}}"#)]); + run_plugin(&mut s, "test.call.files").unwrap(); + assert_eq!(state(&mut s).1, before.1 + 1, "one undo step"); + run(&mut s, "plugin.remove", json!({"id": "test.call.files"})); +} + +/// A command's result describes the document, so a plug-in without `doc.read` may call nothing. +#[test] +fn without_doc_read_every_call_is_refused() { + let mut s = document(); + let before = state(&mut s); + install(&mut s, "test.call.blind", r#"["commands"]"#, r#"["select.all"]"#, SELECT_ALL, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.blind").unwrap_err(); + assert!(e.contains("may not call") && e.contains("select.all"), "{e}"); + assert_eq!(state(&mut s), before); + // The same for an id no command has: without `doc.read` the answer never depends on the command. + let unknown = "(drop (call $vc_call (i32.const 0x2020) (i32.const 11) (i32.const 0) (i32.const 0)))"; + install(&mut s, "test.call.blind", r#"["commands"]"#, r#"["no.such.cmd"]"#, unknown, EMPTY).unwrap(); + let e = run_plugin(&mut s, "test.call.blind").unwrap_err(); + assert!(e.contains("may not call") && e.contains("no.such.cmd"), "{e}"); + run(&mut s, "plugin.remove", json!({"id": "test.call.blind"})); +} diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index c159c1f191..d8316e94e3 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -40,7 +40,7 @@ mod text; mod writer; pub(crate) use entry::{RgbInCmyk, leaving_out_undecodable}; -pub use entry::{export, export_with_report, page_areas}; +pub use entry::{check_page_sizes, export, export_with_report, page_areas}; #[cfg(test)] use exporter::{MAX_COORD, writable, xf}; #[cfg(test)] diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index d131ece8fd..75b87209c5 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -1,5 +1,6 @@ use super::writer::{Sheet, Writer, date_time}; -use super::{Affine, Document, ExportReport, Exporter, HashSet, PageBoxes, PdfError, PdfOptions, Rect, write}; +use super::{Affine, Document, ExportReport, Exporter, HashSet, PageBoxes, PdfError, PdfOptions, Rect, krilla, write}; +use crate::{Compatibility, PdfSettings, Standard}; /// Export `doc` as PDF bytes: one page per artboard (or the artboards chosen in `opts`). pub fn export(doc: &Document, opts: &PdfOptions) -> Result, PdfError> { @@ -49,6 +50,8 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let doc = baked.as_ref().unwrap_or(doc); let pages = pages(doc, opts)?; + let raised = for_long_pages(set, &pages)?; + let set = raised.as_ref().unwrap_or(set); let title = crate::pdfx::title(set.standard, opts.title.clone().unwrap_or_else(|| doc.title.clone())); // The time of writing (none on the web) dates the editing data and the page information. @@ -59,6 +62,11 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let mut w = Writer::new(doc, set, &title, created_at, doc.color_mode == vectorcraft_doc::ColorMode::Cmyk)?; // Preserve Editing: the native document as an embedded file (`check` refused PDF/A with it). let mut warnings = set.warnings(); + if raised.is_some() { + warnings.push( + "PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6".into(), + ); + } let native = opts.native.as_deref().filter(|_| set.preserve_editing); if let Some(native) = native { w.pdf.document_mut().embed_file(crate::editing::embedded_file(native, set.compression.compress_text, now.map(date_time))); @@ -78,9 +86,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha ex.overprint = set.advanced.overprint == crate::Overprint::Preserve; let bleed = set.bleed_of(doc); let marks = set.marks.printer_marks(); - // In PDF 1.6 and later files that aren't PDF/X files, a page with a side longer than - // [`MAX_PAGE_SIDE`] is written in larger units; other files have every page in points. - let scales = set.compatibility.has_user_unit() && !set.standard.is_pdfx(); + let scales = writes_user_units(set); // PDF/X files have no annotations over the art (ISO 15930: only printer's mark and trap // network annotations, outside the bleed box): objects' URLs aren't written as links there. let links = !set.standard.is_pdfx(); @@ -93,6 +99,8 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha } let mut units = Vec::with_capacity(pages.len()); let total = pages.len() as u64; + let long: Vec<(usize, f64)> = + pages.iter().map(|(i, b)| (*i, b.media.width().max(b.media.height()))).filter(|(_, side)| *side > MAX_PDF14_REAL).collect(); for (written, (i, boxes)) in pages.into_iter().enumerate() { // The page count and the page being written, for a client that asked for progress. vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; @@ -104,6 +112,9 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha // `unit` points. let unit = if scales { user_unit(m.width(), m.height()) } else { 1.0 }; units.push(unit); + if m.width().max(m.height()) > MAX_PAGE_SIDE { + warnings.push(long_page_warning(set, i, m.width(), m.height(), unit, scales)); + } let shift = Affine::translate((-m.x0, -m.y0)); let view = if unit > 1.0 { Affine::scale(1.0 / unit) * shift } else { shift }; let sheet = Sheet { @@ -127,7 +138,10 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha vectorcraft_doc::cancel::check().map_err(|_| PdfError::Cancelled)?; let (layers, overprinted, invisible) = (ex.layers, ex.overprinted, ex.invisible); w.absorb(ex); - let (bytes, more) = w.finish(left_out, display_doc_title)?; + let (bytes, more) = match w.finish(left_out, display_doc_title) { + Ok(done) => done, + Err(e) => return Err(writer_error(doc, opts, left_out, &long, e)), + }; let bytes = crate::forms::finish(bytes, doc, set, layers, overprinted, invisible)?; // The writer gives the file its creation date as its modification date too. let bytes = match opts.modified.filter(|m| Some(*m) != created_at) { @@ -138,6 +152,7 @@ fn export_with_report_inner(doc: &Document, opts: &PdfOptions, left_out: &mut Ha let bytes = crate::post::rights(bytes, &doc.metadata)?; warnings.extend(more); let bytes = crate::post::user_units(bytes, &units)?; + // A PDF 1.5 file written as PDF 1.6 keeps the encryption PDF 1.5 has (128-bit RC4). let bytes = crate::post::finish(bytes, opts, native.is_some(), &mut warnings)?; warnings.dedup(); Ok(ExportReport { bytes, warnings }) @@ -168,12 +183,153 @@ pub fn page_areas(doc: &Document, opts: &PdfOptions) -> Result, PdfErr /// gives: 14,400 (200 inches in units of 1/72 inch). pub(crate) const MAX_PAGE_SIDE: f64 = 14_400.0; +/// The smallest side of a page in units of its default user space that ISO 32000-1 (Annex C.2) +/// gives: 3. +const MIN_PAGE_SIDE: f64 = 3.0; + +/// The largest real number the writer puts in a PDF 1.3 or 1.4 file: past it, krilla fails the +/// file with `Limit(TooLargeFloat)`. +const MAX_PDF14_REAL: f64 = 32_767.0; + +/// Pages with a side longer than [`MAX_PAGE_SIDE`] are written with a `UserUnit`: in PDF 1.6 and +/// later files that aren't PDF/X files. Other files have every page in points. +fn writes_user_units(set: &PdfSettings) -> bool { + set.compatibility.has_user_unit() && !set.standard.is_pdfx() +} + /// The `UserUnit` (PDF 1.6) of a page `w` × `h` points large: 1 when both sides are at most /// [`MAX_PAGE_SIDE`], else the longer side divided by it, rounded up to the next thousandth, so -/// that both sides are at most [`MAX_PAGE_SIDE`] units. +/// that both sides are at most [`MAX_PAGE_SIDE`] units. A short side of [`MIN_PAGE_SIDE`] points +/// or more stays at least [`MIN_PAGE_SIDE`] units: the unit is at most the short side divided by +/// it, rounded down to the next thousandth, and the long side is then longer than +/// [`MAX_PAGE_SIDE`] units. fn user_unit(w: f64, h: f64) -> f64 { - let side = w.abs().max(h.abs()); - if side.is_finite() && side > MAX_PAGE_SIDE { (side / MAX_PAGE_SIDE * 1000.0).ceil() / 1000.0 } else { 1.0 } + let (side, short) = (w.abs().max(h.abs()), w.abs().min(h.abs())); + if !(side.is_finite() && side > MAX_PAGE_SIDE) { + return 1.0; + } + let unit = (side / MAX_PAGE_SIDE * 1000.0).ceil() / 1000.0; + if short >= MIN_PAGE_SIDE { unit.min((short / MIN_PAGE_SIDE * 1000.0).floor() / 1000.0).max(1.0) } else { unit } +} + +/// Check the page sizes of `doc` exported with `opts` before anything is drawn: the error +/// [`export`] gives for a page that the file's PDF version or standard can't hold. +pub fn check_page_sizes(doc: &Document, opts: &PdfOptions) -> Result<(), PdfError> { + for_long_pages(&opts.settings, &pages(doc, opts)?).map(|_| ()) +} + +/// The settings `set` is written with when one of `pages` has a side longer than +/// [`MAX_PAGE_SIDE`]: a PDF 1.5 file that isn't a PDF/X file is written as PDF 1.6, which has a +/// page's `UserUnit` (`None`: `set` as it is). Other files without a `UserUnit` have the page in +/// points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has +/// a real number past [`MAX_PDF14_REAL`]: a page whose side is past it and not a whole number of +/// points is refused here, before anything is drawn ([`page_too_long`]). +fn for_long_pages(set: &PdfSettings, pages: &[(usize, PageBoxes)]) -> Result, PdfError> { + if !pages.iter().any(|(_, b)| b.media.width().max(b.media.height()) > MAX_PAGE_SIDE) { + return Ok(None); + } + let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx()) + .then(|| PdfSettings { compatibility: Compatibility::Pdf16, ..set.clone() }); + // The writer's test for a whole number, on the `f32` it writes. + let real = |side: f64| side > MAX_PDF14_REAL && (side as f32) as i32 as f32 != side as f32; + if let Some((i, b)) = pages.iter().find(|(_, b)| real(b.media.width()) || real(b.media.height())) { + page_too_long(set, *i, b.media.width().max(b.media.height()))?; + } + Ok(raised) +} + +/// The error for the page of artboard `artboard` (0-based), `side` points long, whose size or art +/// needs a real number past [`MAX_PDF14_REAL`], in a PDF 1.3 or 1.4 file written with `set`; `Ok` +/// in other files. +fn page_too_long(set: &PdfSettings, artboard: usize, side: f64) -> Result<(), PdfError> { + if !matches!(set.compatibility, Compatibility::Pdf13 | Compatibility::Pdf14) { + return Ok(()); + } + // PDF/X-1a and PDF/X-3 files are always PDF 1.3. + let label = if matches!(set.standard, Standard::PdfX1a | Standard::PdfX3) { set.standard.label() } else { set.compatibility.label() }; + let (max, n, side) = (thousands(MAX_PDF14_REAL), artboard + 1, format!("{:.0}", side.ceil())); + Err(PdfError::BadSetting(format!( + "{label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard" + ))) +} + +/// The writer's `error` for `doc` exported with `opts`, or, when it failed on a real number past +/// [`MAX_PDF14_REAL`] in a PDF 1.3 or 1.4 file, the error for the page of `long` (artboards and +/// sides past it) that needs one. With several such pages, the first [`MAX_PROBES`] are each +/// written alone, without the editing data and the thumbnails, to find it; past them, the first +/// page is named. +fn writer_error(doc: &Document, opts: &PdfOptions, left_out: &mut HashSet, long: &[(usize, f64)], error: PdfError) -> PdfError { + const MAX_PROBES: usize = 8; + let too_large = format!("{:?}", krilla::error::KrillaError::Limit(krilla::error::LimitError::TooLargeFloat)); + if !matches!(&error, PdfError::Write(e) if *e == too_large) { + return error; + } + let failing = match long { + [] => return error, + [one] => *one, + [first, ..] => long + .iter() + .take(MAX_PROBES) + .copied() + .find(|(i, _)| { + let alone = PdfOptions { + settings: opts.settings.clone(), + artboards: Some(vec![*i]), + title: opts.title.clone(), + display_doc_title: opts.display_doc_title, + created: opts.created, + modified: opts.modified, + native: None, + private_data: None, + thumbnails: vec![], + }; + matches!(export_with_report_inner(doc, &alone, left_out), Err(PdfError::BadSetting(_))) + }) + .unwrap_or(*first), + }; + page_too_long(&opts.settings, failing.0, failing.1).err().unwrap_or(error) +} + +/// `v` (a whole number) with commas between groups of three digits: 32,767. +fn thousands(v: f64) -> String { + let digits = format!("{v:.0}"); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (k, c) in digits.chars().enumerate() { + if k > 0 && (digits.len() - k) % 3 == 0 { + out.push(','); + } + out.push(c); + } + out +} + +/// A page `w` × `h` points large in points, rounded up, and in meters: 56693 × 2835 pt (20.00 × +/// 1.00 m). +fn page_size(w: f64, h: f64) -> String { + const METERS_PER_POINT: f64 = 0.0254 / 72.0; + format!("{:.0} × {:.0} pt ({:.2} × {:.2} m)", w.ceil(), h.ceil(), w * METERS_PER_POINT, h * METERS_PER_POINT) +} + +/// The warning for the page of artboard `artboard` (0-based), `w` × `h` points large with a side +/// longer than [`MAX_PAGE_SIDE`], written in units of `unit` points; `scales`: the file has +/// `UserUnit`s. +fn long_page_warning(set: &PdfSettings, artboard: usize, w: f64, h: f64, unit: f64, scales: bool) -> String { + let n = artboard + 1; + let size = page_size(w, h); + if scales && w.max(h) / unit > MAX_PAGE_SIDE { + format!( + "the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units" + ) + } else if unit > 1.0 { + format!( + "the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller" + ) + } else { + let label = if set.standard.is_pdfx() || set.standard == Standard::PdfA2b { set.standard.label() } else { set.compatibility.label() }; + format!( + "the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in" + ) + } } /// The RGB colours and non-CMYK images a CMYK document carries, which the export separates into diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index 5c9701e7e4..234f4b8a8d 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -75,7 +75,7 @@ mod syntax; pub use editing::{EDITING_FILE, Editing, LEGACY_EDITING_FILE, editing, editing_with}; pub use encrypt::Encryption; -pub use export::{export, export_with_report, page_areas}; +pub use export::{check_page_sizes, export, export_with_report, page_areas}; pub use file_info::{FileInfo, file_info}; #[cfg(any(test, feature = "read-count"))] pub use import::imports_of; diff --git a/crates/pdf/src/tests/marks.rs b/crates/pdf/src/tests/marks.rs index e4df914a14..19031505d3 100644 --- a/crates/pdf/src/tests/marks.rs +++ b/crates/pdf/src/tests/marks.rs @@ -133,13 +133,291 @@ fn a_page_past_14400_pt_is_written_with_a_user_unit_and_reads_back_at_its_size() assert!(near(back.artboards[0].rect, Rect::new(0.0, 0.0, 20_000.0, 10_000.0)), "{:?}", back.artboards[0].rect); let red = painted(&back, |p| rgb(p, [255, 0, 0])); assert!(red.len() == 1 && near(red[0], Rect::new(-5.0, 10.0, 40.0, 50.0)), "{red:?}"); - // PDF 1.5 and PDF/X-4 files have the page in points, past 14,400. - for v in [json!({"compatibility": "1.5"}), json!({"standard": "pdfX4", "compatibility": "1.6"})] { + // PDF/X-4 files have the page in points, past 14,400. + for v in [json!({"standard": "pdfX4", "compatibility": "1.5"}), json!({"standard": "pdfX4", "compatibility": "1.6"})] { let pages = units_and_media(&pdf(&d, v.clone())); assert_eq!(pages[0], (1.0, Rect::new(0.0, 0.0, 20_000.0, 10_000.0)), "{v}"); } } +/// 20 m in points. +const TWENTY_M: f64 = 20.0 / 0.0254 * 72.0; + +/// [`doc`] with its artboard `w` × `h` points large. +fn sized(w: f64, h: f64) -> Document { + let mut d = doc(); + d.artboards[0].rect = Rect::new(0.0, 0.0, w, h); + d +} + +/// The export of `d` with `set`. +fn report(d: &Document, set: PdfSettings) -> Result { + export_with_report(d, &PdfOptions { settings: set, created: Some(1_791_200_000), ..PdfOptions::uncompressed() }) +} + +/// The numbers that follow `key` in the file's bytes (`/MediaBox [0 0 w h]`, `/UserUnit u`), read +/// as text, without the PDF reader: none when the file has no `key`. +fn raw_numbers(bytes: &[u8], key: &str, count: usize) -> Vec { + let text = String::from_utf8_lossy(bytes); + let Some(at) = text.find(key) else { return vec![] }; + let words = text[at + key.len()..].split(|c: char| c.is_whitespace() || matches!(c, '[' | ']' | '/' | '>')).filter(|w| !w.is_empty()); + words.take(count).map(|w| w.parse().unwrap_or(f64::NAN)).collect() +} + +/// The page's width and height in meters as the file's bytes give them: its media box times its +/// `UserUnit` (1 without one). +fn raw_meters(bytes: &[u8]) -> (f64, f64) { + let media = raw_numbers(bytes, "/MediaBox", 4); + let unit = raw_numbers(bytes, "/UserUnit", 1).first().copied().unwrap_or(1.0); + let m = |v: f64| v * unit / 72.0 * 0.0254; + (m(media[2] - media[0]), m(media[3] - media[1])) +} + +/// The warnings about pages longer than 14,400 pt. +fn long_page_warnings(r: &ExportReport) -> Vec<&String> { + r.warnings.iter().filter(|w| w.contains("page limit of 14,400 pt")).collect() +} + +/// A 20 m page at PDF 1.7 (the default) is written with a `UserUnit` of 3.938, reads back at 20 m +/// from the file's bytes, through the PDF reader and through the import, and the export says how +/// it is written. +#[test] +fn a_20_m_page_keeps_its_size_with_a_user_unit_and_the_export_says_so() { + let d = sized(TWENTY_M, TWENTY_M / 20.0); + let r = report(&d, PdfSettings::default()).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.7")); + assert_eq!( + long_page_warnings(&r), + [ + "the page of artboard 1 is 56693 × 2835 pt (20.00 × 1.00 m), longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of 3.938, so apps that ignore UserUnit show it that many times smaller" + ], + "{:?}", + r.warnings + ); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938]); + let (w, h) = raw_meters(&r.bytes); + assert!((w - 20.0).abs() < 0.001 && (h - 1.0).abs() < 0.001, "{w} × {h} m"); + let pages = units_and_media(&r.bytes); + assert_eq!(pages[0].0, 3.938); + assert!(pages[0].1.width() <= 14_400.0, "{pages:?}"); + let page = &info(&r.bytes, None).unwrap().pages[0]; + assert!((page.width - TWENTY_M).abs() < 0.01, "{page:?}"); + let back = import(&r.bytes).unwrap(); + assert!((back.artboards[0].rect.width() - TWENTY_M).abs() < 0.01, "{:?}", back.artboards[0].rect); +} + +/// Every built-in preset and every PDF version keeps a 20 m page at its size, or refuses it with +/// the reason: PDF 1.3 and 1.4 files (PDF/X-1a and PDF/X-3 among them) have no `UserUnit` and +/// hold no real number past 32,767, PDF 1.5 is written as PDF 1.6 to have one, and PDF/X-4 pages +/// at PDF 1.5 or 1.6 stay in points with a warning. +#[test] +fn every_preset_and_version_keeps_a_20_m_page_or_says_why_not() { + let d = sized(TWENTY_M, TWENTY_M / 20.0); + let refused = |e: PdfError, label: &str| { + assert_eq!( + e.to_string(), + format!( + "invalid PDF setting: {label} files hold real numbers up to 32,767, and the page of artboard 1, 56693 pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard" + ) + ); + }; + for preset in crate::builtin_presets() { + let name = preset.name.as_str(); + match report(&d, preset.settings.clone()) { + Err(e) if matches!(name, "PDF/X-1a:2001" | "PDF/X-3:2002") => refused(e, name), + Err(e) => panic!("{name}: {e}"), + Ok(r) if name == "PDF/X-4:2010" => { + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{name}"); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{name}"); + let w = long_page_warnings(&r); + let points = "PDF/X-4:2010 pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"; + assert!(w.len() == 1 && w[0].ends_with(points), "{w:?}"); + } + Ok(r) => { + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938], "{name}"); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{name}"); + assert_eq!(long_page_warnings(&r).len(), 1, "{name}: {:?}", r.warnings); + } + } + } + for c in Compatibility::ALL.iter().copied() { + let set = PdfSettings { compatibility: c, ..PdfSettings::default() }; + match (c, report(&d, set)) { + (Compatibility::Pdf13 | Compatibility::Pdf14, Err(e)) => refused(e, c.label()), + (Compatibility::Pdf13 | Compatibility::Pdf14, Ok(_)) => panic!("{} is refused", c.label()), + (_, Err(e)) => panic!("{}: {e}", c.label()), + (_, Ok(r)) => { + let header = if c == Compatibility::Pdf15 { "1.6" } else { c.id() }; + assert!(r.bytes.starts_with(format!("%PDF-{header}").as_bytes()), "{}", c.label()); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.938], "{}", c.label()); + assert!((raw_meters(&r.bytes).0 - 20.0).abs() < 0.001, "{}", c.label()); + let raised = r.warnings.iter().any(|w| w.starts_with("PDF 1.5 has no UserUnit") && w.ends_with("the file is written as PDF 1.6")); + assert_eq!(raised, c == Compatibility::Pdf15, "{}: {:?}", c.label(), r.warnings); + } + } + } + // PDF/X-4 and PDF/A-2b files at PDF 1.4 have no `UserUnit` either. + let at_14 = |standard| report(&d, PdfSettings { standard, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }); + refused(at_14(Standard::PdfX4).err().unwrap(), "PDF 1.4"); + refused(at_14(Standard::PdfA2b).err().unwrap(), "PDF 1.4"); +} + +/// A page from 14,400 to 32,767 pt long is written in points, with the warning, in PDF 1.3 and 1.4 +/// files, PDF/X-1a, PDF/X-3, PDF/X-4 and PDF/A-2b files among them, as before the warning. Past +/// 32,767 pt a page of whole points is written too, as the writer puts whole numbers as integers; +/// a side that isn't a whole number, or art that needs a real number past 32,767, gets the error. +#[test] +fn pdf_1_4_writes_a_page_up_to_32767_pt_in_points() { + let presets = crate::builtin_presets(); + let preset = |name: &str| presets.iter().find(|p| p.name == name).unwrap().settings.clone(); + let sets = [ + ("PDF 1.3", PdfSettings { compatibility: Compatibility::Pdf13, ..PdfSettings::default() }), + ("PDF 1.4", PdfSettings { compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ("PDF/X-1a:2001", preset("PDF/X-1a:2001")), + ("PDF/X-3:2002", preset("PDF/X-3:2002")), + ("PDF/X-4:2010", PdfSettings { standard: Standard::PdfX4, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ("PDF/A-2b", PdfSettings { standard: Standard::PdfA2b, compatibility: Compatibility::Pdf14, ..PdfSettings::default() }), + ]; + for (label, set) in &sets { + for side in [17_000.0, 32_767.0, 40_000.0] { + let r = report(&sized(side, 300.0), set.clone()).unwrap_or_else(|e| panic!("{label} at {side}: {e}")); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{label}"); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, side, 300.0], "{label}"); + let w = long_page_warnings(&r); + let points = format!("{label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in"); + assert!(w.len() == 1 && w[0].ends_with(&points), "{label}: {w:?}"); + } + // For PDF/X-4 and PDF/A-2b files the error names the PDF version. + let label = if matches!(*label, "PDF/X-4:2010" | "PDF/A-2b") { "PDF 1.4" } else { label }; + let refused = |e: PdfError, side: &str| { + let refusal = format!("{label} files hold real numbers up to 32,767, and the page of artboard 1, {side} pt long, needs larger ones"); + assert!(e.to_string().contains(&refusal), "{e}"); + }; + refused(report(&sized(32_767.5, 300.0), set.clone()).err().unwrap(), "32768"); + // Art at a coordinate that isn't a whole number past 32,767. + let mut d = sized(40_000.0, 300.0); + let layer = d.default_layer().unwrap(); + let id = d.alloc_id(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(35_000.5, 10.0, 35_100.25, 50.0)), red)).unwrap(); + refused(report(&d, set.clone()).err().unwrap(), "40000"); + } +} + +/// With several pages past 32,767 pt in a PDF 1.4 file, the error names the page whose art needs a +/// real number past 32,767, not the first long page. +#[test] +fn the_error_names_the_long_page_whose_art_needs_a_larger_real() { + let mut d = sized(40_000.0, 300.0); + let mut second = d.artboards[0].clone(); + second.rect = Rect::new(0.0, 10_000.0, 40_000.0, 10_300.0); + d.artboards.push(second); + let layer = d.default_layer().unwrap(); + let id = d.alloc_id(); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.insert(Some(layer), 0, Node::path(id, shapes::rectangle(Rect::new(35_000.5, 10_010.0, 35_100.25, 10_050.0)), red)).unwrap(); + let set = PdfSettings { compatibility: Compatibility::Pdf14, ..PdfSettings::default() }; + let e = report(&d, set).err().unwrap(); + assert!(e.to_string().contains("the page of artboard 2, 40000 pt long, needs larger ones"), "{e}"); +} + +/// A long page whose short side would be under 3 units at the `UserUnit` its long side needs +/// (ISO 32000-1, Annex C.2; PDF/A-2b's 6.1.13) is written with a smaller unit that keeps the +/// short side at 3 units, and a warning; 100 m × 4 mm is one. A short side under 3 pt is under 3 +/// units at any unit, and keeps the unit its long side needs. +#[test] +fn a_page_too_narrow_for_its_user_unit_keeps_3_units_on_its_short_side() { + const MM: f64 = 72.0 / 25.4; + for set in [PdfSettings::default(), PdfSettings { standard: Standard::PdfA2b, ..PdfSettings::default() }] { + let r = report(&sized(TWENTY_M * 5.0, 4.0 * MM), set).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [3.779]); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!(media[3] - media[1] >= 3.0, "{media:?}"); + assert!((media[2] - media[0] - TWENTY_M * 5.0 / 3.779).abs() < 0.01, "{media:?}"); + assert_eq!( + r.warnings.iter().filter(|w| w.contains("too long and narrow")).collect::>(), + [ + "the page of artboard 1 is 283465 × 12 pt (100.00 × 0.00 m), too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of 3.779, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units" + ] + ); + assert!(long_page_warnings(&r).is_empty(), "{:?}", r.warnings); + } + // A short side of 3 units or more at the long side's unit keeps that unit. + let r = report(&sized(TWENTY_M * 5.0, 60.0), PdfSettings::default()).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); + let media = raw_numbers(&r.bytes, "/MediaBox", 4); + assert!(media[3] - media[1] >= 3.0, "{media:?}"); + let r = report(&sized(TWENTY_M * 5.0, 2.0), PdfSettings::default()).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [19.686]); +} + +/// A PDF 1.5 file written as PDF 1.6 for a long page keeps PDF 1.5's encryption, 128-bit RC4, as +/// the Save PDF dialog shows it. +#[test] +fn a_pdf_1_5_file_written_as_1_6_keeps_rc4_encryption() { + let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() }; + set.security.open_password = "secret".into(); + let has = |bytes: &[u8], s: &[u8]| bytes.windows(s.len()).any(|w| w == s); + let r = report(&sized(TWENTY_M, 300.0), set).unwrap(); + assert!(r.bytes.starts_with(b"%PDF-1.6")); + assert!(has(&r.bytes, b"/CFM/V2") && !has(&r.bytes, b"AESV2"), "the file is encrypted with RC4"); +} + +/// The warning gives a page's size rounded up, as the error does: a side of 14,400.4 pt is 14401. +#[test] +fn the_long_page_warning_rounds_the_size_up() { + let r = report(&sized(14_400.4, 300.0), PdfSettings::default()).unwrap(); + assert!(long_page_warnings(&r)[0].contains("is 14401 × 300 pt"), "{:?}", r.warnings); +} + +/// A page of exactly 14,400 pt is written in points with no warning, at any PDF version; one +/// point longer gets a `UserUnit` of 1.001 and the warning, and stays in points at PDF 1.4. +#[test] +fn a_page_of_14400_pt_stays_in_points_and_one_point_more_does_not() { + let at = |side: f64, c: Compatibility| report(&sized(side, 300.0), PdfSettings { compatibility: c, ..PdfSettings::default() }); + for c in [Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf17] { + let r = at(14_400.0, c).unwrap(); + assert!(long_page_warnings(&r).is_empty() && !r.warnings.iter().any(|w| w.contains("UserUnit")), "{}: {:?}", c.label(), r.warnings); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{}", c.label()); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_400.0, 300.0], "{}", c.label()); + } + let r = at(14_401.0, Compatibility::Pdf17).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), [1.001]); + assert_eq!(long_page_warnings(&r).len(), 1, "{:?}", r.warnings); + assert!(long_page_warnings(&r)[0].contains("14401 × 300 pt (5.08 × 0.11 m)"), "{:?}", r.warnings); + let r = at(14_401.0, Compatibility::Pdf14).unwrap(); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_401.0, 300.0]); + assert_eq!(long_page_warnings(&r).len(), 1, "{:?}", r.warnings); +} + +/// A page of 14,400 pt or less is written as before in every built-in preset and every PDF +/// version: the header names the version asked for, the media box is in points, and there is no +/// `UserUnit` and no page-size warning. A PDF 1.5 file with a password keeps 128-bit RC4. +#[test] +fn a_page_within_14400_pt_is_written_as_before_at_every_version() { + let d = sized(14_400.0, 14_400.0); + let mut sets: Vec = crate::builtin_presets().into_iter().map(|p| p.settings).collect(); + for c in [Compatibility::Pdf13, Compatibility::Pdf14, Compatibility::Pdf15, Compatibility::Pdf16, Compatibility::Pdf17, Compatibility::Pdf20] { + sets.push(PdfSettings { compatibility: c, ..PdfSettings::default() }); + } + for set in sets { + let label = format!("{} {}", set.standard.label(), set.compatibility.label()); + let r = report(&d, set.clone()).unwrap_or_else(|e| panic!("{label}: {e}")); + // PDF/X-1a and PDF/X-3 files are always PDF 1.3. + let pdf13 = set.compatibility == Compatibility::Pdf13 || matches!(set.standard, Standard::PdfX1a | Standard::PdfX3); + let header = if pdf13 { "%PDF-1.3".to_string() } else { format!("%{}", set.compatibility.label().replace(' ', "-")) }; + assert!(r.bytes.starts_with(header.as_bytes()), "{label}: {:?}", String::from_utf8_lossy(&r.bytes[..8])); + assert_eq!(raw_numbers(&r.bytes, "/UserUnit", 1), Vec::::new(), "{label}"); + assert_eq!(raw_numbers(&r.bytes, "/MediaBox", 4), [0.0, 0.0, 14_400.0, 14_400.0], "{label}"); + assert!(!r.warnings.iter().any(|w| w.contains("14,400") || w.contains("UserUnit")), "{label}: {:?}", r.warnings); + } + let mut set = PdfSettings { compatibility: Compatibility::Pdf15, ..PdfSettings::default() }; + set.security.open_password = "secret".into(); + let r = report(&d, set).unwrap(); + let has = |s: &[u8]| r.bytes.windows(s.len()).any(|w| w == s); + assert!(r.bytes.starts_with(b"%PDF-1.5") && has(b"/CFM/V2") && !has(b"AESV2")); +} + #[test] fn art_in_the_bleed_is_kept_and_clipped_to_the_bleed_box() { let d = doc(); diff --git a/crates/plugins/src/host.rs b/crates/plugins/src/host.rs index f8235a4fbb..182456aa71 100644 --- a/crates/plugins/src/host.rs +++ b/crates/plugins/src/host.rs @@ -1,9 +1,10 @@ //! What a plug-in may import from the host ([`IMPORTS`]), from plug-in API level 2 on: //! `vc_progress` reports how far a run has got, `vc_cancelled` tells it the user or a host limit //! asked it to stop, and `vc_log` writes a log line (the `progress` permission); `vc_settings_*` -//! read and write its settings (`settings`) and `vc_cache_*` its cache (`cache`, [`crate::storage`]). -//! A module may import one only when its manifest gives `api` 2 and lists the import's permission, -//! and the host checks each import when the module is loaded ([`check_imports`], [`check_granted`]): +//! read and write its settings (`settings`) and `vc_cache_*` its cache (`cache`, [`crate::storage`]); +//! `vc_call` runs a command its manifest's `commandAllowlist` names and `vc_call_result` reads that +//! command's result (`commands`, through the [`Bridge`] the run is given). A module may import one +//! only when its manifest gives `api` 2 and lists the import's permission, and the host checks each import when the module is loaded ([`check_imports`], [`check_granted`]): //! one it doesn't offer, one with another signature and one the manifest doesn't allow are refused //! by name. //! @@ -13,8 +14,9 @@ //! each line ([`MAX_LOG_LINE`]) and each run ([`MAX_LOG_LINES`], [`MAX_LOG_BYTES`], //! [`MAX_LOG_READ`]) are capped. Keys and values must lie inside the module's memory, keys must be //! [`crate::storage::valid_name`]s, values are capped, and so are each run's storage calls -//! ([`MAX_STORAGE_CALLS`]) and the bytes they move ([`MAX_STORAGE_BYTES`]). Nothing a module passes -//! can panic the host. +//! ([`MAX_STORAGE_CALLS`]) and the bytes they move ([`MAX_STORAGE_BYTES`]). Command calls are capped +//! per call ([`MAX_CALL_DATA`]) and per run ([`MAX_CALLS`], [`MAX_CALL_BYTES`]). Nothing a module +//! passes can panic the host. use std::sync::Arc; @@ -95,6 +97,72 @@ pub const MAX_STORAGE_CALLS: usize = 10_000; /// pass it returns [`STORAGE_BUDGET`]. pub const MAX_STORAGE_BYTES: usize = 1 << 30; +/// What `vc_call` returns: the command ran, and `vc_call_result` reads its result. +pub const CALL_OK: i32 = 0; +/// What `vc_call` or `vc_call_result` returns: the id, the arguments or the buffer doesn't lie +/// inside the module's memory. +pub const CALL_OUTSIDE_MEMORY: i32 = -1; +/// What `vc_call` returns: the id or the arguments are not UTF-8. +pub const CALL_BAD_UTF8: i32 = -2; +/// What `vc_call` returns: the arguments are not a JSON object. +pub const CALL_BAD_JSON: i32 = -3; +/// What `vc_call` returns: the manifest's `commandAllowlist` doesn't list the command. +pub const CALL_NOT_ALLOWED: i32 = -4; +/// What `vc_call` returns: no command has the id. +pub const CALL_UNKNOWN_COMMAND: i32 = -5; +/// What `vc_call` returns: a plug-in may not call the command, whatever its manifest lists. +pub const CALL_DENIED_COMMAND: i32 = -6; +/// What `vc_call` returns: the command can't run now (no document, nothing selected). +pub const CALL_DISABLED: i32 = -7; +/// What `vc_call` returns: the command ran and failed. +pub const CALL_COMMAND_FAILED: i32 = -8; +/// What `vc_call` returns: the arguments or the result are larger than [`MAX_CALL_DATA`], or the +/// run made [`MAX_CALLS`] calls or moved [`MAX_CALL_BYTES`] with them. +pub const CALL_LIMIT: i32 = -9; +/// What `vc_call_result` returns: no call has a result yet. +pub const CALL_NO_RESULT: i32 = -10; +/// What `vc_call` returns: nothing can be called now (while the module is being loaded, in a run +/// that isn't a filter's run on a document, or after a call in the run failed). In a run, this +/// fails it too. +pub const CALL_NO_CONTEXT: i32 = -11; + +/// Most `vc_call` calls one run makes. +pub const MAX_CALLS: usize = 1_000; + +/// Largest arguments or result of one `vc_call`, in bytes. +pub const MAX_CALL_DATA: usize = 8 << 20; + +/// Most bytes of arguments and results one run's `vc_call` calls move, all together. +pub const MAX_CALL_BYTES: usize = 64 << 20; + +/// Instructions each `vc_call` costs the run, besides one for every 64 bytes of its arguments and +/// result: [`MAX_CALLS`] calls cost a fifth of a filter's usual budget. +pub const CALL_FUEL: u64 = 10_000; + +/// Why a command a plug-in called with `vc_call` didn't run, or failed: the code `vc_call` returns +/// and the reason, which the run's error gives. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CallFailure { + pub code: i32, + pub why: String, +} + +/// What runs the commands a plug-in calls: a command id and its arguments (a JSON object) → the +/// command's result, or why it didn't run. +pub type Bridge<'a> = dyn FnMut(&str, &serde_json::Value) -> std::result::Result + 'a; + +/// What `vc_call` pauses the run with, for the host to make the call ([`Run::pending`]). +#[derive(Debug)] +pub(crate) struct CallPending; + +impl std::fmt::Display for CallPending { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("vc_call") + } +} + +impl wasmi::errors::HostError for CallPending {} + /// One host import: its name, its type and the permission it needs. pub struct Import { pub name: &'static str, @@ -134,7 +202,17 @@ const fn storage_import(name: &'static str, params: &'static [ValType], signatur /// A storage call that fails returns [`STORAGE_NOT_FOUND`], [`STORAGE_OUTSIDE_MEMORY`], /// [`STORAGE_BAD_NAME`], [`STORAGE_FULL`], [`STORAGE_UNAVAILABLE`], [`STORAGE_FAILED`] or /// [`STORAGE_BUDGET`]. -pub const IMPORTS: [Import; 9] = [ +/// +/// With `commands`, for a filter whose manifest's `commandAllowlist` names the command: +/// +/// - `vc_call(id, id_len, args, args_len) -> i32`: runs the command with the UTF-8 id of `id_len` +/// bytes at `id` and the arguments at `args` (a UTF-8 JSON object; no bytes: `{}`) on the document +/// the run is for → [`CALL_OK`] or why it didn't run or failed. A failed call fails the run, and +/// nothing the run did stays; +/// - `vc_call_result(out, out_cap) -> i32`: the length of the last successful call's result (JSON), +/// copied to `out` when it fits in `out_cap` (nothing is copied otherwise), or +/// [`CALL_NO_RESULT`]. +pub const IMPORTS: [Import; 11] = [ Import { name: "vc_progress", params: &[ValType::I64, ValType::I64], @@ -156,6 +234,8 @@ pub const IMPORTS: [Import; 9] = [ storage_import("vc_cache_read", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Cache), storage_import("vc_cache_write", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Cache), storage_import("vc_cache_clear", &[I32, I32], "(param i32 i32) (result i32)", Permission::Cache), + storage_import("vc_call", &[I32, I32, I32, I32], "(param i32 i32 i32 i32) (result i32)", Permission::Commands), + storage_import("vc_call_result", &[I32, I32], "(param i32 i32) (result i32)", Permission::Commands), ]; /// Which of a plug-in's stores a storage import reads or writes. @@ -291,6 +371,18 @@ pub(crate) struct Run { storage: Option>, storage_calls: usize, storage_bytes: usize, + /// The commands `vc_call` may run (the manifest's `commandAllowlist`), once the module has + /// loaded and when the run has something to run them ([`Run::allow_calls`]); `None` otherwise. + allowed: Option>, + /// How many `vc_call` calls the run made, and the bytes of arguments and results they moved. + calls: usize, + call_bytes: usize, + /// The call `vc_call` paused the run for: its command id, its arguments and their size in bytes. + pub(crate) pending: Option<(String, serde_json::Value, usize)>, + /// The last successful call's result, as JSON text. + pub(crate) call_result: Option>, + /// The run's first failed call, which fails the run. + pub(crate) call_failure: Option, pub(crate) report: Report, } @@ -309,6 +401,12 @@ impl Run { storage: None, storage_calls: 0, storage_bytes: 0, + allowed: None, + calls: 0, + call_bytes: 0, + pending: None, + call_result: None, + call_failure: None, report: Report::default(), } } @@ -319,6 +417,119 @@ impl Run { self } + /// From now on, `vc_call` runs the commands in `allowed`. + pub(crate) fn allow_calls(&mut self, allowed: Vec) { + self.allowed = Some(allowed); + } + + /// Records the run's first failed call, `e`, and returns `code`. + fn fail(&mut self, code: i32, e: Error) -> i32 { + self.call_failure.get_or_insert(e); + code + } + + /// `vc_call`: checks the call to the command at `id` with the arguments at `args` in `memory` + /// and leaves it in [`Run::pending`] for the host to make, or → the code for why it can't be + /// made, which fails the run. The size of the arguments is checked before they are read. After + /// the run's first failed call, every call returns [`CALL_NO_CONTEXT`] and none is made. + fn call_request(&mut self, memory: &[u8], id: (usize, usize), args: (usize, usize)) -> std::result::Result<(), i32> { + self.call_result = None; + // No call is made after the run's first failed call. + if self.call_failure.is_some() { + return Err(CALL_NO_CONTEXT); + } + if self.allowed.is_none() { + let why = "vc_call: no command can be called here (while the module loads, or in a run that can't make calls)"; + return Err(self.fail(CALL_NO_CONTEXT, Error::Abi(why.into()))); + } + let shown = || { + id.0.checked_add(id.1) + .filter(|_| id.1 <= crate::manifest::MAX_ALLOWED_ID) + .and_then(|end| memory.get(id.0..end)) + .map_or_else(|| "?".to_string(), |b| permissions::display_text(&String::from_utf8_lossy(b), permissions::MAX_SHOWN_FIELD)) + }; + if args.1 > MAX_CALL_DATA { + let (shown, len) = (shown(), args.1); + return Err(self.fail(CALL_LIMIT, Error::Limit(format!("command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA})")))); + } + if self.calls >= MAX_CALLS || self.call_bytes.saturating_add(args.1) > MAX_CALL_BYTES { + return Err(self.fail(CALL_LIMIT, Error::Limit(format!("command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run)")))); + } + self.calls += 1; + self.call_bytes += args.1; + let slice = |(at, len): (usize, usize)| at.checked_add(len).and_then(|end| memory.get(at..end)); + let (Some(id_bytes), Some(arg_bytes)) = (slice(id).filter(|_| id.1 <= crate::manifest::MAX_ALLOWED_ID), slice(args)) else { + if id.1 > crate::manifest::MAX_ALLOWED_ID { + let shown = shown(); + return Err(self.fail(CALL_NOT_ALLOWED, Error::Abi(format!("vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it")))); + } + let shown = shown(); + return Err( + self.fail(CALL_OUTSIDE_MEMORY, Error::Abi(format!("vc_call `{shown}`: the id or the arguments lie outside the module's memory"))) + ); + }; + let (Ok(name), Ok(text)) = (std::str::from_utf8(id_bytes), std::str::from_utf8(arg_bytes)) else { + let shown = shown(); + return Err(self.fail(CALL_BAD_UTF8, Error::Abi(format!("vc_call `{shown}`: the id or the arguments are not UTF-8")))); + }; + if !self.allowed.as_ref().is_some_and(|allowed| allowed.iter().any(|a| a == name)) { + let shown = shown(); + return Err(self.fail(CALL_NOT_ALLOWED, Error::Abi(format!("vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it")))); + } + let parsed = if text.is_empty() { Ok(serde_json::Value::Object(serde_json::Map::new())) } else { serde_json::from_str(text) }; + match parsed { + Ok(v @ serde_json::Value::Object(_)) => { + self.pending = Some((name.to_string(), v, args.1)); + Ok(()) + } + _ => { + let shown = shown(); + Err(self.fail(CALL_BAD_JSON, Error::Abi(format!("vc_call `{shown}`: the arguments are not a JSON object")))) + } + } + } + + /// Takes the host's answer to the call in [`Run::pending`], to command `id`: keeps its result for + /// `vc_call_result`, or records the failure → what `vc_call` returns. + pub(crate) fn call_answered(&mut self, id: &str, answer: std::result::Result) -> i32 { + let shown = permissions::display_text(id, permissions::MAX_SHOWN_FIELD); + let value = match answer { + Ok(value) => value, + Err(f) => { + let why = f.why; + return self.fail(f.code, Error::Failed(format!("vc_call `{shown}`: {why}"))); + } + }; + let text = serde_json::to_vec(&value).unwrap_or_default(); + let len = text.len(); + if len > MAX_CALL_DATA { + return self.fail(CALL_LIMIT, Error::Limit(format!("command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA})"))); + } + if self.call_bytes.saturating_add(len) > MAX_CALL_BYTES { + return self.fail(CALL_LIMIT, Error::Limit(format!("command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run)"))); + } + self.call_bytes += len; + self.call_result = Some(text); + CALL_OK + } + + /// `vc_call_result`: copies the last successful call's result into the `out_cap` bytes at `out` + /// when it fits → its length, or [`CALL_NO_RESULT`] or [`CALL_OUTSIDE_MEMORY`]. Neither fails + /// the run: a plug-in asks again with a larger buffer. + fn call_result(&self, memory: &mut [u8], out: (usize, usize)) -> i32 { + let Some(result) = &self.call_result else { return CALL_NO_RESULT }; + if out.1 > 0 && out.0.checked_add(out.1).is_none_or(|end| end > memory.len()) { + return CALL_OUTSIDE_MEMORY; + } + if result.len() <= out.1 + && let Some(dest) = memory.get_mut(out.0..out.0 + result.len()) + { + dest.copy_from_slice(result); + } + // At most MAX_CALL_DATA, which an i32 holds. + i32::try_from(result.len()).unwrap_or(CALL_LIMIT) + } + /// Makes one storage call with `call`, on the plug-in's storage and a [`Meter`] holding the /// run's storage bytes left, and counts the call and the bytes it read and wrote → the code for /// a run that has used up its calls or has no storage, else what `call` returns. @@ -534,6 +745,25 @@ pub(crate) fn linker(engine: &Engine, granted: &[Permission]) -> Linker { host.run.storage_remove(area, data, (offset(key), offset(key_len))) }); } + if granted.contains(&Permission::Commands) { + // A call that can be made pauses the run: the host makes it with what the run was given to + // make calls with ([`crate::Plugin::run_calling`]), and resumes the run with the code. + let _ = linker.func_wrap( + MODULE, + "vc_call", + |mut caller: Caller<'_, Host>, id: i32, id_len: i32, args: i32, args_len: i32| -> std::result::Result { + let Some((data, host)) = memory_and_host(&mut caller) else { return Ok(CALL_OUTSIDE_MEMORY) }; + match host.run.call_request(data, (offset(id), offset(id_len)), (offset(args), offset(args_len))) { + Ok(()) => Err(wasmi::Error::host(CallPending)), + Err(code) => Ok(code), + } + }, + ); + let _ = linker.func_wrap(MODULE, "vc_call_result", |mut caller: Caller<'_, Host>, out: i32, out_cap: i32| -> i32 { + let Some((data, host)) = memory_and_host(&mut caller) else { return CALL_OUTSIDE_MEMORY }; + host.run.call_result(data, (offset(out), offset(out_cap))) + }); + } linker } diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index e3f1f76dea..b4faf543db 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -5,7 +5,8 @@ //! //! - **no host imports but those of API level 2** ([`host`]: progress, Cancel and log lines with //! the `progress` permission, and settings and a cache of its own with the `settings` and `cache` -//! permissions, [`storage`]): no WASI, file system, network, clock or randomness. A module that +//! permissions, [`storage`], and the commands its `commandAllowlist` names with the `commands` +//! permission): no WASI, file system, network, clock or randomness. A module that //! imports anything else is rejected; //! - an **instruction budget** (fuel) per call, metered in slices so a wall-clock deadline is //! also enforced (native builds), so infinite loops end with an error. A filter may ask for a diff --git a/crates/plugins/src/manifest.rs b/crates/plugins/src/manifest.rs index d548e64440..a16bd8a4f9 100644 --- a/crates/plugins/src/manifest.rs +++ b/crates/plugins/src/manifest.rs @@ -25,6 +25,12 @@ pub const MAX_COMMANDS: usize = 32; /// Longest command id, in characters. pub const MAX_COMMAND_ID: usize = 32; +/// Most commands a manifest's `commandAllowlist` names. +pub const MAX_ALLOWED_COMMANDS: usize = 256; + +/// Longest command id a manifest's `commandAllowlist` names, in bytes. +pub const MAX_ALLOWED_ID: usize = 128; + /// What a plug-in is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -337,6 +343,11 @@ pub struct Manifest { /// The menu commands it adds, in menu order (a filter or a live effect only). #[serde(default, deserialize_with = "ordered_commands", skip_serializing_if = "Vec::is_empty")] pub commands: Vec, + /// The VectorCraft commands a run may call with `vc_call` (exact command ids, such as + /// `object.transform`): only a filter with the usual budget whose `permissions` list `commands` + /// lists any ([`Manifest::validate`]). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub command_allowlist: Vec, } impl Manifest { @@ -371,6 +382,7 @@ impl Manifest { budget: Budget::Light, paint_output: false, commands: Vec::new(), + command_allowlist: Vec::new(), } } @@ -427,7 +439,40 @@ impl Manifest { } } self.validate_params()?; - self.validate_commands() + self.validate_commands()?; + self.validate_allowlist() + } + + /// `commandAllowlist` lists at most [`MAX_ALLOWED_COMMANDS`] distinct command ids + /// ([`valid_allowed_id`]), and only a filter with the usual budget lists any: a heavy one runs in + /// the background, away from the document its commands would change. A list needs the + /// permission `commands`, and `commands` needs a list. + fn validate_allowlist(&self) -> Result<()> { + let listed = self.permissions.as_ref().is_some_and(|p| p.iter().any(|n| n == Permission::Commands.name())); + if self.command_allowlist.is_empty() == listed { + return Err(Error::Manifest("`commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist`".into())); + } + if self.command_allowlist.is_empty() { + return Ok(()); + } + if self.kind != Kind::Filter || self.budget == Budget::Heavy { + return Err(Error::Manifest("only a filter with the usual budget declares `commandAllowlist`".into())); + } + if self.command_allowlist.len() > MAX_ALLOWED_COMMANDS { + return Err(Error::Manifest(format!("at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist`"))); + } + for (i, id) in self.command_allowlist.iter().enumerate() { + if !valid_allowed_id(id) || self.command_allowlist.get(..i).is_some_and(|before| before.contains(id)) { + let shown = permissions::display_text(id, permissions::MAX_SHOWN_FIELD); + return Err(Error::Manifest(format!("`commandAllowlist` names `{shown}`, which is not a command id or is listed twice"))); + } + } + Ok(()) + } + + /// May a run call command `id` ([`Manifest::command_allowlist`])? + pub fn allows_call(&self, id: &str) -> bool { + self.command_allowlist.iter().any(|a| a == id) } /// Checks each parameter and its dialog layout. @@ -810,6 +855,15 @@ fn params_as_object(p: &[(String, Param)], s: S) -> std::r m.end() } +/// A command id as a `commandAllowlist` names it: 1 to [`MAX_ALLOWED_ID`] bytes from +/// `A-Za-z0-9._-`, starting with a letter, with no empty part between dots. +pub fn valid_allowed_id(id: &str) -> bool { + (1..=MAX_ALLOWED_ID).contains(&id.len()) + && id.bytes().next().is_some_and(|b| b.is_ascii_alphabetic()) + && id.split('.').all(|part| !part.is_empty()) + && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + /// `[A-Za-z0-9._-]{1,64}`. pub fn valid_id(id: &str) -> bool { (1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) diff --git a/crates/plugins/src/permissions.rs b/crates/plugins/src/permissions.rs index 778b19cee8..7380edd568 100644 --- a/crates/plugins/src/permissions.rs +++ b/crates/plugins/src/permissions.rs @@ -5,9 +5,9 @@ //! `doc.read`, `doc.write`, `state` and `progress` are the names of the plug-in capability model in //! storytold/photocraft#662; the other names are VectorCraft's own. A manifest without //! `permissions` gets the ones its kind implies ([`Permission::implied`]): what every plug-in of -//! that kind could do before manifests listed them. `progress`, `settings` and `cache`, which let a -//! plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a manifest -//! lists them. +//! that kind could do before manifests listed them. `progress`, `settings`, `cache` and `commands`, +//! which let a plug-in use the host imports of API level 2 ([`crate::host`]), are never implied: a +//! manifest lists them. use serde::{Deserialize, Serialize}; @@ -19,7 +19,7 @@ use crate::{Error, Kind, Result}; pub const API_LEVEL: u32 = 2; /// The API level that adds the host imports ([`crate::host::IMPORTS`]) and the `progress`, -/// `settings` and `cache` permissions they need. +/// `settings`, `cache` and `commands` permissions they need. pub const PROGRESS_API: u32 = 2; /// The API level that adds a filter's `inputs` ([`crate::InputKind`]). @@ -70,10 +70,14 @@ pub enum Permission { /// Keep a cache of its own, which the user can clear ([`crate::storage`]). #[serde(rename = "cache")] Cache, + /// Run the VectorCraft commands its manifest's `commandAllowlist` names, with `vc_call` + /// ([`crate::host::IMPORTS`]): a filter only. + #[serde(rename = "commands")] + Commands, } /// Every permission this host grants, in the order prompts list them. -pub const ALL: [Permission; 9] = [ +pub const ALL: [Permission; 10] = [ Permission::DocRead, Permission::DocWrite, Permission::State, @@ -83,11 +87,13 @@ pub const ALL: [Permission; 9] = [ Permission::Progress, Permission::Settings, Permission::Cache, + Permission::Commands, ]; /// The permissions of the host imports, which any kind may list and none implies; each needs plug-in -/// API level [`PROGRESS_API`]. -pub const HOST: [Permission; 3] = [Permission::Progress, Permission::Settings, Permission::Cache]; +/// API level [`PROGRESS_API`]. Only a filter with a `commandAllowlist` may list `commands` +/// ([`crate::manifest::Manifest::command_allowlist`]). +pub const HOST: [Permission; 4] = [Permission::Progress, Permission::Settings, Permission::Cache, Permission::Commands]; impl Permission { /// Its name in a manifest and in `plugin.install`'s `grant`. @@ -102,6 +108,7 @@ impl Permission { Permission::Progress => "progress", Permission::Settings => "settings", Permission::Cache => "cache", + Permission::Commands => "commands", } } @@ -122,6 +129,7 @@ impl Permission { Permission::Progress => "Show its progress, see Cancel and write log lines", Permission::Settings => "Keep settings of its own", Permission::Cache => "Keep a cache of its own, which you can clear", + Permission::Commands => "Run these commands", } } diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index e6278fc99a..5abaa0bf48 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -1,11 +1,11 @@ //! The wasmi host: loading, instantiating and calling a plug-in under resource limits. use wasmi::{ - Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, WasmParams, - WasmResults, + Config, CustomFuelCosts, EnforcedLimits, Engine, Instance, Memory, Module, Store, StoreLimitsBuilder, TypedFunc, TypedResumableCall, Val, + WasmParams, WasmResults, }; -use crate::host::{self, Deadline, Host, Report, Run}; +use crate::host::{self, Bridge, Deadline, Host, Report, Run}; use crate::manifest::{MAX_MANIFEST_BYTES, Manifest}; use crate::permissions::Permission; use crate::{Error, Kind, Result}; @@ -132,6 +132,18 @@ impl Live { } } +/// Takes `cost` instructions from a run: from the budget still to hand out (`left`), then from what +/// the store holds. A run that can't pay ends with its instruction budget. +fn charge(live: &mut Live, left: &mut u64, cost: u64) -> Result<()> { + let held = live.store.get_fuel().map_err(wasm_err)?; + if held.saturating_add(*left) < cost { + return Err(Error::Limit("instruction budget".into())); + } + let from_left = cost.min(*left); + *left -= from_left; + live.store.set_fuel(held - (cost - from_left)).map_err(wasm_err) +} + fn wasm_err(e: wasmi::Error) -> Error { if e.as_trap_code() == Some(wasmi::TrapCode::OutOfFuel) { Error::Limit("instruction budget".into()) } else { Error::Trap(e.to_string()) } } @@ -257,6 +269,22 @@ impl Plugin { /// slice size, keeping that fuel, and a run ends with the instruction budget only when the /// store's fuel and the rest of the budget together can't pay for the next instruction. fn call(&self, live: &mut Live, f: &TypedFunc, params: P, fuel: u64, deadline: &Deadline) -> Result { + self.call_with(live, f, params, fuel, deadline, None) + } + + /// [`Plugin::call`], making each command call a `vc_call` pauses it for with `bridge` + /// ([`host::Run::pending`]) and resuming it with the code. Each call costs [`host::CALL_FUEL`] + /// instructions and one for every 64 bytes of its arguments and result; the deadline and the + /// caller's cancellation are checked before and after it. + fn call_with( + &self, + live: &mut Live, + f: &TypedFunc, + params: P, + fuel: u64, + deadline: &Deadline, + mut bridge: Option<&mut Bridge<'_>>, + ) -> Result { let mut left = fuel; let give = left.min(FUEL_SLICE); left -= give; @@ -265,7 +293,22 @@ impl Plugin { loop { match call { TypedResumableCall::Finished(r) => return Ok(r), - TypedResumableCall::HostTrap(_) => return Err(Error::Trap("unexpected host trap".into())), + TypedResumableCall::HostTrap(inv) => { + let pending = live.store.data_mut().run.pending.take(); + let (Some((id, args, size)), Some(bridge)) = (pending, bridge.as_deref_mut()) else { + return Err(Error::Trap("unexpected host trap".into())); + }; + charge(live, &mut left, host::CALL_FUEL.saturating_add(size as u64 / 64))?; + deadline.check()?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + let answer = bridge(&id, &args); + let code = live.store.data_mut().run.call_answered(&id, answer); + let returned = live.store.data().run.call_result.as_ref().map_or(0, Vec::len); + charge(live, &mut left, returned as u64 / 64)?; + deadline.check()?; + vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; + call = inv.resume(&mut live.store, &[Val::I32(code)]).map_err(wasm_err)?; + } TypedResumableCall::OutOfFuel(inv) => { let need = inv.required_fuel(); let held = live.store.get_fuel().map_err(wasm_err)?; @@ -302,30 +345,61 @@ impl Plugin { /// [`vectorcraft_doc::cancel::scope`] its progress goes to the scope's sink (a live effect's /// doesn't) and `vc_cancelled` sees the scope's Cancel. pub fn run_reporting(&self, input: &[u8], params: &[u8], limits: &Limits) -> (Result>, Report) { + self.run_guarded(input, params, limits, None) + } + + /// [`Plugin::run_reporting`] for a filter whose manifest's `commandAllowlist` names commands: + /// each `vc_call` of one of them is made with `bridge`, on the caller's thread, while the run + /// waits. A failed call fails the run, also when the plug-in goes on and returns an output; the + /// error names the command. + pub fn run_calling(&self, input: &[u8], params: &[u8], limits: &Limits, bridge: &mut Bridge<'_>) -> (Result>, Report) { + self.run_guarded(input, params, limits, Some(bridge)) + } + + fn run_guarded(&self, input: &[u8], params: &[u8], limits: &Limits, bridge: Option<&mut Bridge<'_>>) -> (Result>, Report) { let mut report = Report::default(); if let Err(e) = crate::safe_mode::check() { return (Err(e), report); } // wasmi reports misbehaving modules as errors; a panic would be a bug in it, and must // still not take the document down (native builds; wasm aborts on panic anyway). - let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report))); + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_inner(input, params, limits, &mut report, bridge))); (run.map_err(|_| Error::Trap("the runtime panicked".into())).and_then(|r| r), report) } - fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report) -> Result> { + fn run_inner(&self, input: &[u8], params: &[u8], limits: &Limits, report: &mut Report, bridge: Option<&mut Bridge<'_>>) -> Result> { let total = input.len().checked_add(params.len()).filter(|b| *b <= i32::MAX as usize && *b <= self.limits.max_memory_bytes / 2); total.ok_or_else(|| Error::Limit(SELECTION_TOO_LARGE.into()))?; let deadline = Deadline::new(limits.wall_time_ms); let m = &self.manifest; let run = Run::new(&m.id, m.kind != Kind::Effect, true, deadline).with_storage(crate::registry::storage(&m.id)); let mut live = self.instantiate(run, &m.permissions(), report)?; - let out = self.run_live(&mut live, input, params, limits, &deadline); - *report = std::mem::take(&mut live.store.data_mut().run.report); - out + // Calls can be made from `vc_run` on, not from the start function. + if bridge.is_some() { + live.store.data_mut().run.allow_calls(m.command_allowlist.clone()); + } + let out = self.run_live(&mut live, input, params, limits, &deadline, bridge); + let state = &mut live.store.data_mut().run; + *report = std::mem::take(&mut state.report); + // A failed call fails the run, whatever the plug-in did after it, unless the run was + // canceled. + match (state.call_failure.take(), out) { + (_, Err(Error::Cancelled)) => Err(Error::Cancelled), + (Some(e), _) => Err(e), + (None, out) => out, + } } /// Hands `input` and `params` to the instance `live` and runs `vc_run` → the output JSON bytes. - fn run_live(&self, live: &mut Live, input: &[u8], params: &[u8], limits: &Limits, deadline: &Deadline) -> Result> { + fn run_live( + &self, + live: &mut Live, + input: &[u8], + params: &[u8], + limits: &Limits, + deadline: &Deadline, + bridge: Option<&mut Bridge<'_>>, + ) -> Result> { let alloc: TypedFunc = live.func("vc_alloc")?; let run: TypedFunc = live.func("vc_run")?; let place = |live: &mut Live, bytes: &[u8]| -> Result { @@ -341,7 +415,7 @@ impl Plugin { let iptr = place(live, input)?; let pptr = place(live, params)?; let fuel = limits.fuel_base.saturating_add((input.len() as u64).saturating_mul(limits.fuel_per_byte)); - let packed = self.call(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline)?; + let packed = self.call_with(live, &run, (iptr as i32, input.len() as i32, pptr as i32, params.len() as i32), fuel, deadline, bridge)?; // A cancelled run, or one past its time budget, changes nothing, also when the plug-in saw // `vc_cancelled` and returned. vectorcraft_doc::cancel::check().map_err(|_| Error::Cancelled)?; diff --git a/crates/plugins/tests/call.rs b/crates/plugins/tests/call.rs new file mode 100644 index 0000000000..2dd2c7c5e7 --- /dev/null +++ b/crates/plugins/tests/call.rs @@ -0,0 +1,382 @@ +//! `vc_call` and `vc_call_result`: a filter of API level 2 that lists `commands` calls the commands +//! its manifest's `commandAllowlist` names, through what the host gives the run to make them with. +//! Every misuse is a code the plug-in sees, and fails the run. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_plugins::host::{ + CALL_BAD_JSON, CALL_BAD_UTF8, CALL_COMMAND_FAILED, CALL_LIMIT, CALL_NO_CONTEXT, CALL_NO_RESULT, CALL_NOT_ALLOWED, CALL_OUTSIDE_MEMORY, + CallFailure, MAX_CALL_DATA, MAX_CALLS, +}; +use vectorcraft_plugins::{Error, Limits, Manifest, Plugin, wat as tpl}; + +const INPUT: &str = r#"{"objects":[]}"#; + +/// The command imports, as `$vc_call` and `$vc_call_result`, and the strings the tests pass: the id +/// "select.all" at 0x2000, "object.delete" at 0x2010, the arguments `{"a":1}` at 0x2100, the byte +/// 0xff at 0x2200 and `[1]` at 0x2300. 0x3000 is free for a result. +const CALLS: &str = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32))) + (import "env" "vc_call_result" (func $vc_call_result (param i32 i32) (result i32))) + (data (i32.const 0x2000) "select.all") + (data (i32.const 0x2010) "object.delete") + (data (i32.const 0x2100) "{\22a\22:1}") + (data (i32.const 0x2200) "\ff") + (data (i32.const 0x2300) "[1]")"#; + +/// A filter `id` that may call `select.all`. +fn manifest(id: &str) -> String { + format!( + r#"{{"id":"{id}","name":"Caller","kind":"filter","api":2,"permissions":["doc.read","doc.write","commands"],"commandAllowlist":["select.all"]}}"# + ) +} + +/// `vc_call` of the id at `id` (`len` bytes) with the arguments at `args` (`args_len` bytes). +fn call(id: &str, len: &str, args: &str, args_len: &str) -> String { + format!("(call $vc_call (i32.const {id}) (i32.const {len}) (i32.const {args}) (i32.const {args_len}))") +} + +/// `select.all` with `{"a":1}`. +fn select_all() -> String { + call("0x2000", "10", "0x2100", "7") +} + +/// Instructions that trap unless `expr` is `want`. +fn expect(expr: &str, want: i32) -> String { + format!("(if (i32.ne {expr} (i32.const {want})) (then unreachable))") +} + +/// A filter that runs `first`, then returns the input. +fn calling(id: &str, first: &str) -> Plugin { + let src = tpl::with_imports(&manifest(id), CALLS, first, INPUT); + Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap() +} + +/// Runs `p` with a bridge that answers every call with `answer` → the run's result and the calls it +/// got. +fn run_with(p: &Plugin, answer: impl Fn(&str) -> Result) -> (vectorcraft_plugins::Result>, Vec<(String, Value)>) { + let mut seen = Vec::new(); + let mut bridge = |id: &str, args: &Value| { + seen.push((id.to_string(), args.clone())); + answer(id) + }; + let (out, _) = p.run_calling(INPUT.as_bytes(), b"{}", p.limits(), &mut bridge); + (out, seen) +} + +#[test] +fn a_call_runs_its_command_and_the_result_is_read_back() { + // The result `{"n":1}` is 7 bytes: a 2-byte buffer gets its length and nothing copied, then a + // larger one gets it, which the run returns as its output. + let run = format!( + "{} {} (if (i32.ne (i32.load8_u (i32.const 0x3000)) (i32.const 0)) (then unreachable)) {} (i64.or (i64.shl (i64.const 7) (i64.const 32)) (i64.const 0x3000))", + expect(&select_all(), 0), + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 2))", 7), + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 64))", 7), + ); + let src = tpl::module(&manifest("test.call.result"), &run, CALLS, 1); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap(); + let (out, seen) = run_with(&p, |_| Ok(json!({"n": 1}))); + assert_eq!(out.unwrap(), br#"{"n":1}"#); + assert_eq!(seen, [("select.all".to_string(), json!({"a": 1}))]); + // No bytes of arguments are `{}`; a result buffer outside memory is a code, not a failure. + let p = calling( + "test.call.empty", + &[ + expect("(call $vc_call_result (i32.const 0x3000) (i32.const 64))", CALL_NO_RESULT), + expect(&call("0x2000", "10", "0", "0"), 0), + expect("(call $vc_call_result (i32.const -16) (i32.const 64))", CALL_OUTSIDE_MEMORY), + ] + .concat(), + ); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert_eq!(out.unwrap(), INPUT.as_bytes()); + assert_eq!(seen, [("select.all".to_string(), json!({}))]); +} + +/// Each misuse returns its code, and the run fails with an error that names the call, even when the +/// plug-in goes on and returns an output. The host makes no call for any of them. +#[test] +fn a_call_the_host_refuses_fails_the_run_even_when_the_plugin_goes_on() { + let cases = [ + (call("0x2010", "13", "0", "0"), CALL_NOT_ALLOWED, "vc_call `object.delete`: the manifest's `commandAllowlist` doesn't list it"), + (call("0x2000", "10", "0x2200", "1"), CALL_BAD_UTF8, "vc_call `select.all`: the id or the arguments are not UTF-8"), + (call("0x2000", "10", "0x2300", "3"), CALL_BAD_JSON, "vc_call `select.all`: the arguments are not a JSON object"), + (call("0x2000", "10", "0x2100", "3"), CALL_BAD_JSON, "the arguments are not a JSON object"), + (call("0x2000", "10", "-16", "7"), CALL_OUTSIDE_MEMORY, "vc_call `select.all`: the id or the arguments lie outside the module's memory"), + (call("-4", "10", "0", "0"), CALL_OUTSIDE_MEMORY, "vc_call `?`: the id or the arguments lie outside the module's memory"), + (call("0x2000", "200", "0", "0"), CALL_NOT_ALLOWED, "doesn't list it"), + ]; + for (i, (first, code, says)) in cases.into_iter().enumerate() { + let p = calling(&format!("test.call.refused{i}"), &expect(&first, code)); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + let e = out.expect_err(says).to_string(); + assert!(e.contains(says), "{first}: {e}"); + assert!(seen.is_empty(), "{first}"); + } +} + +/// Arguments longer than [`MAX_CALL_DATA`] are refused from their length alone: these 100 MiB start +/// outside memory, and the code is still the size limit. +#[test] +fn oversized_arguments_are_refused_before_they_are_read() { + let p = calling("test.call.huge", &expect(&call("0x2000", "10", "-16", &(100 << 20).to_string()), CALL_LIMIT)); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + let e = out.unwrap_err(); + assert!(matches!(&e, Error::Limit(why) if why.contains(&format!("104857600 bytes, limit {MAX_CALL_DATA}"))), "{e}"); + assert!(seen.is_empty()); +} + +#[test] +fn a_failed_command_fails_the_run_with_its_reason() { + let p = calling("test.call.failed", &expect(&select_all(), CALL_COMMAND_FAILED)); + let (out, seen) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); + assert_eq!(seen.len(), 1); + // Also when the plug-in traps after it: the call's failure is the one reported. + let p = calling("test.call.failed.trap", &format!("(drop {}) unreachable", select_all())); + let (out, _) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); +} + +/// After the run's first failed call, a plug-in that goes on calling gets [`CALL_NO_CONTEXT`] for +/// each call and the host makes none of them; the run fails with the first call's reason. +#[test] +fn no_call_is_made_after_a_failed_one() { + let rest = [select_all(), select_all(), select_all()].map(|c| expect(&c, CALL_NO_CONTEXT)).concat(); + let p = calling("test.call.after.failed", &format!("{}{rest}", expect(&select_all(), CALL_COMMAND_FAILED))); + let (out, seen) = run_with(&p, |_| Err(CallFailure { code: CALL_COMMAND_FAILED, why: "nothing is selected".into() })); + assert_eq!(out, Err(Error::Failed("vc_call `select.all`: nothing is selected".into()))); + assert_eq!(seen.len(), 1); + // Also after a call the host refused without making it. + let p = calling( + "test.call.after.refused", + &format!("{}{}", expect(&call("0x2010", "13", "0", "0"), CALL_NOT_ALLOWED), expect(&select_all(), CALL_NO_CONTEXT)), + ); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert!(out.unwrap_err().to_string().contains("vc_call `object.delete`: the manifest's `commandAllowlist` doesn't list it")); + assert!(seen.is_empty()); +} + +/// A result larger than [`MAX_CALL_DATA`] fails the run, and so do more than [`MAX_CALLS`] calls. +#[test] +fn results_and_calls_are_capped() { + let p = calling("test.call.big", &expect(&select_all(), CALL_LIMIT)); + let (out, _) = run_with(&p, |_| Ok(Value::String("x".repeat(MAX_CALL_DATA)))); + assert!(matches!(out, Err(Error::Limit(ref why)) if why.starts_with("command call size (vc_call `select.all`")), "{out:?}"); + // A result of exactly MAX_CALL_DATA bytes (the string and its two quotes) is kept. + let p = calling("test.call.edge", &expect(&select_all(), 0)); + let (out, _) = run_with(&p, |_| Ok(Value::String("x".repeat(MAX_CALL_DATA - 2)))); + assert_eq!(out.unwrap(), INPUT.as_bytes()); + let many = format!( + "(local $i i32) (loop $l {} (local.set $i (i32.add (local.get $i) (i32.const 1))) (br_if $l (i32.lt_u (local.get $i) (i32.const {MAX_CALLS})))) {}", + expect(&select_all(), 0), + expect(&select_all(), CALL_LIMIT) + ); + let p = calling("test.call.many", &many); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert!(matches!(out, Err(Error::Limit(ref why)) if why.starts_with("command calls (")), "{out:?}"); + assert_eq!(seen.len(), MAX_CALLS); +} + +/// Each call costs instructions, so a budget too small for the calls ends the run: 256,000 (the +/// base and the input's share) pays for 25 calls of 10,000 and the loop around them. +#[test] +fn calls_cost_instructions() { + let many = format!("(loop $l {} (br $l))", expect(&select_all(), 0)); + let src = tpl::with_imports(&manifest("test.call.fuel"), CALLS, &many, INPUT); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits { fuel_base: 200_000, ..Limits::default() }).unwrap(); + let (out, seen) = run_with(&p, |_| Ok(Value::Null)); + assert_eq!(out, Err(Error::Limit("instruction budget".into()))); + assert_eq!(seen.len(), 25); +} + +/// Cancel stops the run at the next call, and what it did is the caller's to undo. +#[test] +fn cancel_stops_a_run_at_its_next_call() { + let p = calling("test.call.cancel", &[expect(&select_all(), 0), expect(&select_all(), 0)].concat()); + let token = vectorcraft_doc::cancel::CancelToken::new(); + let mut calls = 0; + let mut bridge = |_: &str, _: &Value| { + calls += 1; + token.cancel(); + Ok(Value::Null) + }; + let (out, _) = vectorcraft_doc::cancel::scope(&token, None, || p.run_calling(INPUT.as_bytes(), b"{}", p.limits(), &mut bridge)); + assert_eq!(out, Err(Error::Cancelled)); + assert_eq!(calls, 1); +} + +/// Without a bridge (a run that isn't a filter's run on a document), and while the module is being +/// loaded, `vc_call` returns [`CALL_NO_CONTEXT`]; in a run, that fails the run as any failed call +/// does, also when the plug-in goes on. +#[test] +fn without_a_bridge_a_call_returns_no_context() { + let no_context = |out: vectorcraft_plugins::Result>| { + let e = out.unwrap_err(); + assert!(matches!(e, Error::Abi(_)) && e.to_string().contains("no command can be called here"), "{e}"); + }; + // The start function's call gets the code, and the module loads; a run, with a bridge or + // without one, then fails on it, and the bridge is never asked. + let start = format!("(func $start {}) (start $start)", expect(&select_all(), CALL_NO_CONTEXT)); + let src = tpl::with_imports(&manifest("test.call.none"), &format!("{CALLS} {start}"), "", INPUT); + let p = Plugin::load(&wat::parse_str(&src).unwrap(), Limits::default()).unwrap(); + no_context(p.run(INPUT.as_bytes(), b"{}")); + let (out, seen) = run_with(&p, |_| Ok(json!({}))); + no_context(out); + assert!(seen.is_empty()); + // A call from `vc_run` without a bridge. + no_context(calling("test.call.none", &expect(&select_all(), CALL_NO_CONTEXT)).run(INPUT.as_bytes(), b"{}")); +} + +/// A module that imports `vc_call` or `vc_call_result` needs the permission `commands`, which needs +/// `api` 2 and a `commandAllowlist`; only a filter with the usual budget lists one. +#[test] +fn the_call_imports_need_the_commands_permission() { + let import = r#"(import "env" "vc_call_result" (func (param i32 i32) (result i32)))"#; + let without = r#"{"id":"test.call.perm","name":"C","kind":"filter","api":2,"permissions":["doc.read"]}"#; + let e = Plugin::load(&wat::parse_str(tpl::with_imports(without, import, "", INPUT)).unwrap(), Limits::default()).unwrap_err().to_string(); + assert!( + e.contains("imports `env.vc_call_result`, which a plug-in may use only at plug-in API level 2 (`api` 2) and with the permission `commands`"), + "{e}" + ); + for (manifest, says) in [ + (r#"{"id":"a","name":"x","kind":"filter","permissions":["commands"],"commandAllowlist":["select.all"]}"#, "needs plug-in API level 2"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"]}"#, "`commands` needs a `commandAllowlist`"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"commandAllowlist":["select.all"]}"#, "`commandAllowlist` needs the permission `commands`"), + ( + r#"{"id":"a","name":"x","kind":"effect","api":2,"permissions":["doc.read","effect.render","commands"],"commandAllowlist":["select.all"]}"#, + "only a filter with the usual budget", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"budget":"heavy","permissions":["commands"],"commandAllowlist":["select.all"]}"#, + "only a filter with the usual budget", + ), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select.all","select.all"]}"#, + "names `select.all`", + ), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select..all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["1select"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[""]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select/all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["select\\all"]}"#, "not a command id"), + (r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["../select.all"]}"#, "not a command id"), + ( + r#"{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[]}"#, + "`commands` needs a `commandAllowlist`", + ), + ] { + let e = Manifest::parse(manifest.as_bytes()).unwrap_err().to_string(); + assert!(e.contains(says), "{manifest}: {e}"); + } + let long = format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":["{}"]}}"#, "a".repeat(129)); + assert!(Manifest::parse(long.as_bytes()).unwrap_err().to_string().contains("not a command id")); + let ids: Vec = (0..257).map(|i| format!("\"c{i}\"")).collect(); + let many = format!(r#"{{"id":"a","name":"x","kind":"filter","api":2,"permissions":["commands"],"commandAllowlist":[{}]}}"#, ids.join(",")); + assert!(Manifest::parse(many.as_bytes()).unwrap_err().to_string().contains("at most 256 commands")); + let m = Manifest::parse(manifest("test.call.ok").as_bytes()).unwrap(); + assert!(m.allows_call("select.all") && !m.allows_call("select.none")); + assert_eq!(serde_json::to_value(&m).unwrap()["commandAllowlist"], json!(["select.all"])); +} + +/// A small xorshift generator, so the cases are the same on every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// Up to `max` random bytes. + fn bytes(&mut self, max: u64) -> Vec { + (0..self.below(max + 1)).map(|_| self.next() as u8).collect() + } + + /// A random JSON value nested at most `depth` deep. + fn json(&mut self, depth: u32) -> Value { + match self.below(if depth == 0 { 4 } else { 6 }) { + 0 => Value::Null, + 1 => Value::Bool(self.below(2) == 0), + 2 => json!((self.next() as i64) >> self.below(64)), + 3 => Value::String(String::from_utf8_lossy(&self.bytes(12)).into_owned()), + 4 => Value::Array((0..self.below(4)).map(|_| self.json(depth - 1)).collect()), + _ => Value::Object((0..self.below(4)).map(|i| (format!("k{i}"), self.json(depth - 1))).collect()), + } + } +} + +/// Any bytes as a call's id and arguments: random bytes, JSON values of every kind, cut-off and +/// corrupted JSON, ids with path characters or a NUL, and arguments of exactly [`MAX_CALL_DATA`] +/// bytes and one byte more. The host makes the call only for a listed id with a JSON object of at +/// most [`MAX_CALL_DATA`] bytes; every other call gets a code and fails the run with an error, and +/// none panics. The plug-in calls with its parameters as the id and its input as the arguments. +#[test] +fn any_bytes_as_a_call_get_a_code() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + let ids: [&[u8]; 7] = [b"select.all", b"select.al", b"select.all\0", b"../select.all", b"select/all", b"\xff\xfe", b""]; + let mut cases: Vec<(Vec, Vec)> = Vec::new(); + for i in 0..600 { + let args = match i % 4 { + 0 => rng.bytes(48), + 1 => serde_json::to_vec(&rng.json(3)).unwrap(), + 2 => { + let mut v = serde_json::to_vec(&rng.json(3)).unwrap(); + v.truncate(rng.below(v.len() as u64 + 1) as usize); + v + } + _ => { + let mut v = serde_json::to_vec(&json!({"a": rng.json(3)})).unwrap(); + let at = rng.below(v.len() as u64) as usize; + v[at] = rng.next() as u8; + v + } + }; + let id = if rng.below(3) == 0 { rng.bytes(16) } else { ids[rng.below(ids.len() as u64) as usize].to_vec() }; + cases.push((args, id)); + } + for len in [MAX_CALL_DATA, MAX_CALL_DATA + 1] { + let mut v = br#"{"a":""#.to_vec(); + v.resize(len - 2, b'x'); + v.extend_from_slice(br#""}"#); + cases.push((v, b"select.all".to_vec())); + } + let p = calling("test.call.fuzz", "(drop (call $vc_call (local.get $pp) (local.get $pl) (local.get $in) (local.get $il)))"); + let mut made = 0; + for (args, id) in &cases { + let mut seen = Vec::new(); + let mut bridge = |_: &str, a: &Value| { + seen.push(a.clone()); + Ok(Value::Null) + }; + let (out, _) = p.run_calling(args, id, p.limits(), &mut bridge); + let object = if args.len() > MAX_CALL_DATA { + None + } else if args.is_empty() { + Some(json!({})) + } else { + serde_json::from_slice::(args).ok().filter(Value::is_object) + }; + let shown = String::from_utf8_lossy(&args[..args.len().min(64)]).into_owned(); + match object.filter(|_| id.as_slice() == b"select.all") { + Some(v) => { + assert_eq!(out.as_deref().ok(), Some(INPUT.as_bytes()), "{shown}"); + assert_eq!(seen, [v], "{shown}"); + made += 1; + } + None => { + assert!(seen.is_empty(), "{shown}"); + let e = out.expect_err(&shown); + assert!(matches!(e, Error::Abi(_) | Error::Limit(_)), "{shown}: {e}"); + } + } + } + // Both kinds of case came up: calls made and calls refused. + assert!(made >= 5 && made < cases.len() - 5, "{made} of {}", cases.len()); +} diff --git a/crates/render/src/fx/bounds.rs b/crates/render/src/fx/bounds.rs index 9bc9ba7565..9d5e9c0d1a 100644 --- a/crates/render/src/fx/bounds.rs +++ b/crates/render/src/fx/bounds.rs @@ -445,7 +445,8 @@ fn three_d_bounds(symbols: &SymbolBoxes, n: &Node) -> Option> { if !effects::has_revolve(n) && !effects::has_solid(n) { return None; } - let art = effects::revolve_art(n).or_else(|| effects::solid_art(n))?; + let doc = Some(symbols.document()); + let art = effects::revolve_art_in(doc, n).or_else(|| effects::solid_art_in(doc, n))?; Some(three_d_art_bounds(symbols, &art)) } diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index 75143f9a06..e9aa8486d8 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -588,7 +588,7 @@ impl Renderer { let art = match effects::crop_marks_art(a) .or_else(|| crate::addons::halftone::art(doc, a)) .or_else(|| { - let art = effects::revolve_art(a).or_else(|| effects::solid_art(a)); + let art = effects::revolve_art_in(Some(doc), a).or_else(|| effects::solid_art_in(Some(doc), a)); self.stats.three_d_built += usize::from(art.is_some()); three_d |= art.is_some(); art diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index 5c4474b229..c03a6cc0f3 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -612,6 +612,96 @@ fn an_export_and_rasterize_hold_the_solid_of_3d_type() { assert!(rasterized.width() > letters.width() + 15.0, "{letters:?} {rasterized:?}"); } +/// A symbol instance, a blend and a clipping group with Extrude & Bevel, alone or in a group, draw +/// their solids on the canvas, in an export and in Object › Rasterize, not their flat art. +#[test] +fn a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids() { + use vectorcraft_doc::{BlendSpacing, BlendSpec, NodeId, NodeKind, Symbol}; + let square = |x: f64, y: f64| { + Arc::new(Node::path( + NodeId(0), + shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0), + )) + }; + let mut d = Document::new(200.0, 200.0); + d.symbols.push(Symbol { dynamic: false, name: "Box".into(), art: square(0.0, 0.0) }); + let mut clip = (*square(30.0, 30.0)).clone(); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(2), ..Default::default() }); + let instance = NodeKind::SymbolInstance { symbol: "Box".into(), xf: Affine::translate((40.0, 40.0)) }; + let clipped = NodeKind::Group { children: vec![Arc::new(clip), square(20.0, 20.0)], clip: true }; + let in_group = |kind: NodeKind| NodeKind::Group { children: vec![Arc::new(Node::new(NodeId(0), kind)), square(100.0, 100.0)], clip: false }; + let kinds = [ + ("a symbol instance", instance.clone()), + ("a blend", NodeKind::Blend { children: vec![square(30.0, 30.0), square(60.0, 40.0)], spec }), + ("a clipping group", clipped.clone()), + ("a group holding a symbol instance", in_group(instance)), + ("a group holding a clipping group", in_group(clipped)), + ]; + for (what, kind) in kinds { + let mut n = Node::new(d.alloc_id(), kind); + let flat = crate::encode::art_bounds(&doc_of(&mut d.clone(), n.clone())).unwrap(); + n.appearance.effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 60.0, "position": "isometricTop"}), visible: true }]; + let solid_doc = doc_of(&mut d.clone(), n); + let n = &solid_doc.layers[0].children().unwrap()[0]; + let (solid, rasterized) = (crate::encode::art_bounds(&solid_doc).unwrap(), crate::drawn_bounds(&solid_doc, n).unwrap()); + let size = |r: Rect| r.width() + r.height(); + assert!(size(solid) > size(flat) + 20.0, "{what}: {flat:?} {solid:?}"); + assert!(size(rasterized) > size(flat) + 20.0, "{what}: {flat:?} {rasterized:?}"); + // The renderer builds the solid from the object itself, with the document's symbols, as + // the effect builds it: one solid built, not the object's art drawn again with the effect. + let built = vectorcraft_effects::solid_art_in(Some(&solid_doc), n).and_then(|a| a.visual_bounds()).unwrap(); + assert!((solid.x0 - built.x0).abs() < 1.0 && (solid.x1 - built.x1).abs() < 1.0, "{what}: {built:?} {solid:?}"); + let mut r = Renderer::new(); + r.art_bounds_on(&solid_doc, Rect::new(0.0, 0.0, 200.0, 200.0)); + assert_eq!(r.stats.three_d_built, 1, "{what}"); + } +} + +/// A loaded file can hold a 3D effect on art past the limits commands check: a blend of more +/// than 4,096 objects, art nested more than 64 levels deep in a clipping group. The art then draws +/// as it does without the effect, and drawing it does not fail. +#[test] +fn art_past_the_three_d_limits_draws_as_without_the_effect() { + use vectorcraft_doc::{BlendSpacing, BlendSpec, NodeId, NodeKind}; + let square = |x: f64| { + Arc::new(Node::path( + NodeId(0), + shapes::rectangle(Rect::new(x, 10.0, x + 20.0, 30.0)), + Appearance::basic(Paint::solid(Color::rgb(0.2, 0.5, 0.8)), Paint::None, 0.0), + )) + }; + let mut clip = (*square(0.0)).clone(); + if let NodeKind::Path { clipping, .. } = &mut clip.kind { + *clipping = true; + } + let mut deep = (*square(0.0)).clone(); + for _ in 0..200 { + deep = Node::group(NodeId(0), vec![Arc::new(deep)]); + } + let spec = Box::new(BlendSpec { spacing: BlendSpacing::Steps(1000), ..Default::default() }); + let kinds = [ + ("a blend of 6,000 objects", NodeKind::Blend { children: (0..6).map(|i| square(30.0 * i as f64)).collect(), spec }), + ("art 200 levels deep in a clip", NodeKind::Group { children: vec![Arc::new(clip), Arc::new(deep)], clip: true }), + ]; + let d = Document::new(200.0, 200.0); + for (what, kind) in kinds { + let mut n = Node::new(NodeId(500), kind); + let flat = crate::encode::art_bounds(&doc_of(&mut d.clone(), n.clone())).unwrap(); + n.appearance.effects = + vec![Effect { id: "threeD.extrude".into(), params: json!({"depth": 60.0, "position": "isometricTop"}), visible: true }]; + let loaded = doc_of(&mut d.clone(), n); + let n = &loaded.layers[0].children().unwrap()[0]; + assert!(vectorcraft_effects::validate_three_d_in(Some(&loaded), n, "threeD.extrude", &json!({})).is_err(), "{what}"); + assert_eq!(crate::encode::art_bounds(&loaded), Some(flat), "{what}"); + assert!(crate::drawn_bounds(&loaded, n).is_some(), "{what}"); + } +} + fn doc_of(d: &mut Document, n: Node) -> Document { let l = d.layers[0].id; d.insert(Some(l), 0, n).unwrap(); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 8c13a9b612..7bb471a76e 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -137,6 +137,35 @@ fn summary_warnings_are_translated() { assert_eq!(warning_line(fr, "no row: for this note"), "⚠ no row\u{a0}: for this note"); } +/// The warnings and the error for a page longer than 14,400 pt are translated: a PDF 1.5 file +/// written as PDF 1.6, a page with a `UserUnit`, a PDF/X-4 page in points, a refused PDF/X-1a +/// file and a page too narrow for the `UserUnit` its long side needs. +#[test] +fn long_page_notes_are_translated() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 56_692.91, "height": 2_834.65})).unwrap(); + let mut notes: Vec = vec![]; + for p in [json!({"compatibility": "1.5"}), json!({"preset": "PDF/X-4:2010"})] { + let r = s.execute("document.exportPdf", &p).unwrap(); + let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); + notes.extend(warnings.filter(|w| w.contains("14,400 pt")).map(str::to_string)); + } + notes.push(s.execute("document.exportPdf", &json!({"preset": "PDF/X-1a:2001"})).unwrap_err().to_string()); + s.execute("file.new", &json!({"width": 85_040, "height": 17})).unwrap(); + let r = s.execute("document.exportPdf", &json!({})).unwrap(); + let warnings = r["warnings"].as_array().unwrap().iter().filter_map(|w| w.as_str()); + notes.extend(warnings.filter(|w| w.contains("too long and narrow")).map(str::to_string)); + assert_eq!(notes.len(), 5, "{notes:?}"); + let english = ["has no UserUnit, which", "apps that ignore UserUnit", "apps that keep to the limit", "real numbers up to", "too long and narrow"]; + for code in ["de", "fr", "ja", "zh-hans"] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + for note in ¬es { + let shown = warning_line(lang, note); + assert!(english.iter().all(|e| !shown.contains(e)), "{code}: {shown}"); + } + } +} + /// A placed image whose pixel data can't be decoded is left out of the PDF, and the status bar /// shows the note raster exports give. #[test] diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 7783e205f8..c5bdfea5c8 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -660,6 +660,7 @@ impl PluginIntField { budget: Default::default(), paint_output: false, commands: Vec::new(), + command_allowlist: Vec::new(), }; let mut f = PluginIntField { ctx, d: Dialog::new(plugin::KIND, json!({ "seed": start })), m, pos: egui::Pos2::ZERO }; fn number_rect(shape: &egui::Shape, text: &str) -> Option { diff --git a/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs b/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs index 75aecde466..46c912170b 100644 --- a/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs +++ b/crates/ui-egui/src/dialogs/tests_revolve_gizmo.rs @@ -315,22 +315,18 @@ impl Harness { } } -fn clipping_group() -> Vec<(&'static str, Value)> { - vec![ - ("shape.ellipse", json!({"x":20,"y":20,"width":100,"height":100})), - ("shape.rectangle", json!({"x":60,"y":60,"width":100,"height":100})), - ("select.all", json!({})), - ("object.clippingMask.make", json!({})), - ] +fn an_image() -> Vec<(&'static str, Value)> { + let data = vectorcraft_format::base64_encode(&crate::tests_sysclip::blue_png()); + vec![("file.place", json!({"name": "blue.png", "dataBase64": data, "link": false, "at": [150, 150]}))] } /// #6140: on an object a 3D effect can't take, the dialog says why in its own words, and OK, which /// could only fail, is off, where it used to look as if OK did nothing. #[test] fn a_refused_3d_effect_says_why_and_turns_ok_off() { - let mut h = Harness::extrude_dialog(&clipping_group(), true); + let mut h = Harness::extrude_dialog(&an_image(), true); assert!(!h.ok_is_on()); - assert!(h.shows("requires a path")); + assert!(h.shows("can't build a solid from an image")); assert!(!h.shows("effect.apply"), "the reason is written without the command's id"); let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; h.frame(vec![enter], Modifiers::NONE); @@ -341,9 +337,9 @@ fn a_refused_3d_effect_says_why_and_turns_ok_off() { /// and trying it leaves no preview open. #[test] fn a_refused_3d_effect_is_found_with_preview_off() { - let mut h = Harness::extrude_dialog(&clipping_group(), false); + let mut h = Harness::extrude_dialog(&an_image(), false); assert!(!h.ok_is_on()); - assert!(h.shows("requires a path")); + assert!(h.shows("can't build a solid from an image")); assert!(!h.app.session.in_interaction()); } @@ -351,7 +347,7 @@ fn a_refused_3d_effect_is_found_with_preview_off() { /// one would replace its preview and cancel it. #[test] fn a_3d_effect_with_preview_off_leaves_another_interaction_alone() { - let mut h = Harness::extrude_dialog(&clipping_group(), false); + let mut h = Harness::extrude_dialog(&an_image(), false); h.app.session.begin_interaction("Drag").unwrap(); let d = h.app.ui.dialog.as_mut().unwrap(); d.fields.remove("__tried"); @@ -360,7 +356,7 @@ fn a_3d_effect_with_preview_off_leaves_another_interaction_alone() { assert!(h.app.session.in_interaction(), "the other interaction goes on"); assert!(h.ok_is_on(), "nothing has tried the values yet"); h.app.session.cancel_interaction().unwrap(); - assert!(h.shows("requires a path")); + assert!(h.shows("can't build a solid from an image")); assert!(!h.ok_is_on()); assert!(!h.app.session.in_interaction()); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bfb2804c9b..354d811a34 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4995,7 +4995,8 @@ lighting Light Светлина Bevel both sides Фасет от двете страни Presets Предварителни настройки @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Един обект може да има само един 3D ефект. Редактирайте параметрите на съществуващия ефект или го премахнете предварително. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} в момента изисква път или съставен път. Първо преобразувайте текста, изображенията и групите в пътища. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} в момента изисква път, съставен път, текст, група, преливане или екземпляр на символ. Първо разширете другите обекти. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} не може да създаде тяло от изображение: първо го трасирайте с Обект › Трасиране на изображение › Създаване. @msg {label} requires a shape with at least two anchors {label} изисква форма с поне две опорни точки @msg The shape is too complex for a 3D effect Формата е твърде сложна за 3D ефект @msg The 3D surface is too complex; simplify the shape 3D повърхността е твърде сложна; опростете формата @@ -5802,6 +5803,7 @@ axis Y Axis Y ос Show its progress, see Cancel and write log lines Показване на напредъка, разпознаване на отказ и записване на редове в дневника Keep settings of its own Съхраняване на собствени настройки Keep a cache of its own, which you can clear Съхраняване на собствен кеш, който можете да изчистите + Run these commands on the document: {ids} Изпълняване на тези команди върху документа: {ids} Clear Plug-in Cache Изчистване на кеша на добавката # Actions panel: action sets (#3712). New Set… Нов набор… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 12a1714be8..d1fc0ea540 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5504,7 +5504,8 @@ mark-style Japanese Japanski Bevel both sides Zakošenje s obje strane Presets Unaprijed postavljene vrijednosti @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objekat prima jedan 3D efekat. Uredite opcije postojećeg efekta ili ga prvo uklonite. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} trenutno zahtijeva putanju ili složenu putanju. Prvo pretvorite tekst, slike i grupe u putanje. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} trenutno zahtijeva putanju, složenu putanju, tekst, grupu, stapanje ili instancu simbola. Prvo proširite ostale objekte. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ne može napraviti tijelo od slike: prvo je pratite pomoću Objekat › Praćenje slike › Napravi. @msg {label} requires a shape with at least two anchors {label} zahtijeva oblik s najmanje dva sidra @msg The shape is too complex for a 3D effect Oblik je previše složen za 3D efekat @msg The 3D surface is too complex; simplify the shape 3D površina je previše složena; pojednostavite oblik @@ -5824,6 +5825,7 @@ axis Y Axis Y osa Show its progress, see Cancel and write log lines Prikazati napredak, prepoznati otkazivanje i zapisivati redove dnevnika Keep settings of its own Čuvati vlastite postavke Keep a cache of its own, which you can clear Čuvati vlastitu predmemoriju koju možete očistiti + Run these commands on the document: {ids} Izvršavati ove naredbe na dokumentu: {ids} Clear Plug-in Cache Očisti predmemoriju dodatka @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} dozvola `{permission}` zahtijeva nivo API-ja dodataka {PROGRESS_API}: navedite `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modul uvozi `env.{name}` s drugim tipom od domaćinovog: domaćinov tip je {signature} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index d84e3a76ce..9e77ecb32f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5292,6 +5292,11 @@ digits Malayalam Malaiàlam @msg Invalid panel layout; restored the default dock Disposició de panells no vàlida; s’ha restaurat l’acoblament per defecte @msg invalid parameters for `{cmd}`: {msg} paràmetres no vàlids per a `{cmd}`: {msg} @msg invalid PDF setting: {0} configuració del PDF no vàlida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): s’escriu amb un UserUnit de {unit}, de manera que les aplicacions que ignoren UserUnit la mostren tantes vegades més petita +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pàgina del tauler {n} fa {size}, més que el límit de pàgina del PDF de 14.400 pt (200 in): les pàgines {label} s’escriuen sense UserUnit, en punts, i les aplicacions que respecten el límit retallen la pàgina a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 el PDF 1.5 no té UserUnit, que una pàgina de més de 14.400 pt (200 in) necessita per mantenir la mida: el fitxer s’escriu com a PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pàgina del tauler {n} fa {size}, massa llarga i estreta per als costats de pàgina del PDF de 3 a 14.400 unitats: s'escriu amb una UserUnit de {unit}, que manté el costat curt en 3 unitats o més, i les aplicacions que respecten el límit retallen el costat llarg a 14.400 unitats +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard els fitxers {label} admeten nombres reals fins a {max}, i la pàgina del tauler {n}, de {side} pt, en necessita de més grans: trieu PDF 1.6 o posterior sense estàndard PDF/X, o un tauler més petit @msg Invalid real scale Escala real no vàlida @msg invalid restored panel group grup de panells restaurat no vàlid @msg invalid stroke widths amplades de traç no vàlides @@ -5956,7 +5961,8 @@ digits Malayalam Malaiàlam @msg {key} must be a finite coordinate {key} ha de ser una coordenada finita @msg {key} must be an array of non-negative integer object ids {key} ha de ser una matriu d’identificadors d’objecte enters no negatius @msg {key} must be Unix seconds (an integer) or null {key} ha de ser segons Unix (un enter) o null -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} actualment requereix un traçat, un traçat compost, text o un grup. Converteix primer les imatges i altres objectes en traçats. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} actualment requereix un traçat, un traçat compost, text, un grup, una fusió o una instància de símbol. Expandeix primer els altres objectes. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} no pot crear un sòlid a partir d’una imatge: traça-la primer amb Objecte › Traçat d’imatge › Crea. @msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} conserva 1 dels {n} taulers del document: el fitxer es reobre amb un. Activa Conserva les capacitats d’edició per conservar-los tots. @msg {label} produced an empty result {label} ha produït un resultat buit @msg {label} requires a shape with at least two anchors {label} requereix una forma amb com a mínim dos punts d’ancoratge @@ -5991,6 +5997,20 @@ digits Malayalam Malaiàlam Show its progress, see Cancel and write log lines Mostrar el progrés, detectar la cancel·lació i escriure línies de registre Keep settings of its own Desar una configuració pròpia Keep a cache of its own, which you can clear Desar una memòria cau pròpia, que podeu buidar + Run these commands on the document: {ids} Executar aquestes ordres al document: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» inclou `{id}` a `commandAllowlist`, que un complement no pot cridar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: el `commandAllowlist` del manifest no la inclou +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: l’ID o els arguments són fora de la memòria del mòdul +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: l’ID o els arguments no són UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: els arguments no són un objecte JSON +@msg only a filter with the usual budget declares `commandAllowlist` només un filtre amb el pressupost habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) crides d’ordres ({MAX_CALLS} crides i {MAX_CALL_BYTES} bytes per execució) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) mida d’una crida d’ordre (vc_call `{shown}`: {len} bytes, límit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` com a màxim {MAX_ALLOWED_COMMANDS} ordres a `commandAllowlist` +@msg a plug-in may not call this command un complement no pot cridar aquesta ordre +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` necessita el permís `commands`, i `commands` necessita un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` inclou `{shown}`, que no és un ID d’ordre o hi apareix dues vegades Clear Plug-in Cache Buida la memòria cau del complement @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} el permís `{permission}` necessita el nivell d’API de complements {PROGRESS_API}: indiqueu `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} el mòdul importa `env.{name}` amb un tipus diferent del de l’amfitrió: el de l’amfitrió és {signature} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 3d6b0d2d90..de1723b906 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4648,6 +4648,11 @@ imageTrace Outline Obrys @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) vnitřní chyba v `{cmd}`: {msg} (dokument zůstal ve stavu před příkazem; nahlaste prosím tuto chybu) @msg internal error: {msg} (please report this bug) vnitřní chyba: {msg} (nahlaste prosím tuto chybu) @msg invalid PDF setting: {0} neplatné nastavení PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): zapisuje se s UserUnit {unit}, takže aplikace, které UserUnit ignorují, ji zobrazí tolikrát menší +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in stránka pracovní plochy {n} má {size}, což přesahuje limit stránky PDF 14 400 pt (200 in): stránky {label} se zapisují bez UserUnit, v bodech, a aplikace, které limit dodržují, stránku oříznou na 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nemá UserUnit, který stránka delší než 14 400 pt (200 in) potřebuje, aby si zachovala velikost: soubor se zapíše jako PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units stránka pracovní plochy {n} má rozměr {size} a je příliš dlouhá a úzká pro strany stránky PDF od 3 do 14 400 jednotek: zapisuje se s UserUnit {unit}, která drží kratší stranu na 3 jednotkách nebo více, a aplikace, které limit dodržují, ořežou delší stranu na 14 400 jednotek +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard soubory {label} pojmou reálná čísla nejvýše {max} a stránka pracovní plochy {n}, dlouhá {side} pt, potřebuje větší: zvolte PDF 1.6 nebo novější bez standardu PDF/X, nebo menší pracovní plochu @msg invalid image data for `{0}` neplatná obrazová data pro `{0}` @msg invalid parameters for `{cmd}`: {msg} neplatné parametry pro `{cmd}`: {msg} @msg is not an image VectorCraft reads není obraz, který VectorCraft umí přečíst @@ -5616,7 +5621,8 @@ mark-style Japanese Japonské Bevel both sides Zkosení na obou stranách Presets Předvolby @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objekt může mít jen jeden 3D efekt. Upravte volby stávajícího efektu, nebo jej nejprve odstraňte. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} zatím vyžaduje cestu, složenou cestu, text nebo skupinu. Obrazy a další objekty nejprve převeďte na cesty. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} zatím vyžaduje cestu, složenou cestu, text, skupinu, prolnutí nebo instanci symbolu. Ostatní objekty nejprve rozložte. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} nedokáže vytvořit těleso z obrazu: nejprve jej vektorizujte příkazem Objekt › Vektorizace obrazu › Vytvořit. @msg {label} requires a shape with at least two anchors {label} vyžaduje tvar alespoň se dvěma kotevními body @msg The shape is too complex for a 3D effect Tvar je pro 3D efekt příliš složitý @msg The 3D surface is too complex; simplify the shape 3D povrch je příliš složitý; zjednodušte tvar @@ -5970,6 +5976,20 @@ axis Y Axis osa Y Show its progress, see Cancel and write log lines Zobrazit průběh, rozpoznat zrušení a zapisovat řádky protokolu Keep settings of its own Uchovávat vlastní nastavení Keep a cache of its own, which you can clear Uchovávat vlastní mezipaměť, kterou můžete vymazat + Run these commands on the document: {ids} Spouštět v dokumentu tyto příkazy: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ uvádí v `commandAllowlist` příkaz `{id}`, který zásuvný modul nesmí volat +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` manifestu ho neuvádí +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID nebo argumenty leží mimo paměť modulu +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID nebo argumenty nejsou v UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenty nejsou objekt JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` deklaruje pouze filtr s obvyklým rozpočtem +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) volání příkazů ({MAX_CALLS} volání a {MAX_CALL_BYTES} bajtů na běh) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) velikost volání příkazu (vc_call `{shown}`: {len} bajtů, limit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` nejvýše {MAX_ALLOWED_COMMANDS} příkazů v `commandAllowlist` +@msg a plug-in may not call this command zásuvný modul nesmí volat tento příkaz +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` potřebuje oprávnění `commands` a `commands` potřebuje `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` uvádí `{shown}`, což není ID příkazu nebo je uvedeno dvakrát Clear Plug-in Cache Vymazat mezipaměť zásuvného modulu @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} oprávnění `{permission}` vyžaduje úroveň API zásuvných modulů {PROGRESS_API}: uveďte `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modul importuje `env.{name}` s jiným typem, než má hostitel: typ hostitele je {signature} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 7c06c069f2..77687493e5 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5157,7 +5157,8 @@ mark-style Japanese Japansk Bevel both sides Facet på begge sider Presets Forudindstillinger @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Et objekt kan kun have én 3D-effekt. Redigér den eksisterende effekts indstillinger, eller fjern den først. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} kræver i øjeblikket en sti eller en sammensat sti. Konvertér tekst, billeder og grupper til stier først. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} kræver i øjeblikket en sti, en sammensat sti, tekst, en gruppe, en blanding eller en symbolforekomst. Udvid andre objekter først. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan ikke bygge et legeme ud fra et billede: spor det først med Objekt › Billedsporing › Opret. @msg {label} requires a shape with at least two anchors {label} kræver en form med mindst to ankerpunkter @msg The shape is too complex for a 3D effect Formen er for kompleks til en 3D-effekt @msg The 3D surface is too complex; simplify the shape 3D-fladen er for kompleks; forenkl formen @@ -5817,6 +5818,7 @@ axis Y Axis Y-akse Show its progress, see Cancel and write log lines Vise sin fremdrift, se en annullering og skrive logrækker Keep settings of its own Gemme sine egne indstillinger Keep a cache of its own, which you can clear Gemme sin egen cache, som du kan rydde + Run these commands on the document: {ids} Køre disse kommandoer på dokumentet: {ids} Clear Plug-in Cache Ryd plug-in-cache # Actions panel: action sets (#3712). New Set… Nyt sæt… diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index bc6c36435d..7e2619386b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4254,6 +4254,11 @@ theme Appearance Erscheinungsbild @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) interner Fehler in `{cmd}`: {msg} (das Dokument wurde im vorherigen Zustand belassen; bitte melden Sie diesen Fehler) @msg internal error: {msg} (please report this bug) interner Fehler: {msg} (bitte melden Sie diesen Fehler) @msg invalid PDF setting: {0} ungültige PDF-Einstellung: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): sie wird mit einer UserUnit von {unit} geschrieben, daher zeigen Apps, die UserUnit ignorieren, sie entsprechend oft kleiner an +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in die Seite der Zeichenfläche {n} ist {size} groß und damit länger als die PDF-Seitengrenze von 14.400 pt (200 in): {label}-Seiten werden ohne UserUnit in Punkt geschrieben, und Apps, die die Grenze einhalten, schneiden die Seite auf 200 in ab +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 hat keine UserUnit, die eine Seite länger als 14.400 pt (200 in) braucht, um ihre Größe zu behalten: die Datei wird als PDF 1.6 geschrieben +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units die Seite der Zeichenfläche {n} ist {size} groß und damit zu lang und schmal für PDF-Seitenlängen von 3 bis 14.400 Einheiten: sie wird mit einer UserUnit von {unit} geschrieben, die die kurze Seite bei mindestens 3 Einheiten hält, und Apps, die die Grenze einhalten, schneiden die lange Seite auf 14.400 Einheiten ab +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-Dateien fassen reelle Zahlen bis {max}, und die Seite der Zeichenfläche {n} mit {side} pt Länge braucht größere: wählen Sie PDF 1.6 oder höher ohne PDF/X-Standard oder eine kleinere Zeichenfläche @msg invalid image data for `{0}` ungültige Bilddaten für `{0}` @msg invalid parameters for `{cmd}`: {msg} ungültige Parameter für `{cmd}`: {msg} @msg is not an image VectorCraft reads ist kein Bild, das VectorCraft lesen kann @@ -5183,7 +5188,8 @@ lighting Light Licht Bevel both sides Abgeflachte Kante beidseitig Presets Vorgaben @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ein Objekt kann nur einen 3D-Effekt haben. Bearbeiten Sie die Optionen des vorhandenen Effekts oder entfernen Sie ihn zuerst. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} erfordert derzeit einen Pfad, zusammengesetzten Pfad, Text oder eine Gruppe. Wandeln Sie Bilder und andere Objekte zuerst in Pfade um. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} erfordert derzeit einen Pfad, zusammengesetzten Pfad, Text, eine Gruppe, eine Angleichung oder eine Symbolinstanz. Wandeln Sie andere Objekte zuerst um. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kann aus einem Bild keinen Körper erstellen: Zeichnen Sie es zuerst mit Objekt › Bildnachzeichner › Erstellen nach. @msg {label} requires a shape with at least two anchors {label} erfordert eine Form mit mindestens zwei Ankerpunkten @msg The shape is too complex for a 3D effect Die Form ist für einen 3D-Effekt zu komplex @msg The 3D surface is too complex; simplify the shape Die 3D-Oberfläche ist zu komplex; vereinfachen Sie die Form @@ -5553,6 +5559,20 @@ axis Y Axis Y-Achse Show its progress, see Cancel and write log lines Den Fortschritt anzeigen, ein Abbrechen erkennen und Protokollzeilen schreiben Keep settings of its own Eigene Einstellungen speichern Keep a cache of its own, which you can clear Einen eigenen Cache anlegen, den Sie leeren können + Run these commands on the document: {ids} Diese Befehle im Dokument ausführen: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ führt `{id}` in `commandAllowlist` auf, den ein Plug-in nicht aufrufen darf +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: die `commandAllowlist` des Manifests führt ihn nicht auf +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: die ID oder die Argumente liegen außerhalb des Speichers des Moduls +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: die ID oder die Argumente sind kein UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: die Argumente sind kein JSON-Objekt +@msg only a filter with the usual budget declares `commandAllowlist` nur ein Filter mit dem üblichen Budget deklariert `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) Befehlsaufrufe ({MAX_CALLS} Aufrufe und {MAX_CALL_BYTES} Byte pro Lauf) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) Größe eines Befehlsaufrufs (vc_call `{shown}`: {len} Byte, Grenze {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` höchstens {MAX_ALLOWED_COMMANDS} Befehle in `commandAllowlist` +@msg a plug-in may not call this command ein Plug-in darf diesen Befehl nicht aufrufen +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` braucht die Berechtigung `commands`, und `commands` braucht eine `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` nennt `{shown}`, das keine Befehls-ID ist oder doppelt aufgeführt ist Clear Plug-in Cache Plug-in-Cache leeren @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} die Berechtigung `{permission}` braucht die Plug-in-API-Stufe {PROGRESS_API}: Geben Sie `api` {PROGRESS_API} an @msg the module imports `env.{name}` with another type than the host's: it is {signature} das Modul importiert `env.{name}` mit einem anderen Typ als dem des Hosts: Der Typ des Hosts ist {signature} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 76c6099eb6..a95d84be33 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4293,6 +4293,11 @@ digits Malayalam Μαλαγιάλαμ @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) εσωτερικό σφάλμα στην εντολή `{cmd}`: {msg} (το έγγραφο έμεινε αμετάβλητο· αναφέρετε το σφάλμα) @msg internal error: {msg} (please report this bug) εσωτερικό σφάλμα: {msg} (αναφέρετε το σφάλμα) @msg invalid PDF setting: {0} μη έγκυρη ρύθμιση PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): γράφεται με UserUnit {unit}, οπότε οι εφαρμογές που αγνοούν το UserUnit την εμφανίζουν τόσες φορές μικρότερη +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in η σελίδα του πίνακα σχεδίασης {n} είναι {size}, μεγαλύτερη από το όριο σελίδας PDF των 14.400 pt (200 in): οι σελίδες {label} γράφονται χωρίς UserUnit, σε στιγμές, και οι εφαρμογές που τηρούν το όριο κόβουν τη σελίδα στις 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 το PDF 1.5 δεν έχει UserUnit, που χρειάζεται μια σελίδα μεγαλύτερη από 14.400 pt (200 in) για να κρατήσει το μέγεθός της: το αρχείο γράφεται ως PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units η σελίδα του πίνακα σχεδίασης {n} είναι {size}, πολύ μακριά και στενή για τις πλευρές σελίδας PDF από 3 έως 14.400 μονάδες: γράφεται με UserUnit {unit}, που κρατά τη μικρή πλευρά στις 3 μονάδες ή περισσότερο, και οι εφαρμογές που τηρούν το όριο κόβουν τη μεγάλη πλευρά στις 14.400 μονάδες +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard τα αρχεία {label} δέχονται πραγματικούς αριθμούς έως {max}, και η σελίδα του πίνακα σχεδίασης {n}, μήκους {side} pt, χρειάζεται μεγαλύτερους: επιλέξτε PDF 1.6 ή νεότερο χωρίς πρότυπο PDF/X, ή μικρότερο πίνακα σχεδίασης @msg invalid image data for `{0}` μη έγκυρα δεδομένα εικόνας για `{0}` @msg invalid parameters for `{cmd}`: {msg} μη έγκυρες παράμετροι για `{cmd}`: {msg} @msg is not an image VectorCraft reads δεν είναι μορφή εικόνας που μπορεί να διαβάσει το VectorCraft @@ -4977,7 +4982,8 @@ digits Malayalam Μαλαγιάλαμ Bevel Inside Εσωτερική λοξότμηση Bevel both sides Λοξότμηση και των δύο πλευρών @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ένα αντικείμενο δέχεται ένα εφέ 3D. Επεξεργαστείτε τις επιλογές του υπάρχοντος εφέ ή αφαιρέστε το πρώτα. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. Το {label} απαιτεί προς το παρόν διαδρομή, σύνθετη διαδρομή, κείμενο ή ομάδα. Μετατρέψτε πρώτα τις εικόνες και τα άλλα αντικείμενα σε διαδρομές. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. Το {label} απαιτεί προς το παρόν διαδρομή, σύνθετη διαδρομή, κείμενο, ομάδα, ανάμειξη ή στιγμιότυπο συμβόλου. Επεκτείνετε πρώτα τα άλλα αντικείμενα. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. Το {label} δεν μπορεί να δημιουργήσει στερεό από εικόνα: ανιχνεύστε την πρώτα με Αντικείμενο › Ανίχνευση περιγραμμάτων εικόνας › Κατασκευαστής. @msg {label} requires a shape with at least two anchors το {label} απαιτεί σχήμα με τουλάχιστον δύο σημεία αγκύρωσης @msg The shape is too complex for a 3D effect Το σχήμα είναι πολύ σύνθετο για εφέ 3D @msg The 3D surface is too complex; simplify the shape Η επιφάνεια 3D είναι πολύ σύνθετη· απλοποιήστε το σχήμα @@ -5921,6 +5927,20 @@ axis Y Axis Άξονας Y Show its progress, see Cancel and write log lines Εμφάνιση της προόδου, αναγνώριση της ακύρωσης και εγγραφή γραμμών καταγραφής Keep settings of its own Διατήρηση δικών του ρυθμίσεων Keep a cache of its own, which you can clear Διατήρηση δικής του κρυφής μνήμης, την οποία μπορείτε να εκκαθαρίσετε + Run these commands on the document: {ids} Εκτέλεση αυτών των εντολών στο έγγραφο: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call το «{name}» αναφέρει το `{id}` στο `commandAllowlist`, το οποίο ένα πρόσθετο δεν επιτρέπεται να καλέσει +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: το `commandAllowlist` του μανιφέστου δεν την αναφέρει +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: το αναγνωριστικό ή τα ορίσματα βρίσκονται εκτός της μνήμης της λειτουργικής μονάδας +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: το αναγνωριστικό ή τα ορίσματα δεν είναι UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: τα ορίσματα δεν είναι αντικείμενο JSON +@msg only a filter with the usual budget declares `commandAllowlist` μόνο ένα φίλτρο με τον συνήθη προϋπολογισμό δηλώνει `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) κλήσεις εντολών ({MAX_CALLS} κλήσεις και {MAX_CALL_BYTES} byte ανά εκτέλεση) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) μέγεθος κλήσης εντολής (vc_call `{shown}`: {len} byte, όριο {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` το πολύ {MAX_ALLOWED_COMMANDS} εντολές στο `commandAllowlist` +@msg a plug-in may not call this command ένα πρόσθετο δεν επιτρέπεται να καλέσει αυτή την εντολή +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` το `commandAllowlist` χρειάζεται το δικαίωμα `commands`, και το `commands` χρειάζεται ένα `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice το `commandAllowlist` αναφέρει το `{shown}`, που δεν είναι αναγνωριστικό εντολής ή αναφέρεται δύο φορές Clear Plug-in Cache Εκκαθάριση κρυφής μνήμης προσθέτου @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} το δικαίωμα `{permission}` χρειάζεται το επίπεδο API προσθέτων {PROGRESS_API}: δώστε `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} η λειτουργική μονάδα εισάγει το `env.{name}` με άλλον τύπο από αυτόν του κεντρικού υπολογιστή: ο τύπος του είναι {signature} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 4e5cf58ef8..e0903d19d7 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4339,6 +4339,11 @@ axis Both Ambos @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) error interno en `{cmd}`: {msg} (el documento quedó como estaba; por favor, informa de este error) @msg internal error: {msg} (please report this bug) error interno: {msg} (por favor, informa de este error) @msg invalid PDF setting: {0} ajuste de PDF no válido: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): se escribe con un UserUnit de {unit}, así que las aplicaciones que ignoran UserUnit la muestran ese número de veces más pequeña +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la página de la mesa de trabajo {n} mide {size}, más que el límite de página de PDF de 14.400 pt (200 in): las páginas {label} se escriben sin UserUnit, en puntos, y las aplicaciones que respetan el límite recortan la página a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 no tiene UserUnit, que una página de más de 14.400 pt (200 in) necesita para conservar su tamaño: el archivo se escribe como PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la página de la mesa de trabajo {n} mide {size}, demasiado larga y estrecha para los lados de página de PDF de 3 a 14.400 unidades: se escribe con una UserUnit de {unit}, que mantiene el lado corto en 3 unidades o más, y las aplicaciones que respetan el límite recortan el lado largo a 14.400 unidades +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard los archivos {label} admiten números reales de hasta {max}, y la página de la mesa de trabajo {n}, de {side} pt, necesita otros mayores: elija PDF 1.6 o posterior sin estándar PDF/X, o una mesa de trabajo más pequeña @msg invalid image data for `{0}` datos de imagen no válidos para `{0}` @msg invalid parameters for `{cmd}`: {msg} parámetros no válidos para `{cmd}`: {msg} @msg is not an image VectorCraft reads no es una imagen que VectorCraft pueda leer @@ -5557,7 +5562,8 @@ mark-style Japanese Japonesas Bevel both sides Bisel en ambos lados Presets Ajustes preestablecidos @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un objeto admite un solo efecto 3D. Edite las opciones del efecto existente o quítelo primero. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} requiere por ahora un trazado, un trazado compuesto, texto o un grupo. Convierta primero las imágenes y otros objetos en trazados. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} requiere por ahora un trazado, un trazado compuesto, texto, un grupo, una fusión o una instancia de símbolo. Expanda primero los demás objetos. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} no puede crear un sólido a partir de una imagen: cálquela primero con Objeto › Calco de imagen › Crear. @msg {label} requires a shape with at least two anchors {label} requiere una forma con al menos dos puntos de ancla @msg The shape is too complex for a 3D effect La forma es demasiado compleja para un efecto 3D @msg The 3D surface is too complex; simplify the shape La superficie 3D es demasiado compleja; simplifique la forma @@ -5912,6 +5918,20 @@ axis Y Axis Eje Y Show its progress, see Cancel and write log lines Mostrar su progreso, detectar la cancelación y escribir líneas de registro Keep settings of its own Guardar una configuración propia Keep a cache of its own, which you can clear Guardar una caché propia, que usted puede vaciar + Run these commands on the document: {ids} Ejecutar estos comandos en el documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” incluye `{id}` en `commandAllowlist`, que un plugin no puede llamar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: el `commandAllowlist` del manifiesto no lo incluye +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: el ID o los argumentos están fuera de la memoria del módulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: el ID o los argumentos no son UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: los argumentos no son un objeto JSON +@msg only a filter with the usual budget declares `commandAllowlist` solo un filtro con el presupuesto habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) llamadas a comandos ({MAX_CALLS} llamadas y {MAX_CALL_BYTES} bytes por ejecución) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) tamaño de una llamada a comando (vc_call `{shown}`: {len} bytes, límite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` como máximo {MAX_ALLOWED_COMMANDS} comandos en `commandAllowlist` +@msg a plug-in may not call this command un plugin no puede llamar a este comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` necesita el permiso `commands`, y `commands` necesita un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` incluye `{shown}`, que no es un ID de comando o aparece dos veces Clear Plug-in Cache Vaciar caché del plugin @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} el permiso `{permission}` necesita el nivel de API de plugins {PROGRESS_API}: indique `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} el módulo importa `env.{name}` con un tipo distinto del del host: el del host es {signature} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index d16ef82869..b593200aa5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4556,6 +4556,11 @@ imageTrace Outline Ääriviiva @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) sisäinen virhe kohteessa `{cmd}`: {msg} (asiakirja jätettiin ennalleen; ilmoita tästä virheestä) @msg internal error: {msg} (please report this bug) sisäinen virhe: {msg} (ilmoita tästä virheestä) @msg invalid PDF setting: {0} virheellinen PDF-asetus: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: se kirjoitetaan UserUnit-arvolla {unit}, joten UserUnitin ohittavat sovellukset näyttävät sen niin monta kertaa pienempänä +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in piirtoalustan {n} sivu on {size}, pidempi kuin PDF:n 14 400 pt:n (200 in) sivuraja: {label}-sivut kirjoitetaan ilman UserUnitia, pisteinä, ja rajaa noudattavat sovellukset rajaavat sivun 200 in:iin +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5:ssä ei ole UserUnitia, jota yli 14 400 pt:n (200 in) sivu tarvitsee säilyttääkseen kokonsa: tiedosto kirjoitetaan PDF 1.6:na +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units piirtoalustan {n} sivu on {size}, liian pitkä ja kapea PDF:n sivuille, jotka ovat 3:sta 14 400 yksikköön: se kirjoitetaan UserUnit-arvolla {unit}, joka pitää lyhyen sivun vähintään 3 yksikössä, ja rajaa noudattavat sovellukset leikkaavat pitkän sivun 14 400 yksikköön +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-tiedostot sallivat reaaliluvut enintään {max}, ja piirtoalustan {n} sivu, {side} pt pitkä, tarvitsee suurempia: valitse PDF 1.6 tai uudempi ilman PDF/X-standardia tai pienempi piirtoalusta @msg invalid image data for `{0}` virheellinen kuvadata kohteelle `{0}` @msg invalid parameters for `{cmd}`: {msg} virheelliset parametrit kohteelle `{cmd}`: {msg} @msg is not an image VectorCraft reads ei ole kuva, jota VectorCraft lukee @@ -5500,7 +5505,8 @@ mark-style Japanese Japanilainen Bevel both sides Viiste molemmin puolin Presets Esiasetukset @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Objektilla voi olla yksi 3D-tehoste. Muokkaa olemassa olevan tehosteen asetuksia tai poista se ensin. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} vaatii tällä hetkellä polun, yhdistelmäpolun, tekstin tai ryhmän. Muunna kuvat ja muut objektit ensin poluiksi. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} vaatii tällä hetkellä polun, yhdistelmäpolun, tekstin, ryhmän, sulautuksen tai symbolin ilmentymän. Laajenna muut objektit ensin. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ei voi luoda kappaletta kuvasta: jäljitä se ensin komennolla Objekti › Kuvan jäljitys › Luo. @msg {label} requires a shape with at least two anchors {label} vaatii muodon, jossa on vähintään kaksi ankkuria @msg The shape is too complex for a 3D effect Muoto on liian monimutkainen 3D-tehosteelle @msg The 3D surface is too complex; simplify the shape 3D-pinta on liian monimutkainen; yksinkertaista muotoa @@ -6000,6 +6006,20 @@ axis Y Axis Y-akseli Show its progress, see Cancel and write log lines Näyttää edistymisensä, havaita peruutuksen ja kirjoittaa lokirivejä Keep settings of its own Säilyttää omat asetuksensa Keep a cache of its own, which you can clear Säilyttää oman välimuistin, jonka voit tyhjentää + Run these commands on the document: {ids} Suorittaa nämä komennot asiakirjassa: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” luettelee `commandAllowlist`-luettelossa komennon `{id}`, jota laajennus ei saa kutsua +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestin `commandAllowlist` ei luettele sitä +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: tunnus tai argumentit ovat moduulin muistin ulkopuolella +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: tunnus tai argumentit eivät ole UTF-8:aa +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumentit eivät ole JSON-objekti +@msg only a filter with the usual budget declares `commandAllowlist` vain tavallisen budjetin suodatin voi määrittää `commandAllowlist`-luettelon +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) komentokutsut ({MAX_CALLS} kutsua ja {MAX_CALL_BYTES} tavua ajoa kohden) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) komentokutsun koko (vc_call `{shown}`: {len} tavua, raja {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` enintään {MAX_ALLOWED_COMMANDS} komentoa `commandAllowlist`-luettelossa +@msg a plug-in may not call this command laajennus ei saa kutsua tätä komentoa +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` tarvitsee käyttöoikeuden `commands`, ja `commands` tarvitsee `commandAllowlist`-luettelon +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` mainitsee kohteen `{shown}`, joka ei ole komennon tunnus tai on luettelossa kahdesti Clear Plug-in Cache Tyhjennä laajennuksen välimuisti @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} käyttöoikeus `{permission}` vaatii laajennus-API:n tason {PROGRESS_API}: anna `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} moduuli tuo kohteen `env.{name}` eri tyyppisenä kuin isäntä: isännän tyyppi on {signature} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8613ae5eae..6dd4e37a41 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4327,6 +4327,11 @@ axis Both Les deux @msg installing from a path is not available on the web; pass the module as `dataBase64` l’installation depuis un chemin n’est pas disponible sur le web ; transmettez le module sous forme de `dataBase64` @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) erreur interne dans `{cmd}` : {msg} (le document est resté tel qu’il était ; veuillez signaler ce bogue) @msg internal error: {msg} (please report this bug) erreur interne : {msg} (veuillez signaler ce bogue) +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : elle est écrite avec une UserUnit de {unit}, donc les applications qui ignorent UserUnit l’affichent autant de fois plus petite +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la page du plan de travail {n} mesure {size}, plus que la limite de page PDF de 14 400 pt (200 in) : les pages {label} sont écrites sans UserUnit, en points, et les applications qui respectent la limite coupent la page à 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 n’a pas d’UserUnit, dont une page de plus de 14 400 pt (200 in) a besoin pour garder sa taille : le fichier est écrit en PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la page du plan de travail {n} mesure {size}, trop longue et étroite pour les côtés de page PDF de 3 à 14 400 unités : elle est écrite avec une UserUnit de {unit}, qui garde le petit côté à 3 unités ou plus, et les apps qui respectent la limite coupent le grand côté à 14 400 unités +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard les fichiers {label} acceptent des nombres réels jusqu’à {max}, et la page du plan de travail {n}, longue de {side} pt, en demande de plus grands : choisissez PDF 1.6 ou ultérieur sans norme PDF/X, ou un plan de travail plus petit @msg invalid PDF setting: {0} réglage PDF non valide : {0} @msg invalid image data for `{0}` données d’image non valides pour `{0}` @msg invalid parameters for `{cmd}`: {msg} paramètres non valides pour `{cmd}` : {msg} @@ -5187,7 +5192,8 @@ lighting Light Lumière Bevel both sides Biseau des deux côtés Presets Paramètres prédéfinis @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un objet n'accepte qu'un seul effet 3D. Modifiez les options de l'effet existant ou supprimez-le d'abord. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} nécessite pour l'instant un tracé, un tracé transparent, du texte ou un groupe. Convertissez d'abord les images et les autres objets en tracés. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} nécessite pour l'instant un tracé, un tracé transparent, du texte, un groupe, un dégradé de formes ou une instance de symbole. Décomposez d'abord les autres objets. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} ne peut pas créer de solide à partir d'une image : vectorisez-la d'abord avec Objet › Vectorisation de l’image › Créer. @msg {label} requires a shape with at least two anchors {label} nécessite une forme comportant au moins deux points d'ancrage @msg The shape is too complex for a 3D effect La forme est trop complexe pour un effet 3D @msg The 3D surface is too complex; simplify the shape La surface 3D est trop complexe ; simplifiez la forme @@ -5965,6 +5971,20 @@ axis Y Axis Axe Y Show its progress, see Cancel and write log lines Afficher sa progression, détecter l’annulation et écrire des lignes de journal Keep settings of its own Conserver ses propres réglages Keep a cache of its own, which you can clear Conserver son propre cache, que vous pouvez vider + Run these commands on the document: {ids} Exécuter ces commandes sur le document : {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call « {name} » indique `{id}` dans `commandAllowlist`, qu’un module externe ne peut pas appeler +@msg vc_call `{shown}`: {why} vc_call `{shown}` : {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}` : le `commandAllowlist` du manifeste ne l’indique pas +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}` : l’ID ou les arguments se trouvent hors de la mémoire du module +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}` : l’ID ou les arguments ne sont pas en UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}` : les arguments ne sont pas un objet JSON +@msg only a filter with the usual budget declares `commandAllowlist` seul un filtre au budget habituel déclare `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) appels de commandes ({MAX_CALLS} appels et {MAX_CALL_BYTES} octets par exécution) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) taille d’un appel de commande (vc_call `{shown}` : {len} octets, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` au plus {MAX_ALLOWED_COMMANDS} commandes dans `commandAllowlist` +@msg a plug-in may not call this command un module externe ne peut pas appeler cette commande +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` a besoin de l’autorisation `commands`, et `commands` a besoin d’un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` indique `{shown}`, qui n’est pas un ID de commande ou figure deux fois Clear Plug-in Cache Vider le cache du module externe @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} l’autorisation `{permission}` nécessite le niveau d’API de module externe {PROGRESS_API} : indiquez `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} le module importe `env.{name}` avec un autre type que celui de l’hôte : celui de l’hôte est {signature} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 22d882a03c..3397e7f347 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5292,6 +5292,20 @@ antiAlias Sharp शार्प Show its progress, see Cancel and write log lines अपनी प्रगति दिखाना, रद्द करने का अनुरोध देखना और लॉग पंक्तियाँ लिखना Keep settings of its own अपनी सेटिंग्स रखना Keep a cache of its own, which you can clear अपना कैश रखना, जिसे आप साफ़ कर सकते हैं + Run these commands on the document: {ids} दस्तावेज़ पर ये कमांड चलाना: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” `commandAllowlist` में `{id}` सूचीबद्ध करता है, जिसे कोई प्लग-इन कॉल नहीं कर सकता +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: मैनिफ़ेस्ट की `commandAllowlist` में यह सूचीबद्ध नहीं है +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: आईडी या आर्ग्युमेंट मॉड्यूल की मेमोरी के बाहर हैं +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: आईडी या आर्ग्युमेंट UTF-8 नहीं हैं +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: आर्ग्युमेंट JSON ऑब्जेक्ट नहीं हैं +@msg only a filter with the usual budget declares `commandAllowlist` केवल सामान्य बजट वाला फ़िल्टर `commandAllowlist` घोषित करता है +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) कमांड कॉल (हर रन में {MAX_CALLS} कॉल और {MAX_CALL_BYTES} बाइट) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) कमांड कॉल का आकार (vc_call `{shown}`: {len} बाइट, सीमा {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` में अधिकतम {MAX_ALLOWED_COMMANDS} कमांड +@msg a plug-in may not call this command कोई प्लग-इन इस कमांड को कॉल नहीं कर सकता +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` को `commands` अनुमति चाहिए, और `commands` को `commandAllowlist` चाहिए +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` में `{shown}` है, जो कमांड आईडी नहीं है या दो बार सूचीबद्ध है Clear Plug-in Cache प्लग-इन कैश साफ़ करें @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} अनुमति `{permission}` के लिए प्लग-इन API स्तर {PROGRESS_API} चाहिए: `api` {PROGRESS_API} दें @msg the module imports `env.{name}` with another type than the host's: it is {signature} मॉड्यूल `env.{name}` को होस्ट से अलग प्रकार के साथ आयात करता है: होस्ट का प्रकार {signature} है @@ -5417,7 +5431,8 @@ antiAlias Sharp शार्प @msg {key} must name a registered panel {key} एक पंजीकृत पैनल का नाम होना चाहिए @msg {kind} files have no transparency, and the file would have {what}: flatten it first (object.flattenTransparency) {kind} फ़ाइलों में पारदर्शिता नहीं होती और इस फ़ाइल में {what} होगा: पहले इसे फ़्लैट करें (object.flattenTransparency) @msg {kind} images can't be opened (see document.formats) {kind} इमेज ओपन नहीं हो सकतीं (document.formats देखें) -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} के लिए वर्तमान में एक पाथ, यौगिक पाथ, टाइप या समूह आवश्यक है। पहले इमेज और अन्य ऑब्जेक्ट को पाथ में परिवर्तित करें। +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} के लिए वर्तमान में एक पाथ, यौगिक पाथ, टाइप, समूह, ब्लेंड या सिंबल इंस्टेंस आवश्यक है। पहले अन्य ऑब्जेक्ट को एक्सपैंड करें। +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} इमेज से ठोस नहीं बना सकता: पहले ऑब्जेक्ट › इमेज ट्रेस › बनाएँ से उसे ट्रेस करें। @msg {label} keeps 1 of the document's {n} artboards: the file reopens with one. Turn on Preserve Editing Capabilities to keep them all. {label} डॉक्यूमेंट के {n} आर्टबोर्ड में से 1 रखता है: फ़ाइल एक के साथ फिर से खुलती है। उन्हें रखने के लिए संरक्षित संपादन क्षमताओं को चालू करें। @msg {label} must be a number {label} एक नंबर होना चाहिए @msg {label} must be a number above 0 and at most {max} {label} 0 से ऊपर और सबसे {max} पर होना चाहिए @@ -6493,6 +6508,11 @@ antiAlias Sharp शार्प @msg invalid parameters for `{cmd}`: {msg} `{cmd}` के लिए अमान्य पैरामीटर: {msg} @msg invalid pattern tile choice अमान्य पैटर्न टाइल ऑप्शन @msg invalid PDF setting: {0} Invalid PDF सेटिंग: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: इसे {unit} के UserUnit के साथ लिखा जाता है, इसलिए UserUnit को अनदेखा करने वाले ऐप इसे उतने गुना छोटा दिखाते हैं +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in आर्टबोर्ड {n} का पेज {size} है, जो PDF की 14,400 pt (200 in) की पेज सीमा से लंबा है: {label} पेज बिना UserUnit के, पॉइंट में लिखे जाते हैं, और सीमा मानने वाले ऐप पेज को 200 in पर काट देते हैं +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 में UserUnit नहीं है, जिसकी 14,400 pt (200 in) से लंबे पेज को अपना आकार बनाए रखने के लिए ज़रूरत होती है: फ़ाइल PDF 1.6 के रूप में लिखी जाती है +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units आर्टबोर्ड {n} का पेज {size} है, जो PDF की 3 से 14,400 इकाई की पेज भुजाओं के लिए बहुत लंबा और संकरा है: इसे {unit} की UserUnit के साथ लिखा जाता है, जो छोटी भुजा को 3 इकाई या अधिक पर रखती है, और सीमा का पालन करने वाले ऐप लंबी भुजा को 14,400 इकाई पर काट देते हैं +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} फ़ाइलें {max} तक की वास्तविक संख्याएँ रखती हैं, और आर्टबोर्ड {n} का {side} pt लंबा पेज इससे बड़ी संख्याएँ माँगता है: बिना PDF/X मानक के PDF 1.6 या बाद का चुनें, या छोटा आर्टबोर्ड @msg invalid point अमानवीय बिंदु @msg Invalid point अमानवीय बिंदु @msg Invalid real scale अमानवीय वास्तविक पैमाने diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 46f4669ccc..4b813215e0 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4977,6 +4977,11 @@ imageTrace Outline Körvonal @msg Invalid panel layout; restored the default dock Érvénytelen panelelrendezés; az alapértelmezett dokk visszaállítva @msg invalid parameters for `{cmd}`: {msg} érvénytelen paraméterek (`{cmd}`): {msg} @msg invalid PDF setting: {0} érvénytelen PDF-beállítás: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: {unit} UserUnit értékkel íródik, így a UserUnit-ot figyelmen kívül hagyó alkalmazások ennyiszer kisebbnek mutatják +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a(z) {n}. rajztábla oldala {size}, hosszabb a PDF 14 400 pt-os (200 in) oldalkorlátjánál: a(z) {label} oldalak UserUnit nélkül, pontokban íródnak, és a korlátot betartó alkalmazások 200 in-re vágják az oldalt +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 a PDF 1.5-ben nincs UserUnit, amelyre egy 14 400 pt-nál (200 in) hosszabb oldalnak szüksége van a mérete megtartásához: a fájl PDF 1.6-ként íródik +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a(z) {n}. rajztábla oldala {size}, túl hosszú és keskeny a PDF 3 és 14 400 egység közötti oldalaihoz: {unit} UserUnit értékkel íródik, amely a rövid oldalt legalább 3 egységen tartja, és a korlátot betartó alkalmazások a hosszú oldalt 14 400 egységre vágják +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard a(z) {label} fájlok legfeljebb {max} értékű valós számokat tárolnak, a(z) {n}. rajztábla {side} pt hosszú oldalához pedig nagyobbak kellenek: válassza a PDF 1.6-os vagy újabb verziót PDF/X szabvány nélkül, vagy egy kisebb rajztáblát @msg invalid restored panel group érvénytelen visszaállított panelcsoport @msg is not an image VectorCraft reads nem olyan kép, amelyet a VectorCraft olvas @msg it ends inside a group or compound path egy csoporton vagy összetett útvonalon belül ér véget @@ -5599,7 +5604,8 @@ imageTrace Outline Körvonal Bevel both sides Élletörés mindkét oldalon Presets Készletek @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Egy objektumnak csak egy 3D effektusa lehet. Szerkessze a meglévő effektus beállításait, vagy előbb távolítsa el. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} egyelőre görbét, összetett görbét, szöveget vagy csoportot igényel. Előbb alakítsa görbévé a képeket és az egyéb objektumokat. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} egyelőre görbét, összetett görbét, szöveget, csoportot, összemosást vagy szimbólumpéldányt igényel. Előbb bontsa ki az egyéb objektumokat. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} képből nem tud testet létrehozni: előbb vektorizálja az Objektum › Képvektorizálás › Létrehozás paranccsal. @msg {label} requires a shape with at least two anchors {label} legalább két szerkesztőpontos alakzatot igényel @msg The shape is too complex for a 3D effect Az alakzat túl összetett a 3D effektushoz @msg The 3D surface is too complex; simplify the shape A 3D felület túl összetett; egyszerűsítse az alakzatot @@ -5953,6 +5959,20 @@ axis Y Axis Y tengely Show its progress, see Cancel and write log lines Megjelenítheti az előrehaladását, észlelheti a megszakítást és naplósorokat írhat Keep settings of its own Saját beállításokat tárolhat Keep a cache of its own, which you can clear Saját gyorsítótárat tárolhat, amelyet Ön kiüríthet + Run these commands on the document: {ids} Ezeket a parancsokat futtathatja a dokumentumon: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call a(z) „{name}” a(z) `{id}` parancsot sorolja fel a `commandAllowlist` listában, amelyet bővítmény nem hívhat meg +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: a jegyzék `commandAllowlist` listája nem sorolja fel +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: az azonosító vagy az argumentumok a modul memóriáján kívül esnek +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: az azonosító vagy az argumentumok nem UTF-8 kódolásúak +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: az argumentumok nem JSON-objektumot alkotnak +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` listát csak a szokásos keretű szűrő adhat meg +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) parancshívások (futásonként {MAX_CALLS} hívás és {MAX_CALL_BYTES} bájt) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) parancshívás mérete (vc_call `{shown}`: {len} bájt, korlát {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` legfeljebb {MAX_ALLOWED_COMMANDS} parancs a `commandAllowlist` listában +@msg a plug-in may not call this command bővítmény nem hívhatja meg ezt a parancsot +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` a `commandAllowlist` listához a `commands` engedély szükséges, a `commands` engedélyhez pedig `commandAllowlist` lista +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice a `commandAllowlist` a(z) `{shown}` elemet nevezi meg, amely nem parancsazonosító, vagy kétszer szerepel Clear Plug-in Cache Bővítmény gyorsítótárának kiürítése @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} a(z) `{permission}` engedélyhez {PROGRESS_API}. szintű bővítmény-API kell: adja meg az `api` {PROGRESS_API} értéket @msg the module imports `env.{name}` with another type than the host's: it is {signature} a modul az `env.{name}` elemet a gazdaprogramétól eltérő típussal importálja: a gazdaprogram típusa {signature} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 737f451244..33d229c85a 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5157,7 +5157,8 @@ mark-style Japanese Jepang Bevel both sides Bevel di kedua sisi Presets Preset @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Sebuah objek hanya menerima satu efek 3D. Edit opsi efek yang sudah ada, atau hapus dulu efek tersebut. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} saat ini memerlukan jalur atau jalur majemuk. Konversikan dulu teks, gambar, dan grup menjadi jalur. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} saat ini memerlukan jalur, jalur majemuk, teks, grup, blend, atau instans simbol. Perluas dulu objek lainnya. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} tidak dapat membuat benda padat dari gambar: lacak dulu dengan Objek › Image Trace › Buat. @msg {label} requires a shape with at least two anchors {label} memerlukan bentuk dengan setidaknya dua jangkar @msg The shape is too complex for a 3D effect Bentuknya terlalu kompleks untuk efek 3D @msg The 3D surface is too complex; simplify the shape Permukaan 3D terlalu kompleks; sederhanakan bentuknya @@ -5817,6 +5818,7 @@ axis Y Axis Sumbu Y Show its progress, see Cancel and write log lines Menampilkan kemajuannya, mengenali pembatalan, dan menulis baris log Keep settings of its own Menyimpan pengaturannya sendiri Keep a cache of its own, which you can clear Menyimpan cache-nya sendiri, yang dapat Anda kosongkan + Run these commands on the document: {ids} Menjalankan perintah ini pada dokumen: {ids} Clear Plug-in Cache Kosongkan cache plug-in # Actions panel: action sets (#3712). New Set… Set baru… diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index d5420b3a9a..b5fd752e9b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4381,6 +4381,11 @@ axis Both Entrambi @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) errore interno in `{cmd}`: {msg} (il documento è rimasto com'era; segnala questo bug) @msg internal error: {msg} (please report this bug) errore interno: {msg} (segnala questo bug) @msg invalid PDF setting: {0} impostazione PDF non valida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): viene scritta con una UserUnit di {unit}, quindi le app che ignorano UserUnit la mostrano altrettante volte più piccola +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in la pagina della tavola da disegno {n} misura {size}, più del limite di pagina PDF di 14.400 pt (200 in): le pagine {label} vengono scritte senza UserUnit, in punti, e le app che rispettano il limite tagliano la pagina a 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 non ha UserUnit, che serve a una pagina più lunga di 14.400 pt (200 in) per mantenere le sue dimensioni: il file viene scritto come PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units la pagina della tavola da disegno {n} misura {size}, troppo lunga e stretta per i lati di pagina PDF da 3 a 14.400 unità: viene scritta con una UserUnit di {unit}, che tiene il lato corto a 3 unità o più, e le app che rispettano il limite tagliano il lato lungo a 14.400 unità +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard i file {label} accettano numeri reali fino a {max}, e la pagina della tavola da disegno {n}, lunga {side} pt, ne richiede di più grandi: scegli PDF 1.6 o successivo senza standard PDF/X, oppure una tavola da disegno più piccola @msg invalid image data for `{0}` dati immagine non validi per `{0}` @msg invalid parameters for `{cmd}`: {msg} parametri non validi per `{cmd}`: {msg} @msg is not an image VectorCraft reads non è un'immagine che VectorCraft sa leggere @@ -5225,7 +5230,8 @@ lighting Light Luce Bevel both sides Smusso su entrambi i lati Presets Predefiniti @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Un oggetto può avere un solo effetto 3D. Modificate le opzioni dell'effetto esistente oppure rimuovetelo prima. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} richiede per ora un tracciato, un tracciato composto, testo o un gruppo. Convertite prima immagini e altri oggetti in tracciati. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} richiede per ora un tracciato, un tracciato composto, testo, un gruppo, una fusione o un'istanza di simbolo. Espandete prima gli altri oggetti. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} non può creare un solido da un'immagine: ricalcatela prima con Oggetto › Ricalco immagine › Crea. @msg {label} requires a shape with at least two anchors {label} richiede una forma con almeno due punti di ancoraggio @msg The shape is too complex for a 3D effect La forma è troppo complessa per un effetto 3D @msg The 3D surface is too complex; simplify the shape La superficie 3D è troppo complessa; semplificate la forma @@ -5587,6 +5593,20 @@ axis Y Axis Asse Y Show its progress, see Cancel and write log lines Mostrare il proprio avanzamento, rilevare l’annullamento e scrivere righe di registro Keep settings of its own Conservare impostazioni proprie Keep a cache of its own, which you can clear Conservare una cache propria, che è possibile svuotare + Run these commands on the document: {ids} Eseguire questi comandi sul documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” elenca `{id}` in `commandAllowlist`, che un plug-in non può chiamare +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: il `commandAllowlist` del manifesto non lo elenca +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: l’ID o gli argomenti si trovano fuori dalla memoria del modulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: l’ID o gli argomenti non sono UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: gli argomenti non sono un oggetto JSON +@msg only a filter with the usual budget declares `commandAllowlist` solo un filtro con il budget consueto dichiara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) chiamate di comandi ({MAX_CALLS} chiamate e {MAX_CALL_BYTES} byte per esecuzione) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) dimensione di una chiamata di comando (vc_call `{shown}`: {len} byte, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` al massimo {MAX_ALLOWED_COMMANDS} comandi in `commandAllowlist` +@msg a plug-in may not call this command un plug-in non può chiamare questo comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` richiede l’autorizzazione `commands`, e `commands` richiede un `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` elenca `{shown}`, che non è un ID di comando o è elencato due volte Clear Plug-in Cache Svuota cache del plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} l’autorizzazione `{permission}` richiede il livello API dei plug-in {PROGRESS_API}: indicare `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} il modulo importa `env.{name}` con un tipo diverso da quello dell’host: quello dell’host è {signature} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 28787e6fbb..56fc8a5907 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4607,6 +4607,11 @@ swatch Bright Violet ビビッドバイオレット @msg artboard {0} does not exist アートボード {0} は存在しません @msg cannot read PDF: {0} PDF を読み込めません: {0} @msg invalid PDF setting: {0} PDF の設定が正しくありません: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: UserUnit {unit} で書き出されるため、UserUnit を無視するアプリではその倍率だけ小さく表示されます +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in アートボード {n} のページは {size} で、PDF のページ上限 14,400 pt (200 in) を超えています: {label} のページは UserUnit なしでポイント単位で書き出され、上限を守るアプリではページが 200 in で切り取られます +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 には、14,400 pt (200 in) を超えるページがサイズを保つために必要な UserUnit がありません: ファイルは PDF 1.6 として書き出されます +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units アートボード {n} のページは {size} で、PDF のページ辺 3 から 14,400 単位には長く細すぎます: 短辺を 3 単位以上に保つ UserUnit {unit} で書き出され、上限を守るアプリは長辺を 14,400 単位で切り取ります +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ファイルの実数は {max} までですが、アートボード {n} の {side} pt のページにはそれより大きな値が必要です: PDF/X 規格なしの PDF 1.6 以降を選ぶか、アートボードを小さくしてください @msg page {0} does not exist (the PDF has {1}) ページ {0} は存在しません (この PDF のページ数は {1} です) @msg thumbnail: no page {n} (the file has 1) thumbnail: ページ {n} は存在しません (このファイルのページ数は 1 です) @msg the PDF has no pages PDF にページがありません @@ -5267,7 +5272,8 @@ lighting Light ライト Bevel both sides 両面にベベル Presets プリセット @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 1 つのオブジェクトに適用できる 3D 効果は 1 つです。既存の効果のオプションを編集するか、先に削除してください。 -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} には現在、パス、複合パス、テキスト、またはグループが必要です。画像やその他のオブジェクトは先にパスに変換してください。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} には現在、パス、複合パス、テキスト、グループ、ブレンド、またはシンボルインスタンスが必要です。その他のオブジェクトは先に拡張してください。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} は画像から立体を作成できません。先に「オブジェクト › 画像トレース › 作成」でトレースしてください。 @msg {label} requires a shape with at least two anchors {label} には 2 つ以上のアンカーポイントを持つシェイプが必要です @msg The shape is too complex for a 3D effect シェイプが複雑すぎるため 3D 効果を適用できません @msg The 3D surface is too complex; simplify the shape 3D サーフェスが複雑すぎます。シェイプを単純化してください @@ -5652,6 +5658,20 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 進行状況の表示、キャンセルの検知、ログ行の書き込み Keep settings of its own 独自の設定の保持 Keep a cache of its own, which you can clear 消去できる独自のキャッシュの保持 + Run these commands on the document: {ids} ドキュメントでのこれらのコマンドの実行: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」は `commandAllowlist` にプラグインが呼び出せない `{id}` を挙げています +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: マニフェストの `commandAllowlist` にありません +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID または引数がモジュールのメモリの外にあります +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID または引数が UTF-8 ではありません +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: 引数が JSON オブジェクトではありません +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` を宣言できるのは通常の予算のフィルターだけです +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) コマンド呼び出し (1 回の実行につき {MAX_CALLS} 回、{MAX_CALL_BYTES} バイト) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) コマンド呼び出しのサイズ (vc_call `{shown}`: {len} バイト、上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` のコマンドは最大 {MAX_ALLOWED_COMMANDS} 個です +@msg a plug-in may not call this command プラグインはこのコマンドを呼び出せません +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` には権限 `commands` が必要で、`commands` には `commandAllowlist` が必要です +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` の `{shown}` はコマンド ID ではないか、2 回挙げられています Clear Plug-in Cache プラグインのキャッシュを消去 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 権限 `{permission}` にはプラグイン API レベル {PROGRESS_API} が必要です。`api` {PROGRESS_API} を指定してください @msg the module imports `env.{name}` with another type than the host's: it is {signature} モジュールが `env.{name}` をホストと異なる型でインポートしています。ホストの型は {signature} です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index f7ddd33291..388dd4a01e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4087,6 +4087,11 @@ font-technology Variable ცვლადი @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) შიდა შეცდომა `{cmd}`-ში: {msg} (დოკუმენტი წინანდელ მდგომარეობაში დარჩა; გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg internal error: {msg} (please report this bug) შიდა შეცდომა: {msg} (გთხოვთ, შეგვატყობინოთ ამ ხარვეზის შესახებ) @msg invalid PDF setting: {0} PDF-ის არასწორი პარამეტრი: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): ის იწერება UserUnit {unit}-ით, ამიტომ აპები, რომლებიც UserUnit-ს უგულებელყოფენ, მას ამდენჯერ პატარას აჩვენებენ +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in სამუშაო დაფა {n}-ის გვერდი არის {size}, რაც აღემატება PDF-ის გვერდის ლიმიტს 14 400 pt (200 in): {label} გვერდები იწერება UserUnit-ის გარეშე, პუნქტებში, და აპები, რომლებიც ლიმიტს იცავენ, გვერდს 200 in-ზე ჭრიან +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5-ს არ აქვს UserUnit, რომელიც 14 400 pt-ზე (200 in) გრძელ გვერდს ზომის შესანარჩუნებლად სჭირდება: ფაილი იწერება როგორც PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units სამუშაო დაფა {n}-ის გვერდი არის {size}, ძალიან გრძელი და ვიწრო PDF-ის 3-დან 14 400 ერთეულამდე გვერდის მხარეებისთვის: ის იწერება UserUnit {unit}-ით, რომელიც მოკლე მხარეს 3 ერთეულზე ან მეტზე ინარჩუნებს, ხოლო ზღვრის დამცველი აპები გრძელ მხარეს 14 400 ერთეულამდე ჭრიან +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} ფაილები ინახავს ნამდვილ რიცხვებს {max}-მდე, სამუშაო დაფა {n}-ის {side} pt სიგრძის გვერდს კი უფრო დიდი სჭირდება: აირჩიეთ PDF 1.6 ან უფრო ახალი PDF/X სტანდარტის გარეშე, ან უფრო პატარა სამუშაო დაფა @msg invalid image data for `{0}` არასწორი გამოსახულების მონაცემები `{0}`-სთვის @msg invalid parameters for `{cmd}`: {msg} `{cmd}`: არასწორი პარამეტრები — {msg} @msg is not an image VectorCraft reads ეს არ არის გამოსახულება, რომელსაც VectorCraft კითხულობს @@ -4966,7 +4971,8 @@ font-technology Variable ცვლადი Bevel both sides წაკვეთა ორივე მხარეს Presets პრესეტები @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. ობიექტს ერთი 3D ეფექტი შეიძლება ჰქონდეს. შეცვალეთ არსებული ეფექტის პარამეტრები ან ჯერ წაშალეთ ის. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}: ამჟამად საჭიროა ტრაექტორია, შედგენილი ტრაექტორია, ტექსტი ან ჯგუფი. ჯერ გარდაქმენით გამოსახულებები და სხვა ობიექტები ტრაექტორიებად. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: ამჟამად საჭიროა ტრაექტორია, შედგენილი ტრაექტორია, ტექსტი, ჯგუფი, გადასვლა ან სიმბოლოს ეგზემპლარი. ჯერ გაშალეთ სხვა ობიექტები. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: გამოსახულებიდან მყარი სხეულის აგება შეუძლებელია. ჯერ მოახდინეთ მისი ვექტორიზაცია ბრძანებით ობიექტი › გამოსახულების ვექტორიზაცია › შექმნა. @msg {label} requires a shape with at least two anchors {label}: საჭიროა ფიგურა მინიმუმ ორი საყრდენი წერტილით @msg The shape is too complex for a 3D effect ფიგურა ზედმეტად რთულია 3D ეფექტისთვის @msg The 3D surface is too complex; simplify the shape 3D ზედაპირი ზედმეტად რთულია; გაამარტივეთ ფიგურა @@ -5893,6 +5899,20 @@ axis Y Axis Y ღერძი Show its progress, see Cancel and write log lines პროგრესის ჩვენება, გაუქმების შემჩნევა და ჟურნალის სტრიქონების ჩაწერა Keep settings of its own საკუთარი პარამეტრების შენახვა Keep a cache of its own, which you can clear საკუთარი ქეშის შენახვა, რომლის გასუფთავებაც შეგიძლიათ + Run these commands on the document: {ids} ამ ბრძანებების გაშვება დოკუმენტზე: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}“ `commandAllowlist`-ში ასახელებს `{id}`-ს, რომლის გამოძახებაც პლაგინს არ შეუძლია +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: მანიფესტის `commandAllowlist` მას არ ასახელებს +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID ან არგუმენტები მოდულის მეხსიერების გარეთაა +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID ან არგუმენტები UTF-8 არ არის +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: არგუმენტები JSON ობიექტი არ არის +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist`-ის გამოცხადება მხოლოდ ჩვეულებრივი ბიუჯეტის ფილტრს შეუძლია +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) ბრძანებების გამოძახებები ({MAX_CALLS} გამოძახება და {MAX_CALL_BYTES} ბაიტი ერთ გაშვებაზე) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) ბრძანების გამოძახების ზომა (vc_call `{shown}`: {len} ბაიტი, ლიმიტი {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` მაქსიმუმ {MAX_ALLOWED_COMMANDS} ბრძანება `commandAllowlist`-ში +@msg a plug-in may not call this command პლაგინს ამ ბრძანების გამოძახება არ შეუძლია +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist`-ს სჭირდება ნებართვა `commands`, ხოლო `commands`-ს სჭირდება `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` ასახელებს `{shown}`-ს, რომელიც ბრძანების ID არ არის ან ორჯერაა ჩამოთვლილი Clear Plug-in Cache პლაგინის ქეშის გასუფთავება @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} ნებართვას `{permission}` სჭირდება პლაგინის API-ის დონე {PROGRESS_API}: მიუთითეთ `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} მოდულს შემოაქვს `env.{name}` ჰოსტისგან განსხვავებული ტიპით: ჰოსტის ტიპია {signature} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 36201c4659..03930932a7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4534,6 +4534,11 @@ theme Appearance 외관 @msg artboard {0} does not exist 아트보드 {0}이(가) 없습니다 @msg cannot read PDF: {0} PDF를 읽을 수 없습니다: {0} @msg invalid PDF setting: {0} 잘못된 PDF 설정: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: UserUnit {unit}(으)로 기록되므로 UserUnit을 무시하는 앱에서는 그 배수만큼 작게 표시됩니다 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 아트보드 {n}의 페이지는 {size}로 PDF 페이지 한도 14,400 pt (200 in)보다 깁니다: {label} 페이지는 UserUnit 없이 포인트 단위로 기록되며, 한도를 지키는 앱은 페이지를 200 in으로 자릅니다 +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5에는 14,400 pt (200 in)보다 긴 페이지가 크기를 유지하는 데 필요한 UserUnit이 없습니다: 파일이 PDF 1.6으로 기록됩니다 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 아트보드 {n}의 페이지는 {size}로, PDF 페이지 변 3에서 14,400 단위에 비해 너무 길고 좁습니다: 짧은 변을 3 단위 이상으로 유지하는 UserUnit {unit}로 기록되며, 한도를 지키는 앱은 긴 변을 14,400 단위로 자릅니다 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 파일은 실수를 최대 {max}까지 담는데 아트보드 {n}의 {side} pt 페이지에는 더 큰 값이 필요합니다: PDF/X 표준 없이 PDF 1.6 이상을 선택하거나 더 작은 아트보드를 사용하세요 @msg page {0} does not exist (the PDF has {1}) 페이지 {0}이(가) 없습니다(PDF의 페이지 수: {1}) @msg thumbnail: no page {n} (the file has 1) thumbnail: 페이지 {n}이(가) 없습니다(파일의 페이지 수: 1) @msg the PDF has no pages PDF에 페이지가 없습니다 @@ -5186,7 +5191,8 @@ lighting Light 광원 Bevel both sides 양면 베벨 Presets 사전 설정 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 오브젝트에는 3D 효과를 하나만 적용할 수 있습니다. 기존 효과의 옵션을 편집하거나 먼저 제거하십시오. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}에는 현재 패스, 컴파운드 패스, 문자 또는 그룹이 필요합니다. 이미지 및 기타 개체를 먼저 패스로 변환하십시오. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}에는 현재 패스, 컴파운드 패스, 문자, 그룹, 블렌드 또는 심볼 인스턴스가 필요합니다. 기타 개체를 먼저 확장하십시오. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}은(는) 이미지로 입체를 만들 수 없습니다. 먼저 개체 › 이미지 추적 › 만들기로 추적하십시오. @msg {label} requires a shape with at least two anchors {label}에는 고정점이 두 개 이상인 모양이 필요합니다 @msg The shape is too complex for a 3D effect 모양이 너무 복잡하여 3D 효과를 적용할 수 없습니다 @msg The 3D surface is too complex; simplify the shape 3D 표면이 너무 복잡합니다. 모양을 단순화하십시오 @@ -5548,6 +5554,20 @@ axis Y Axis Y축 Show its progress, see Cancel and write log lines 진행률 표시, 취소 감지 및 로그 줄 쓰기 Keep settings of its own 자체 설정 보관 Keep a cache of its own, which you can clear 지울 수 있는 자체 캐시 보관 + Run these commands on the document: {ids} 문서에서 다음 명령 실행: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”의 `commandAllowlist`에 플러그인이 호출할 수 없는 `{id}`가 있습니다 +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: 매니페스트의 `commandAllowlist`에 없습니다 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID 또는 인수가 모듈의 메모리 밖에 있습니다 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID 또는 인수가 UTF-8이 아닙니다 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: 인수가 JSON 객체가 아닙니다 +@msg only a filter with the usual budget declares `commandAllowlist` 보통 예산의 필터만 `commandAllowlist`를 선언할 수 있습니다 +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 명령 호출(실행당 {MAX_CALLS}회, {MAX_CALL_BYTES}바이트) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 명령 호출 크기(vc_call `{shown}`: {len}바이트, 제한 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist`의 명령은 최대 {MAX_ALLOWED_COMMANDS}개입니다 +@msg a plug-in may not call this command 플러그인은 이 명령을 호출할 수 없습니다 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist`에는 `commands` 권한이 필요하고, `commands`에는 `commandAllowlist`가 필요합니다 +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist`의 `{shown}`은(는) 명령 ID가 아니거나 두 번 나열되었습니다 Clear Plug-in Cache 플러그인 캐시 지우기 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} `{permission}` 권한에는 플러그인 API 수준 {PROGRESS_API}이(가) 필요합니다. `api` {PROGRESS_API}을(를) 지정하십시오 @msg the module imports `env.{name}` with another type than the host's: it is {signature} 모듈이 `env.{name}`을(를) 호스트와 다른 형식으로 가져옵니다. 호스트의 형식은 {signature}입니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 4d2d1b7071..c5151622d4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5169,7 +5169,8 @@ mark-style Japanese Japans Bevel both sides Afschuining aan beide zijden Presets Voorinstellingen @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Een object kan maar één 3D-effect hebben. Pas de opties van het bestaande effect aan of verwijder het eerst. -@msg {label} currently requires a path or compound path. Convert type, images and groups to paths first. {label} vereist momenteel een pad of samengesteld pad. Zet tekst, afbeeldingen en groepen eerst om naar paden. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} vereist momenteel een pad, samengesteld pad, tekst, groep, vermenging of symboolinstantie. Breid andere objecten eerst uit. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan geen massief object maken van een afbeelding: traceer deze eerst met Object › Afbeelding traceren › Maken. @msg {label} requires a shape with at least two anchors {label} vereist een vorm met minstens twee ankerpunten @msg The shape is too complex for a 3D effect De vorm is te complex voor een 3D-effect @msg The 3D surface is too complex; simplify the shape Het 3D-oppervlak is te complex; vereenvoudig de vorm @@ -5868,6 +5869,7 @@ axis Y Axis Y-as Show its progress, see Cancel and write log lines De voortgang tonen, een annulering zien en logregels schrijven Keep settings of its own Eigen instellingen bewaren Keep a cache of its own, which you can clear Een eigen cache bewaren, die u kunt legen + Run these commands on the document: {ids} Deze opdrachten op het document uitvoeren: {ids} Clear Plug-in Cache Plug-incache legen # Actions panel: action sets (#3712). New Set… Nieuwe set… diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index c4a5d4f33a..58016a4bd0 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4471,6 +4471,11 @@ imageTrace Outline Kontur @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) błąd wewnętrzny w `{cmd}`: {msg} (dokument pozostał bez zmian; zgłoś ten błąd) @msg internal error: {msg} (please report this bug) błąd wewnętrzny: {msg} (zgłoś ten błąd) @msg invalid PDF setting: {0} nieprawidłowe ustawienie PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): jest zapisywana z UserUnit {unit}, więc aplikacje ignorujące UserUnit pokazują ją tyle razy mniejszą +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in strona obszaru kompozycji {n} ma {size}, czyli więcej niż limit strony PDF wynoszący 14 400 pt (200 in): strony {label} są zapisywane bez UserUnit, w punktach, a aplikacje przestrzegające limitu przycinają stronę do 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 nie ma UserUnit, którego strona dłuższa niż 14 400 pt (200 in) potrzebuje, aby zachować rozmiar: plik jest zapisywany jako PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units strona obszaru kompozycji {n} ma {size} i jest za długa i za wąska dla boków strony PDF od 3 do 14 400 jednostek: jest zapisywana z UserUnit {unit}, która utrzymuje krótszy bok na co najmniej 3 jednostkach, a aplikacje przestrzegające limitu przycinają dłuższy bok do 14 400 jednostek +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard pliki {label} mieszczą liczby rzeczywiste do {max}, a strona obszaru kompozycji {n} o długości {side} pt wymaga większych: wybierz PDF 1.6 lub nowszy bez standardu PDF/X albo mniejszy obszar kompozycji @msg invalid image data for `{0}` nieprawidłowe dane obrazu dla `{0}` @msg invalid parameters for `{cmd}`: {msg} nieprawidłowe parametry dla `{cmd}`: {msg} @msg is not an image VectorCraft reads nie jest obrazem obsługiwanym przez VectorCraft @@ -5446,7 +5451,8 @@ mark-style Japanese Japońskie Bevel both sides Faza po obu stronach Presets Ustawienia @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Obiekt może mieć jeden efekt 3D. Edytuj opcje istniejącego efektu lub najpierw go usuń. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} wymaga obecnie ścieżki, ścieżki złożonej, tekstu lub grupy. Najpierw przekonwertuj obrazy i inne obiekty na ścieżki. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} wymaga obecnie ścieżki, ścieżki złożonej, tekstu, grupy, przejścia lub wystąpienia symbolu. Najpierw rozszerz inne obiekty. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} nie może utworzyć bryły z obrazu: najpierw obrysuj go poleceniem Obiekt › Obrys obrazu › Utwórz. @msg {label} requires a shape with at least two anchors {label} wymaga kształtu z co najmniej dwoma punktami @msg The shape is too complex for a 3D effect Kształt jest zbyt złożony dla efektu 3D @msg The 3D surface is too complex; simplify the shape Powierzchnia 3D jest zbyt złożona; uprość kształt @@ -5824,6 +5830,20 @@ axis Y Axis Oś Y Show its progress, see Cancel and write log lines Pokazywać swój postęp, wykrywać anulowanie i zapisywać wiersze dziennika Keep settings of its own Przechowywać własne ustawienia Keep a cache of its own, which you can clear Przechowywać własną pamięć podręczną, którą możesz wyczyścić + Run these commands on the document: {ids} Uruchamiać w dokumencie te polecenia: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call „{name}” wymienia w `commandAllowlist` polecenie `{id}`, którego wtyczka nie może wywołać +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` manifestu go nie wymienia +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID lub argumenty leżą poza pamięcią modułu +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID lub argumenty nie są w UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenty nie są obiektem JSON +@msg only a filter with the usual budget declares `commandAllowlist` tylko filtr ze zwykłym budżetem deklaruje `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) wywołania poleceń ({MAX_CALLS} wywołań i {MAX_CALL_BYTES} bajtów na uruchomienie) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) rozmiar wywołania polecenia (vc_call `{shown}`: {len} bajtów, limit {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` najwyżej {MAX_ALLOWED_COMMANDS} poleceń w `commandAllowlist` +@msg a plug-in may not call this command wtyczka nie może wywołać tego polecenia +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` potrzebuje uprawnienia `commands`, a `commands` potrzebuje `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` wymienia `{shown}`, które nie jest ID polecenia lub występuje dwa razy Clear Plug-in Cache Wyczyść pamięć podręczną wtyczki @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} uprawnienie `{permission}` wymaga poziomu API wtyczek {PROGRESS_API}: podaj `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} moduł importuje `env.{name}` z innym typem niż typ hosta: typ hosta to {signature} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 5139495efe..b0d940693f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3889,6 +3889,11 @@ axis Both Ambos @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) erro interno em `{cmd}`: {msg} (o documento foi mantido como estava; relate este bug) @msg internal error: {msg} (please report this bug) erro interno: {msg} (relate este bug) @msg invalid PDF setting: {0} configuração de PDF inválida: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): ela é gravada com um UserUnit de {unit}, então apps que ignoram UserUnit a mostram essa quantidade de vezes menor +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in a página da prancheta {n} tem {size}, mais que o limite de página do PDF de 14.400 pt (200 in): páginas {label} são gravadas sem UserUnit, em pontos, e apps que respeitam o limite cortam a página em 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 o PDF 1.5 não tem UserUnit, de que uma página com mais de 14.400 pt (200 in) precisa para manter seu tamanho: o arquivo é gravado como PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units a página da prancheta {n} tem {size}, longa e estreita demais para os lados de página do PDF, de 3 a 14.400 unidades: ela é gravada com uma UserUnit de {unit}, que mantém o lado menor em 3 unidades ou mais, e os apps que seguem o limite cortam o lado maior em 14.400 unidades +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard os arquivos {label} aceitam números reais de até {max}, e a página da prancheta {n}, com {side} pt, precisa de números maiores: escolha PDF 1.6 ou posterior sem padrão PDF/X, ou uma prancheta menor @msg invalid image data for `{0}` dados de imagem inválidos para `{0}` @msg invalid parameters for `{cmd}`: {msg} parâmetros inválidos para `{cmd}`: {msg} @msg is not an image VectorCraft reads não é uma imagem que o VectorCraft lê @@ -5561,7 +5566,8 @@ mark-style Japanese Japonesas Bevel both sides Chanfro nos Dois Lados Presets Predefinidos @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Um objeto aceita apenas um efeito 3D. Edite as opções do efeito existente ou remova-o primeiro. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} exige, por enquanto, um caminho, caminho composto, texto ou grupo. Converta antes imagens e outros objetos em caminhos. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} exige, por enquanto, um caminho, caminho composto, texto, grupo, mesclagem ou instância de símbolo. Expanda antes os outros objetos. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} não pode criar um sólido a partir de uma imagem: rastreie-a antes com Objeto › Rastreamento de Imagem › Criar. @msg {label} requires a shape with at least two anchors {label} exige uma forma com pelo menos dois pontos de ancoragem @msg The shape is too complex for a 3D effect A forma é complexa demais para um efeito 3D @msg The 3D surface is too complex; simplify the shape A superfície 3D é complexa demais; simplifique a forma @@ -5885,6 +5891,20 @@ axis Y Axis Eixo Y Show its progress, see Cancel and write log lines Mostrar seu progresso, detectar o cancelamento e gravar linhas de log Keep settings of its own Guardar configurações próprias Keep a cache of its own, which you can clear Guardar um cache próprio, que você pode limpar + Run these commands on the document: {ids} Executar estes comandos no documento: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” lista `{id}` em `commandAllowlist`, que um plug-in não pode chamar +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: o `commandAllowlist` do manifesto não o lista +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: o ID ou os argumentos estão fora da memória do módulo +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: o ID ou os argumentos não são UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: os argumentos não são um objeto JSON +@msg only a filter with the usual budget declares `commandAllowlist` somente um filtro com o orçamento habitual declara `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) chamadas de comandos ({MAX_CALLS} chamadas e {MAX_CALL_BYTES} bytes por execução) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) tamanho de uma chamada de comando (vc_call `{shown}`: {len} bytes, limite {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` no máximo {MAX_ALLOWED_COMMANDS} comandos em `commandAllowlist` +@msg a plug-in may not call this command um plug-in não pode chamar este comando +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` precisa da permissão `commands`, e `commands` precisa de um `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` lista `{shown}`, que não é um ID de comando ou aparece duas vezes Clear Plug-in Cache Limpar cache do plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} a permissão `{permission}` exige o nível de API de plug-in {PROGRESS_API}: informe `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} o módulo importa `env.{name}` com um tipo diferente do tipo do host: o do host é {signature} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 803159a1dd..a00325e8b8 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4375,6 +4375,11 @@ axis Both Оба @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) внутренняя ошибка в `{cmd}`: {msg} (документ оставлен в прежнем состоянии; пожалуйста, сообщите об этой ошибке) @msg internal error: {msg} (please report this bug) внутренняя ошибка: {msg} (пожалуйста, сообщите об этой ошибке) @msg invalid PDF setting: {0} недопустимый параметр PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): она записывается с UserUnit {unit}, поэтому приложения, которые игнорируют UserUnit, показывают её во столько же раз меньше +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in страница монтажной области {n} имеет размер {size}, что больше ограничения PDF на размер страницы в 14 400 pt (200 in): страницы {label} записываются без UserUnit, в пунктах, и приложения, соблюдающие ограничение, обрезают страницу до 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 в PDF 1.5 нет UserUnit, который нужен странице длиннее 14 400 pt (200 in), чтобы сохранить размер: файл записывается как PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units страница монтажной области {n} имеет размер {size} и слишком длинная и узкая для сторон страницы PDF от 3 до 14 400 единиц: она записывается с UserUnit {unit}, которая держит короткую сторону не меньше 3 единиц, а приложения, соблюдающие предел, обрезают длинную сторону до 14 400 единиц +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файлы {label} вмещают вещественные числа до {max}, а странице монтажной области {n} длиной {side} pt нужны большие: выберите PDF 1.6 или новее без стандарта PDF/X или монтажную область меньшего размера @msg invalid image data for `{0}` недопустимые данные изображения для `{0}` @msg invalid parameters for `{cmd}`: {msg} недопустимые параметры для `{cmd}`: {msg} @msg is not an image VectorCraft reads не является изображением, которое читает VectorCraft @@ -5219,7 +5224,8 @@ lighting Light Свет Bevel both sides Фаска с обеих сторон Presets Наборы @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. У объекта может быть только один 3D-эффект. Измените параметры существующего эффекта или сначала удалите его. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}: пока требуется контур, составной контур, текст или группа. Сначала преобразуйте изображения и другие объекты в контуры. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: пока требуется контур, составной контур, текст, группа, переход или экземпляр символа. Сначала разберите другие объекты. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: из изображения нельзя построить тело. Сначала трассируйте его командой Объект › Трассировка изображения › Создать. @msg {label} requires a shape with at least two anchors {label}: требуется фигура не менее чем с двумя опорными точками @msg The shape is too complex for a 3D effect Фигура слишком сложна для 3D-эффекта @msg The 3D surface is too complex; simplify the shape 3D-поверхность слишком сложна; упростите фигуру @@ -5581,6 +5587,20 @@ axis Y Axis Ось Y Show its progress, see Cancel and write log lines Показывать свой ход выполнения, замечать отмену и записывать строки журнала Keep settings of its own Хранить собственные настройки Keep a cache of its own, which you can clear Хранить собственный кэш, который можно очистить + Run these commands on the document: {ids} Выполнять в документе эти команды: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» указывает в `commandAllowlist` команду `{id}`, которую модуль вызывать не может +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: в `commandAllowlist` манифеста её нет +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID или аргументы лежат вне памяти модуля +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID или аргументы не в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументы не являются объектом JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` может объявлять только фильтр с обычным бюджетом +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) вызовы команд ({MAX_CALLS} вызовов и {MAX_CALL_BYTES} байт за запуск) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) размер вызова команды (vc_call `{shown}`: {len} байт, предел {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` не более {MAX_ALLOWED_COMMANDS} команд в `commandAllowlist` +@msg a plug-in may not call this command модуль не может вызывать эту команду +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` для `commandAllowlist` нужно разрешение `commands`, а для `commands` нужен `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` указывает `{shown}`, который не является ID команды или указан дважды Clear Plug-in Cache Очистить кэш модуля @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} разрешению `{permission}` нужен уровень API модулей {PROGRESS_API}: укажите `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} модуль импортирует `env.{name}` с другим типом, чем у хоста: у хоста тип {signature} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8dd68ee2e6..f2b24e7d08 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4243,6 +4243,11 @@ axis Both Båda @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) internt fel i `{cmd}`: {msg} (dokumentet lämnades som det var innan; rapportera gärna felet) @msg internal error: {msg} (please report this bug) internt fel: {msg} (rapportera gärna felet) @msg invalid PDF setting: {0} ogiltig PDF-inställning: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): den skrivs med en UserUnit på {unit}, så appar som ignorerar UserUnit visar den så många gånger mindre +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in sidan för rityta {n} är {size}, längre än PDF:s sidgräns på 14 400 pt (200 in): {label}-sidor skrivs utan UserUnit, i punkter, och appar som håller sig till gränsen beskär sidan till 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 har ingen UserUnit, som en sida längre än 14 400 pt (200 in) behöver för att behålla sin storlek: filen skrivs som PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units sidan för rityta {n} är {size}, för lång och smal för PDF:s sidlängder på 3 till 14 400 enheter: den skrivs med UserUnit {unit}, som håller den korta sidan på minst 3 enheter, och appar som följer gränsen klipper den långa sidan vid 14 400 enheter +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label}-filer rymmer reella tal upp till {max}, och sidan för rityta {n}, {side} pt lång, behöver större: välj PDF 1.6 eller senare utan PDF/X-standard, eller en mindre rityta @msg invalid image data for `{0}` ogiltiga bilddata för `{0}` @msg invalid parameters for `{cmd}`: {msg} ogiltiga parametrar för `{cmd}`: {msg} @msg is not an image VectorCraft reads är inte en bild som VectorCraft kan läsa @@ -5091,7 +5096,8 @@ lighting Light Ljus Bevel both sides Fasning på båda sidor Presets Förinställningar @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Ett objekt kan bara ha en 3D-effekt. Redigera alternativen för den befintliga effekten eller ta bort den först. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} kräver för närvarande en bana, sammansatt bana, text eller grupp. Konvertera bilder och andra objekt till banor först. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} kräver för närvarande en bana, sammansatt bana, text, grupp, blandning eller symbolinstans. Expandera andra objekt först. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} kan inte skapa en solid av en bild: kalkera den först med Objekt › Bildkalkering › Skapa. @msg {label} requires a shape with at least two anchors {label} kräver en form med minst två ankarpunkter @msg The shape is too complex for a 3D effect Formen är för komplex för en 3D-effekt @msg The 3D surface is too complex; simplify the shape 3D-ytan är för komplex; förenkla formen @@ -5993,6 +5999,20 @@ axis Y Axis Y-axel Show its progress, see Cancel and write log lines Visa sitt förlopp, se när det avbryts och skriva loggrader Keep settings of its own Spara egna inställningar Keep a cache of its own, which you can clear Spara en egen cache, som du kan tömma + Run these commands on the document: {ids} Köra dessa kommandon på dokumentet: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call ”{name}” anger `{id}` i `commandAllowlist`, som ett plugin inte får anropa +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: manifestets `commandAllowlist` anger det inte +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: id:t eller argumenten ligger utanför modulens minne +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: id:t eller argumenten är inte UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: argumenten är inte ett JSON-objekt +@msg only a filter with the usual budget declares `commandAllowlist` bara ett filter med den vanliga budgeten anger `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) kommandoanrop ({MAX_CALLS} anrop och {MAX_CALL_BYTES} byte per körning) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) storlek på ett kommandoanrop (vc_call `{shown}`: {len} byte, gräns {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` högst {MAX_ALLOWED_COMMANDS} kommandon i `commandAllowlist` +@msg a plug-in may not call this command ett plugin får inte anropa det här kommandot +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` behöver behörigheten `commands`, och `commands` behöver en `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` anger `{shown}`, som inte är ett kommando-id eller finns två gånger Clear Plug-in Cache Töm pluginets cache @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} behörigheten `{permission}` kräver plugin-API-nivå {PROGRESS_API}: ange `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} modulen importerar `env.{name}` med en annan typ än värdens: värdens typ är {signature} diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3479fd156b..76d73994b5 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4102,6 +4102,11 @@ axis Both Her İkisi @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) `{cmd}`de dahili hata: {msg} (belge daha önce olduğu gibi bırakıldı; lütfen bu hatayı bildirin) @msg internal error: {msg} (please report this bug) dahili hata: {msg} (lütfen bu hatayı bildirin) @msg invalid PDF setting: {0} geçersiz PDF ayarı: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {unit} UserUnit değeriyle yazılır, bu yüzden UserUnit'i yok sayan uygulamalar onu o kadar kat küçük gösterir +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in {n} çalışma yüzeyinin sayfası {size}, PDF'nin 14.400 pt (200 in) sayfa sınırından uzun: {label} sayfaları UserUnit olmadan, punto cinsinden yazılır ve sınıra uyan uygulamalar sayfayı 200 in'de keser +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5'te, 14.400 pt (200 in) uzunluğunu aşan bir sayfanın boyutunu koruması için gereken UserUnit yoktur: dosya PDF 1.6 olarak yazılır +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units {n} çalışma yüzeyinin sayfası {size}, PDF'nin 3 ile 14.400 birim arasındaki sayfa kenarları için fazla uzun ve dar: kısa kenarı en az 3 birimde tutan {unit} UserUnit değeriyle yazılır ve sınıra uyan uygulamalar uzun kenarı 14.400 birimde keser +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} dosyaları en fazla {max} değerinde gerçek sayı tutar ve {n} çalışma yüzeyinin {side} pt uzunluğundaki sayfası daha büyüklerini gerektiriyor: PDF/X standardı olmadan PDF 1.6 veya sonrasını ya da daha küçük bir çalışma yüzeyi seçin @msg invalid image data for `{0}` `{0}` için geçersiz resim verileri @msg invalid parameters for `{cmd}`: {msg} `{cmd}` için geçersiz parametreler: {msg} @msg is not an image VectorCraft reads VectorCraft'ın okuduğu bir resim değil @@ -4887,7 +4892,8 @@ lighting Light Işık Bevel both sides Her iki tarafa da eğim verin Presets Ön ayarlar @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Bir nesne bir 3D efekti alır. Mevcut efektin seçeneklerini düzenleyin veya önce onu kaldırın. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} şu anda bir yol, bileşik yol, yazı veya grup gerektiriyor. Önce görüntüleri ve diğer nesneleri yollara dönüştürün. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} şu anda bir yol, bileşik yol, yazı, grup, karışım veya sembol örneği gerektiriyor. Önce diğer nesneleri genişletin. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} bir görüntüden katı cisim oluşturamaz: önce Nesne › Görüntü İzleme › Yap ile izleyin. @msg {label} requires a shape with at least two anchors {label} en az iki bağlantı noktasına sahip bir şekil gerektirir @msg The shape is too complex for a 3D effect Şekli 3 boyutlu bir efekt için fazla karmaşık @msg The 3D surface is too complex; simplify the shape 3 boyutlu yüzey çok karmaşık; şekli basitleştir @@ -5926,6 +5932,20 @@ axis Y Axis Y ekseni Show its progress, see Cancel and write log lines İlerlemesini gösterme, iptali algılama ve günlük satırları yazma Keep settings of its own Kendi ayarlarını saklama Keep a cache of its own, which you can clear Temizleyebileceğiniz kendi önbelleğini saklama + Run these commands on the document: {ids} Belgede şu komutları çalıştırma: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”, `commandAllowlist` içinde bir eklentinin çağıramayacağı `{id}` komutunu listeliyor +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: bildirimin `commandAllowlist` listesinde yok +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: kimlik veya bağımsız değişkenler modülün belleğinin dışında +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: kimlik veya bağımsız değişkenler UTF-8 değil +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: bağımsız değişkenler bir JSON nesnesi değil +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` yalnızca olağan bütçeli bir filtrede bildirilebilir +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) komut çağrıları (çalıştırma başına {MAX_CALLS} çağrı ve {MAX_CALL_BYTES} bayt) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) komut çağrısı boyutu (vc_call `{shown}`: {len} bayt, sınır {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` içinde en fazla {MAX_ALLOWED_COMMANDS} komut +@msg a plug-in may not call this command bir eklenti bu komutu çağıramaz +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` için `commands` izni, `commands` için de bir `commandAllowlist` gerekir +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist`, komut kimliği olmayan veya iki kez listelenen `{shown}` öğesini adlandırıyor Clear Plug-in Cache Eklenti Önbelleğini Temizle @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} `{permission}` izni için eklenti API düzeyi {PROGRESS_API} gerekir: `api` {PROGRESS_API} verin @msg the module imports `env.{name}` with another type than the host's: it is {signature} modül `env.{name}` öğesini ana bilgisayarınkinden farklı bir türle içe aktarıyor: ana bilgisayarın türü {signature} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b96c347dc6..4652ce4ca8 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4365,6 +4365,11 @@ axis Both Обидві @msg internal error in `{cmd}`: {msg} (the document was left as it was before; please report this bug) внутрішня помилка `{cmd}`: {msg} (документ залишений у попередньому стані; будь ласка, повідомте про цю помилку) @msg internal error: {msg} (please report this bug) внутрішня помилка: {msg} (будь ласка, повідомте про цю помилку) @msg invalid PDF setting: {0} неприпустимий параметр PDF: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): її записано з UserUnit {unit}, тому застосунки, які ігнорують UserUnit, показують її в стільки ж разів меншою +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in сторінка монтажної області {n} має розмір {size}, що більше за обмеження PDF на розмір сторінки в 14 400 pt (200 in): сторінки {label} записуються без UserUnit, у пунктах, і застосунки, що дотримуються обмеження, обрізають сторінку до 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 у PDF 1.5 немає UserUnit, який потрібен сторінці, довшій за 14 400 pt (200 in), щоб зберегти розмір: файл записується як PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units сторінка монтажної області {n} має розмір {size} і задовга та завузька для сторін сторінки PDF від 3 до 14 400 одиниць: її записано з UserUnit {unit}, що тримає коротку сторону не менше 3 одиниць, а застосунки, які дотримуються межі, обрізають довгу сторону до 14 400 одиниць +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard файли {label} вміщують дійсні числа до {max}, а сторінці монтажної області {n} завдовжки {side} pt потрібні більші: виберіть PDF 1.6 або новіший без стандарту PDF/X чи меншу монтажну область @msg invalid image data for `{0}` неприпустимі дані зображення для `{0}` @msg invalid parameters for `{cmd}`: {msg} неприпустимі параметри для `{cmd}`: {msg} @msg is not an image VectorCraft reads не є зображенням, яке читає VectorCraft @@ -5205,7 +5210,8 @@ lighting Light Світло Bevel both sides Фаска з обох боків Presets Набори @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. Об'єкт може мати лише один 3D-ефект. Змініть параметри наявного ефекту або спершу вилучіть його. -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}: поки що потрібен контур, складений контур, текст або група. Спершу перетворіть зображення та інші об'єкти на контури. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}: поки що потрібен контур, складений контур, текст, група, перехід або екземпляр символу. Спершу розберіть інші об'єкти. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}: із зображення не можна побудувати тіло. Спершу трасуйте його командою Об’єкт › Трасування зображення › Створити. @msg {label} requires a shape with at least two anchors {label}: потрібна фігура щонайменше з двома опорними точками @msg The shape is too complex for a 3D effect Фігура надто складна для 3D-ефекту @msg The 3D surface is too complex; simplify the shape 3D-поверхня надто складна; спростіть фігуру @@ -5567,6 +5573,20 @@ axis Y Axis Вісь Y Show its progress, see Cancel and write log lines Показувати свій поступ, помічати скасування і записувати рядки журналу Keep settings of its own Зберігати власні налаштування Keep a cache of its own, which you can clear Зберігати власний кеш, який можна очистити + Run these commands on the document: {ids} Виконувати в документі ці команди: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call «{name}» вказує в `commandAllowlist` команду `{id}`, яку модуль викликати не може +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: у `commandAllowlist` маніфесту її немає +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID або аргументи лежать поза пам’яттю модуля +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID або аргументи не в UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: аргументи не є об’єктом JSON +@msg only a filter with the usual budget declares `commandAllowlist` `commandAllowlist` може оголошувати лише фільтр зі звичайним бюджетом +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) виклики команд ({MAX_CALLS} викликів і {MAX_CALL_BYTES} байтів за запуск) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) розмір виклику команди (vc_call `{shown}`: {len} байтів, межа {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` щонайбільше {MAX_ALLOWED_COMMANDS} команд у `commandAllowlist` +@msg a plug-in may not call this command модуль не може викликати цю команду +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` для `commandAllowlist` потрібен дозвіл `commands`, а для `commands` потрібен `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` вказує `{shown}`, що не є ID команди або вказане двічі Clear Plug-in Cache Очистити кеш модуля @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} дозволу `{permission}` потрібен рівень API модулів {PROGRESS_API}: укажіть `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} модуль імпортує `env.{name}` з іншим типом, ніж у хоста: у хоста тип {signature} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index ab43035c27..4c9dac833c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4624,6 +4624,11 @@ theme Appearance Giao diện @msg Invalid panel layout; restored the default dock Bố cục bảng không hợp lệ; đã phục hồi dock mặc định @msg invalid parameters for `{cmd}`: {msg} tham số không hợp lệ cho `{cmd}`: {msg} @msg invalid PDF setting: {0} cài đặt PDF không hợp lệ: {0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): trang được ghi với UserUnit là {unit}, nên các ứng dụng bỏ qua UserUnit sẽ hiển thị nó nhỏ đi bấy nhiêu lần +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in trang của bảng vẽ {n} có kích thước {size}, dài hơn giới hạn trang PDF 14.400 pt (200 in): các trang {label} được ghi không có UserUnit, theo đơn vị điểm, và các ứng dụng tuân theo giới hạn sẽ cắt trang ở 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 không có UserUnit, thứ mà trang dài hơn 14.400 pt (200 in) cần để giữ kích thước: tệp được ghi dưới dạng PDF 1.6 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units trang của bảng vẽ {n} có kích thước {size}, quá dài và hẹp so với cạnh trang PDF từ 3 đến 14.400 đơn vị: trang được ghi với UserUnit {unit}, giữ cạnh ngắn từ 3 đơn vị trở lên, và các ứng dụng tuân theo giới hạn sẽ cắt cạnh dài ở 14.400 đơn vị +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard tệp {label} chỉ chứa số thực tối đa {max}, còn trang của bảng vẽ {n} dài {side} pt cần số lớn hơn: hãy chọn PDF 1.6 trở lên không theo tiêu chuẩn PDF/X, hoặc một bảng vẽ nhỏ hơn @msg invalid restored panel group nhóm bảng được phục hồi không hợp lệ @msg is not an image VectorCraft reads không phải ảnh mà VectorCraft đọc được @msg it ends inside a group or compound path nó kết thúc bên trong một nhóm hoặc đường dẫn phức @@ -5205,7 +5210,8 @@ theme Appearance Giao diện @msg {C}: no effect at index {from} {C}: không có hiệu ứng tại chỉ mục {from} @msg {depth}-bit PSD files in this colour mode can't be read tệp PSD {depth}-bit ở chế độ màu này không thể đọc được @msg {key} must be a finite coordinate {key} phải là tọa độ hữu hạn -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label} hiện yêu cầu một đường dẫn, đường dẫn phức, văn bản hoặc nhóm. Hãy chuyển hình ảnh và các đối tượng khác thành đường dẫn trước. +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label} hiện yêu cầu một đường dẫn, đường dẫn phức, văn bản, nhóm, hòa trộn hoặc thực thể ký hiệu. Hãy mở rộng các đối tượng khác trước. +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label} không thể tạo khối từ hình ảnh: hãy vector hóa ảnh trước bằng Đối tượng › Vector hóa ảnh › Tạo. @msg {label} produced an empty result {label} tạo ra kết quả trống @msg {label} requires a shape with at least two anchors {label} yêu cầu một hình dạng có ít nhất hai điểm neo @msg {label}: lost track of a shape's style {label}: mất dấu kiểu của hình dạng @@ -5568,6 +5574,20 @@ axis Y Axis Trục Y Show its progress, see Cancel and write log lines Hiển thị tiến độ, nhận biết yêu cầu hủy và ghi các dòng nhật ký Keep settings of its own Lưu cài đặt riêng Keep a cache of its own, which you can clear Lưu bộ nhớ đệm riêng mà bạn có thể xóa + Run these commands on the document: {ids} Chạy các lệnh này trên tài liệu: {ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}” liệt kê `{id}` trong `commandAllowlist`, lệnh mà plug-in không được gọi +@msg vc_call `{shown}`: {why} vc_call `{shown}`: {why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`: `commandAllowlist` của manifest không liệt kê lệnh này +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`: ID hoặc đối số nằm ngoài bộ nhớ của mô-đun +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`: ID hoặc đối số không phải UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`: đối số không phải là đối tượng JSON +@msg only a filter with the usual budget declares `commandAllowlist` chỉ bộ lọc có ngân sách thông thường mới khai báo `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) lệnh gọi lệnh ({MAX_CALLS} lần gọi và {MAX_CALL_BYTES} byte mỗi lần chạy) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) kích thước lệnh gọi lệnh (vc_call `{shown}`: {len} byte, giới hạn {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` tối đa {MAX_ALLOWED_COMMANDS} lệnh trong `commandAllowlist` +@msg a plug-in may not call this command plug-in không được gọi lệnh này +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` cần quyền `commands`, và `commands` cần một `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` nêu `{shown}`, không phải ID lệnh hoặc được liệt kê hai lần Clear Plug-in Cache Xóa bộ nhớ đệm của plug-in @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} quyền `{permission}` cần API plug-in cấp {PROGRESS_API}: hãy đặt `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} mô-đun nhập `env.{name}` với kiểu khác với kiểu của máy chủ: kiểu của máy chủ là {signature} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b5105e92ec..c62b176687 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4320,6 +4320,11 @@ imageTrace Outline 轮廓 @msg artboard {0} does not exist 画板 {0} 不存在 @msg cannot read PDF: {0} 无法读取 PDF:{0} @msg invalid PDF setting: {0} PDF 设置无效:{0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):它以 UserUnit {unit} 写入,因此忽略 UserUnit 的应用会将其显示为缩小相应倍数 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 画板 {n} 的页面为 {size},超过 PDF 的页面上限 14,400 pt (200 in):{label} 页面不带 UserUnit,以点为单位写入,遵守上限的应用会将页面裁切为 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 没有 UserUnit,而长于 14,400 pt (200 in) 的页面需要它来保持尺寸:文件将以 PDF 1.6 写入 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 画板 {n} 的页面为 {size},对 PDF 3 至 14,400 单位的页面边长而言过长过窄:以 UserUnit {unit} 写入,使短边保持 3 单位以上,遵守上限的应用会把长边裁到 14,400 单位 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 文件的实数最大为 {max},而画板 {n} 的页面长 {side} pt,需要更大的数:请选择不带 PDF/X 标准的 PDF 1.6 或更高版本,或使用更小的画板 @msg page {0} does not exist (the PDF has {1}) 页面 {0} 不存在 (该 PDF 有 {1} 页) @msg thumbnail: no page {n} (the file has 1) thumbnail:页面 {n} 不存在 (该文件有 1 页) @msg the PDF has no pages 该 PDF 没有页面 @@ -5486,7 +5491,8 @@ lighting Light 光源 Bevel both sides 双面斜角 Presets 预设 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 一个对象只能应用一种 3D 效果。请编辑现有效果的选项,或先将其移去。 -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}目前需要路径、复合路径、文字或编组。请先将图像和其他对象转换为路径。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}目前需要路径、复合路径、文字、编组、混合或符号实例。请先扩展其他对象。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}无法从图像生成立体:请先使用“对象 › 图像描摹 › 创建”进行描摹。 @msg {label} requires a shape with at least two anchors {label}需要至少有两个锚点的形状 @msg The shape is too complex for a 3D effect 形状过于复杂,无法应用 3D 效果 @msg The 3D surface is too complex; simplify the shape 3D 表面过于复杂;请简化形状 @@ -5808,6 +5814,20 @@ axis Y Axis Y 轴 Show its progress, see Cancel and write log lines 显示进度、检测取消请求并写入日志行 Keep settings of its own 保存自己的设置 Keep a cache of its own, which you can clear 保存自己的缓存,您可以清除它 + Run these commands on the document: {ids} 在文档上运行这些命令:{ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call “{name}”在 `commandAllowlist` 中列出了增效工具不能调用的 `{id}` +@msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`:清单的 `commandAllowlist` 未列出它 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`:ID 或参数位于模块内存之外 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`:ID 或参数不是 UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`:参数不是 JSON 对象 +@msg only a filter with the usual budget declares `commandAllowlist` 只有使用通常预算的滤镜才能声明 `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 命令调用(每次运行 {MAX_CALLS} 次调用和 {MAX_CALL_BYTES} 字节) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 命令调用大小(vc_call `{shown}`:{len} 字节,上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` 中最多 {MAX_ALLOWED_COMMANDS} 个命令 +@msg a plug-in may not call this command 增效工具不能调用此命令 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` 需要权限 `commands`,而 `commands` 需要 `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` 列出的 `{shown}` 不是命令 ID,或列出了两次 Clear Plug-in Cache 清除增效工具缓存 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 权限 `{permission}` 需要增效工具 API 级别 {PROGRESS_API}:请设置 `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} 模块以与宿主不同的类型导入 `env.{name}`:宿主的类型为 {signature} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index d853aa88cf..0b3a21250c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2158,6 +2158,11 @@ file-filter Templates 範本 @msg artboard {0} does not exist 工作區域 {0} 不存在 @msg cannot read PDF: {0} 無法讀取 PDF:{0} @msg invalid PDF setting: {0} PDF 設定無效:{0} +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): it is written with a UserUnit of {unit}, so apps that ignore UserUnit show it that many times smaller 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):它以 UserUnit {unit} 寫入,因此忽略 UserUnit 的應用程式會將其顯示為縮小相應倍數 +@msg the page of artboard {n} is {size}, longer than PDF's page limit of 14,400 pt (200 in): {label} pages are written without a UserUnit, in points, and apps that keep to the limit cut the page to 200 in 工作區域 {n} 的頁面為 {size},超過 PDF 的頁面上限 14,400 pt (200 in):{label} 頁面不含 UserUnit,以點為單位寫入,遵守上限的應用程式會將頁面裁切為 200 in +@msg PDF 1.5 has no UserUnit, which a page longer than 14,400 pt (200 in) needs to keep its size: the file is written as PDF 1.6 PDF 1.5 沒有 UserUnit,而長於 14,400 pt (200 in) 的頁面需要它來保持尺寸:檔案將以 PDF 1.6 寫入 +@msg the page of artboard {n} is {size}, too long and narrow for PDF's page sides of 3 to 14,400 units: it is written with a UserUnit of {unit}, which keeps the short side at 3 units or more, and apps that keep to the limit cut the long side to 14,400 units 工作區域 {n} 的頁面為 {size},對 PDF 3 至 14,400 單位的頁面邊長而言過長過窄:以 UserUnit {unit} 寫入,使短邊保持 3 單位以上,遵守上限的應用程式會把長邊裁到 14,400 單位 +@msg {label} files hold real numbers up to {max}, and the page of artboard {n}, {side} pt long, needs larger ones: choose PDF 1.6 or later without a PDF/X standard, or a smaller artboard {label} 檔案的實數最大為 {max},而工作區域 {n} 的頁面長 {side} pt,需要更大的數:請選擇不含 PDF/X 標準的 PDF 1.6 或更新版本,或使用較小的工作區域 @msg page {0} does not exist (the PDF has {1}) 頁面 {0} 不存在 (此 PDF 有 {1} 頁) @msg the PDF has no pages 此 PDF 沒有頁面 @msg the PDF is password-protected: give its password 此 PDF 受密碼保護:請提供其密碼 @@ -5312,7 +5317,8 @@ lighting Light 光源 Bevel both sides 雙面斜角 Presets 預設集 @msg An object takes one 3D effect. Edit the existing effect's options, or remove it first. 一個物件只能套用一種 3D 效果。請編輯現有效果的選項,或先將其移除。 -@msg {label} currently requires a path, compound path, type or group. Convert images and other objects to paths first. {label}目前需要路徑、複合路徑、文字或群組。請先將影像和其他物件轉換為路徑。 +@msg {label} currently requires a path, compound path, type, group, blend or symbol instance. Expand other objects first. {label}目前需要路徑、複合路徑、文字、群組、漸變或符號範例。請先展開其他物件。 +@msg {label} can't build a solid from an image: trace it first with Object › Image Trace › Make. {label}無法從影像建立立體:請先使用「物件 › 影像描圖 › 製作」描圖。 @msg {label} requires a shape with at least two anchors {label}需要至少有兩個錨點的形狀 @msg The shape is too complex for a 3D effect 形狀過於複雜,無法套用 3D 效果 @msg The 3D surface is too complex; simplify the shape 3D 表面過於複雜;請簡化形狀 @@ -5605,6 +5611,20 @@ axis Y Axis Y 軸 Show its progress, see Cancel and write log lines 顯示進度、偵測取消要求並寫入記錄行 Keep settings of its own 保存自己的設定 Keep a cache of its own, which you can clear 保存自己的快取,您可以清除它 + Run these commands on the document: {ids} 在文件上執行這些指令:{ids} +@msg “{name}” lists `{id}` in `commandAllowlist`, which a plug-in may not call 「{name}」在 `commandAllowlist` 中列出了增效模組不能呼叫的 `{id}` +@msg vc_call `{shown}`: {why} vc_call `{shown}`:{why} +@msg vc_call `{shown}`: the manifest's `commandAllowlist` doesn't list it vc_call `{shown}`:資訊清單的 `commandAllowlist` 未列出它 +@msg vc_call `{shown}`: the id or the arguments lie outside the module's memory vc_call `{shown}`:ID 或引數位於模組記憶體之外 +@msg vc_call `{shown}`: the id or the arguments are not UTF-8 vc_call `{shown}`:ID 或引數不是 UTF-8 +@msg vc_call `{shown}`: the arguments are not a JSON object vc_call `{shown}`:引數不是 JSON 物件 +@msg only a filter with the usual budget declares `commandAllowlist` 只有使用一般預算的濾鏡才能宣告 `commandAllowlist` +@msg command calls ({MAX_CALLS} calls and {MAX_CALL_BYTES} bytes per run) 指令呼叫(每次執行 {MAX_CALLS} 次呼叫和 {MAX_CALL_BYTES} 位元組) +@msg command call size (vc_call `{shown}`: {len} bytes, limit {MAX_CALL_DATA}) 指令呼叫大小(vc_call `{shown}`:{len} 位元組,上限 {MAX_CALL_DATA}) +@msg at most {MAX_ALLOWED_COMMANDS} commands in `commandAllowlist` `commandAllowlist` 中最多 {MAX_ALLOWED_COMMANDS} 個指令 +@msg a plug-in may not call this command 增效模組不能呼叫此指令 +@msg `commandAllowlist` needs the permission `commands`, and `commands` needs a `commandAllowlist` `commandAllowlist` 需要權限 `commands`,而 `commands` 需要 `commandAllowlist` +@msg `commandAllowlist` names `{shown}`, which is not a command id or is listed twice `commandAllowlist` 列出的 `{shown}` 不是指令 ID,或列出了兩次 Clear Plug-in Cache 清除增效模組快取 @msg permission `{permission}` needs plug-in API level {PROGRESS_API}: give `api` {PROGRESS_API} 權限 `{permission}` 需要增效模組 API 層級 {PROGRESS_API}:請設定 `api` {PROGRESS_API} @msg the module imports `env.{name}` with another type than the host's: it is {signature} 模組以與主機不同的類型匯入 `env.{name}`:主機的類型為 {signature} diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index a75171ae36..50f13e695e 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -172,10 +172,13 @@ pub fn install_plugin(app: &mut VectorcraftApp, p: &Value) -> Result String { +/// What permission `name` lets a plug-in do, in plain words in the UI language, with the ids of +/// the `commands` it may call for `commands`; a name the app doesn't know is shown as it is. +fn permission_words(name: &str, commands: &[String]) -> String { let words = match permissions::Permission::parse(name) { + Some(permissions::Permission::Commands) => { + return crate::i18n::fmt(tl!("Run these commands on the document: {ids}"), &[("ids", &commands.join(", "))]); + } Some(permissions::Permission::DocRead) => tl!("Read the objects it is given"), Some(permissions::Permission::DocWrite) => tl!("Change, add and delete objects in the document"), Some(permissions::Permission::State) => tl!("Keep data of its own with the document"), @@ -244,7 +247,11 @@ pub fn install_module(app: &mut VectorcraftApp, module: Value) -> Result = info["commandAllowlist"] + .as_array() + .map(|ids| ids.iter().filter_map(Value::as_str).map(|id| permissions::display_text(id, permissions::MAX_SHOWN_FIELD)).collect()) + .unwrap_or_default(); + lines.extend(asked.iter().filter_map(Value::as_str).map(|p| format!("• {}", permission_words(p, &commands)))); paragraphs.push(lines.join("\n")); install["grant"] = Value::Array(asked.clone()); } diff --git a/docs/mcp.md b/docs/mcp.md index a0a7f20b47..e263ddf1dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -840,7 +840,16 @@ transparency and rasterized areas are clipped to their regions. A file that woul export. PDF/X-1a and PDF/X-3 files are PDF 1.3 files too. A page with a side longer than 14,400 pt is written with a `UserUnit` (PDF 1.6): its longer side divided by 14,400, rounded up to the next thousandth, with the page's sizes and coordinates in those units, so that no side is longer than -14,400 units (ISO 32000-1, Annex C.2). In PDF 1.3 to 1.5 files and PDF/X files, such a page is written in points. +14,400 units (ISO 32000-1, Annex C.2). A PDF 1.5 file with such a page is written as PDF 1.6, with a warning, and +keeps PDF 1.5's encryption (128-bit RC4). PDF/X files and PDF 1.3 and 1.4 files write such a page in points, and apps +that keep to the limit cut it to 200 in. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can +be at most 32,767, and whole numbers are written as integers: a page longer than 32,767 pt whose sides aren't whole +numbers of points fails the export with an error naming the page before the thumbnails are drawn and the transparency is +flattened, and one whose art needs a real number past 32,767 fails with the same error when the file is written. A page whose short side is 3 pt or longer but would be under 3 units at that +`UserUnit` (Annex C.2 gives 3 as the smallest page side), such as 30 m × 6 mm, gets a smaller `UserUnit`: its short +side divided by 3, rounded down to the next thousandth, so that the short side is at least 3 units and the long side is +longer than 14,400 units. Each such page adds a warning with its size and how it is written. File › Print writes pages in +points, 14,400 pt at most. An Illustrator EPS (version 9 on) or `.ai` file opens from the editing data it carries (after the EPS page; in the `.ai` file's PDF private data): layers and sublayers (name, order, visibility, lock, printing, preview, dimming, @@ -1114,7 +1123,7 @@ before anything runs, with the step's number and its entry (`entry 3`) or line ( ### What a headless session remembers -`vectorcraft-cli run` and the headless `mcp` server keep two things between runs, in folders next to the +`vectorcraft-cli run` and the headless `mcp` server keep these between runs, in folders and files next to the preferences (the folder the desktop app uses, so both see the same ones; `VECTORCRAFT_CONFIG_DIR` moves it): - **Saved PDF presets** (`pdf.preset.save`, `.delete`, `.import`): one `.vcpdfpresets` file per preset in @@ -1125,8 +1134,12 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR command, so `edit.colorSettings {"cmyk": "…"}` or a preset's output intent can name it in a later run. The copy is what counts: the original may move or be deleted. `color.removeProfile {name}` forgets a profile and its copy (not while it is a working space). +- **Color Settings** (`edit.colorSettings`): the RGB and CMYK working spaces, intent and black point + compensation go into `Color Settings.json` when they change, and are the active settings again at the next + start, after the profiles above are registered (#6335). Saved settings that name a profile that is no longer + there, or a damaged file, leave the defaults (logged), and the next change writes over the file. -Not remembered: Color Settings, the document, anything else. Nothing is read or written when +Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or `--automation-write-root` keeps nothing either (the folders are outside its roots). A file that is damaged, too large (a profile over 32 MB, a presets file over 1 MB) or not a valid preset or profile is skipped and logged. When the @@ -1617,6 +1630,12 @@ the editing layer. With gradient mesh points picked, `opacity` goes to those poi {"name":"run_command","arguments":{"command":"transparency.info","params":{"ids":[12,20]}}} ``` +`transparency.makeOpacityMask` rejects a `clip` or `invert` value that is not a boolean, such as `"clip": "false"`, +and `transparency.setOpacityMask` does the same for `clip`, `invert`, `disabled` and `linked`. The toggles +`transparency.toggleNewMasksClipping`, `transparency.toggleNewMasksInverted`, `transparency.togglePageKnockoutGroup` +and `transparency.togglePageIsolatedBlending` reject a `value` that is not a boolean. A rejected call changes nothing. +Omitting a param or giving null keeps its default. + Knockout Group has three states: `transparency.set {knockout: "on"|"off"|"neutral"}` (`true` = on, `false` = neutral, the default). In a knockout group each child hides what it covers of the children below it; neutral groups pass the enclosing group's setting to their children, off groups never knock out. `knockoutShape: true` makes the @@ -1717,16 +1736,17 @@ overrides selected anchors or guides. Every explicit id is validated before any or unknown id leaves the document unchanged. An empty `ids` array does nothing. Layers themselves are kept, and selecting an ancestor together with its descendants deletes that subtree once. Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior. +With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a +boolean. + `edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an -ordinary path with the compound's paint, transparency, opacity mask and fill rule. A gradient fitted to the compound -keeps the compound's fit. Copy takes the whole compound when the compound itself is selected, or when every member is +ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's +graphic style while it has that style's look, and otherwise to no style. A gradient fitted to the compound keeps the compound's fit. Copy takes the whole compound when the compound itself is selected, or when every member is selected whole outside isolation mode, which includes the one member of a compound of one. In an isolated compound path each member is taken as itself. `edit.cut` removes the same objects it copies, so cutting one member leaves the other members in the compound, a compound of one member included. When Clear deletes every anchor or segment of every member, it also removes the compound. With a copied member still selected, `edit.pasteInFront` puts the path into the compound, just above the member. -With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a -boolean. `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is hidden or locked after the call: the selected objects it hides or locks, selected objects inside them, and selected objects @@ -2508,10 +2528,10 @@ default) white ones knock out instead; `"discard"` writes none. ## Revolve (initial 3D effect) `effect.apply {effect: "threeD.revolve", params: {...}, ids?, item?}` applies a live Revolve to a path, -compound path, type, or a group or layer of them. `effect.dialog` opens compact options with artboard rotation and light gizmos, `effect.setParams` edits it, and +compound path, type, clipping group, blend, symbol instance, or a group or layer of them. `effect.dialog` opens compact options with artboard rotation and light gizmos, `effect.setParams` edits it, and `effect.expandAppearance` bakes it into shaded vector faces. Native saves keep the editable source; SVG/PDF exports bake the same faces the canvas draws. Only one Revolve is supported per profile. -Type sweeps as its glyph outlines and stays type. On a group or layer, every visible member sweeps about one axis on the chosen edge of the members' bounds together, in its own paint, and the members stay editable. A group holding a clipping group, an image, a symbol instance or another object that can't be swept is refused, and so is type with no outlines or a group with no shape in it. +Type sweeps as its glyph outlines and stays type. On a group or layer, every visible member sweeps about one axis on the chosen edge of the members' bounds together, in its own paint, and the members stay editable. A clipping group sweeps its art inside the clipping path, a blend its keys and steps, and a symbol instance its symbol's art where the instance places it, alone or in a group ([three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances)). An image, alone or in a group, is refused with "trace it first with Object › Image Trace › Make"; a group holding another object that can't be swept is refused, and so is type with no outlines or a group with no shape in it. A surface takes at most 16,384 profile points and 163,840 faces, the members of a group together, counted after any geometry effects before the Revolve. A straight segment takes one point, a curve takes at least four, and each contour takes one. Each curved segment takes 16 samples; on a surface over those limits every curve takes as many as fit, down to 4, and the call is refused below that with "reduce Segments or simplify the profile". The call is also refused with "reduce Segments or simplify the gradient" when the faces' copies of the paint would take more than 256 MiB, counted together for the members of a group and for the fills and strokes of one object that carry a Revolve. To find the holes, mesh export cuts each sampled piece of a closed contour where it crosses another closed contour, adding a profile point at each cut, and tests the middle of each part against the closed contours whose bounds share its cell of a grid over the profile. It refuses the profile as too complex when its contours overlap so much that the search would take more than 16,000,000 steps, where each path element tested, each contour looked at and each contour placed in a grid cell counts one. Parameters: `angle` (degrees, 0..360, default 360), `offset` (points, 0..100000, default 0), @@ -2587,6 +2607,11 @@ checked as that effect's. It is one undo step. Any other `threeDType` value, or the other 3D types to a path or compound path, live like Revolve (the source stays editable; SVG/PDF exports and `effect.expandAppearance` use the same shaded faces). An object takes one 3D effect, Revolve included. On a group or layer the 3D effect goes on the group itself: `effect.apply` and `effect.setParams` refuse one on its fill or stroke. +Every 3D type, `threeD.classicExtrude` and `threeD.revolve` included, also applies to a clipping group, a blend or a +symbol instance, alone or in a group, and builds from the art it shows, the same way for the canvas, exports and +`assets.add3D` ([three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances)); like a group, it takes the +effect on the object itself, not on a fill or stroke. An image, alone or in a group, is refused with "trace it first +with Object › Image Trace › Make", and nothing changes. `threeD.extrude`: `depth` (points, 0..2000, default 50), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true solid, false hollow), `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, `ogee`), `bevelWidth` @@ -3427,6 +3452,8 @@ holds symbol instances that `object` expands, whether only their art holds it, w mesh points as the gradient paints them, with the colors Object › Expand gives them. `object.expand`, `effect.expandAppearance`, `type.createOutlines` and `object.path.outlineStroke` turn a dimension whose art they change into a plain group of that art, in the same undo step (see [dimensions.md](dimensions.md)). +`object.expand` rejects a param of the wrong type, such as `"fill": "yes"`, `"gradient": 3` or `"steps": "16"`, and +changes nothing. Omitting a param or giving null keeps its default. ```json {"name":"run_command","arguments":{"command":"object.expand","params":{"stroke":false,"gradient":"mesh"}}} @@ -3664,6 +3691,11 @@ dialog `simplifySlider` with field `level`) at the Auto-Simplify level for the s opens the Simplify dialog at the slider's tolerance. When OK confirms the dialog with `retain` ticked, the menu item opens the dialog on those settings next time. +`object.path.simplify`, `object.path.offsetPath`, `object.path.splitIntoGrid`, `object.path.cleanUp`, +`object.pathfinder.trap` and `addon.contour.set` reject a param of the wrong type, such as `"offset": true`, +`"joins": 3`, `"rows": "many"` or `"addGuides": "yes"`, and change nothing. A distance still takes a string with a unit +(`"5 mm"`). `joins` must be `miter`, `round` or `bevel`. Omitting a param or giving null keeps its default. + ## Smooth `object.path.smooth` smooths the selected paths (or the objects in `ids`), compound path members included, as one undo @@ -6964,7 +6996,13 @@ fit makes `plugin.run` return a memory-budget error naming the object and its si memory-budget error `the selection is too large to hand over`, and more than 100,000 of these objects make it return an object-budget error. Its output returns each of them as `{"id": …}` or exactly as given, otherwise `plugin.run` returns an error naming the object and the -field, and the document and undo history are unchanged. A live-effect plug-in is an effect with +field, and the document and undo history are unchanged. A filter at plug-in API level 2 whose manifest lists the +`commands` permission and a `commandAllowlist` (both in its `plugin.list` entry) runs the commands that list names +while it runs, through `vc_call`: the calls and its output are one undo step, and a run that fails or makes a call that +fails leaves the documents, selections and history as they were. Without `doc.read` every call fails. A command that +reads or writes files, uses the clipboard, changes preferences or the view, runs a script, an action or a plug-in, +switches documents or undoes is never called; `plugin.install` refuses a manifest that lists one, and `plugin.inspect` lists such ids as +`refusedCommands` and ids no command has as `unknownCommands` (`plugin.install` lists those too). A live-effect plug-in is an effect with id `plugin.`: `effect.apply`, `effect.setParams` and `effect.expandAppearance` work as for built-in effects, and `effect.list` lists it. One whose manifest declares `paintOutput` (at plug-in API level 2; `plugin.list` gives `api` and `paintOutput: true`) draws the pieces it returns with paints of their own, and `effect.expandAppearance` writes them diff --git a/docs/plugins.md b/docs/plugins.md index 890183c7fb..026dcc0d9a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -27,11 +27,11 @@ This page is the contract for plug-in authors and the reference for the host (`c | Command | Params | What it does | |---|---|---| -| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | +| `plugin.list` | `{}` | `{"plugins": [{id, name, version, kind, author, description, params, paramsSchema, effect?, format?, extensions?, budget?, commands?, commandAllowlist?, size, source, api, paintOutput?, permissions, hash, cacheBytes}], "folder": report}` (`api` is the manifest's [plug-in API level](#permissions); `budget: "heavy"` for a [heavy filter](#heavy-filters); `commands` lists its [commands](#commands); `commandAllowlist` lists the commands it may [call](#command-calls); `paintOutput: true` marks a [painted live effect](#painted-live-effects); `permissions` lists what it [may do](#permissions), `hash` is the module's SHA-256; `cacheBytes` is the size of its [cache](#settings-and-cache)) | | `plugin.info` | `{"id"}` | One plug-in: the `plugin.list` entry plus `manifest`, `defaults` and `lastError` (a live effect's last failure). | | `plugin.run` | `{"id", "params"?: {…}, "ids"?: [...]}` (plug-in params may also be top-level keys) | Runs an object filter on the selection (or `ids`; an `ids` that is not a list of object ids is an error). One undo step; the result is selected, except the objects it locked or made guides. | -| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. | -| `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval) and `needsReplace` (true when `plugin.install` needs `replace: true`). | +| `plugin.install` | `{"path": "/x/y.wasm"}` (desktop) or `{"dataBase64": "…", "name"?}`, `"replace"?: bool`, `"allowHeavy": bool = false`, `"grant"?: [permission]`, `"hash"?: "sha256 hex"` | Validates and installs a module; returns its `plugin.list` entry. The desktop app and `vectorcraft-cli` keep it in the `Plug-ins` folder next to the preferences, so it is installed again after a restart (#2541). A module with other bytes than the plug-in installed with its id, or, with none installed, one whose id has [settings and a cache](#settings-and-cache) in the `Plug-ins` folder, installs only with `replace: true`, once the user agreed; it takes that plug-in's place and gets its settings and cache. The same module installs again without `replace`, and `replace: false` refuses a module whose id is installed. A [heavy filter](#heavy-filters) installs only with `allowHeavy: true`. A plug-in whose manifest lists [permissions](#permissions) installs only when `grant` lists every one of them, unless a grant is already recorded for a module with the same SHA-256. A request's `grant` and `allowHeavy` are refused except in a session started with `vectorcraft-cli --allow-plugin-grants`. With `hash`, a module whose SHA-256 differs is refused. A module whose `commandAllowlist` lists a command no plug-in may call is refused; ids no command has are listed as `unknownCommands` ([command calls](#command-calls)). | +| `plugin.inspect` | as `plugin.install`: `{"path"}` or `{"dataBase64", "name"?}` | Validates a module without installing it; returns the `plugin.list` entry it would have, plus `needsApproval` (true when installing it needs a person's approval), `needsReplace` (true when `plugin.install` needs `replace: true`), and the `commandAllowlist` ids no command has (`unknownCommands`) and those no plug-in may call (`refusedCommands`). | | `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; a bad module is reported and skipped, and so are a heavy filter and a plug-in whose permissions the user hasn't granted (nobody was asked). | @@ -178,6 +178,7 @@ capability model proposed for PhotoCraft plug-ins | `progress` | all | Show its progress, see Cancel and write log lines through the [host imports](#host-imports-api-level-2). Needs `api` 2. | | `settings` | all | Keep settings of its own between runs and sessions ([settings and cache](#settings-and-cache)). Needs `api` 2. | | `cache` | all | Keep a cache of its own, which the user can clear ([settings and cache](#settings-and-cache)). Needs `api` 2. | +| `commands` | filter | Run the commands its `commandAllowlist` lists on the document ([command calls](#command-calls)). Needs `api` 2. | - 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` @@ -186,9 +187,10 @@ capability model proposed for PhotoCraft plug-ins 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 - `state`, which only its commands use. A filter may list any of its three. + `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` or `cache` with an `api` below 2, or + name that doesn't apply to the kind, more than 16 names, `progress`, `settings`, `cache` or `commands` with an `api` + below 2, or one of the names kept for a later plug-in API (`ui.panel`, `ui.tool`) is refused when the module is installed, and the error names it. - **Installing asks first.** Install Plug-in… and File › Open show the plug-in's name, id, version, the SHA-256 of @@ -308,7 +310,8 @@ module's memory. A plug-in whose manifest gives `"api": 2` and lists the [permission](#permissions) an import needs may import these functions from module `env` (the module a Rust or C toolchain gives `extern` functions by default). `vc_abi_version` still returns `1`. `vc_progress`, `vc_cancelled` and `vc_log` need `progress`; the `vc_settings_*` imports need -`settings` and the `vc_cache_*` imports need `cache` ([settings and cache](#settings-and-cache)). +`settings` and the `vc_cache_*` imports need `cache` ([settings and cache](#settings-and-cache)); `vc_call` and +`vc_call_result` need `commands` ([command calls](#command-calls)). | Import | Signature | Meaning | |---|---|---| @@ -389,6 +392,51 @@ A live effect runs while the art draws, so keep the entries it uses small. `plugin.info` give the cache's size as `cacheBytes`. - Without a `Plug-ins` folder (the web build, and embedders that attach none) the storage calls return `-5`. +### Command calls + +A filter whose manifest lists the `commands` permission and names commands in `commandAllowlist` runs those commands +on the document while it runs (#2186). It names each command by its id, as `command_list` lists it, and passes its +arguments as a JSON object, the params the command takes from any request: + +| Import | Signature | Meaning | +|---|---|---| +| `vc_call` | `(id, id_len, args, args_len) -> i32` | Runs the command whose UTF-8 id is at `id` with the JSON object at `args` (`args_len` 0 means `{}`). Returns `0` when it ran, else a negative code. | +| `vc_call_result` | `(out, out_cap) -> i32` | The JSON result of the last call that ran: its length in bytes. When it fits in the `out_cap` bytes at `out`, its bytes are copied there; otherwise nothing is copied. `-10` when no call has a result, `-1` when the buffer doesn't lie inside the module's memory. | + +`vc_call` returns `-1` when the id or the arguments don't lie inside the module's memory, `-2` when they are not UTF-8, +`-3` when the arguments are not a JSON object, `-4` when `commandAllowlist` doesn't list the id, `-5` when no command +has the id, `-6` when a plug-in may not call the command, `-7` when the command can't run now (nothing is selected), +`-8` when the command ran and failed, `-9` when a limit below is passed, and `-11` when nothing can be called (from +the module's start function, in a run that isn't a filter's run on a document, or after a call in the run failed). + +- Every code also fails the run, whatever the plug-in does next, and the error names the call and why it failed. The run's calls and its output are one undo step, named after the plug-in or its command. A run that fails, + traps, runs out of budget or is canceled leaves every document, its selection and its history as they were. +- Each call runs on the document the run is for, with its params checked as any request's are, and sees what the calls + before it changed: a `select.all` followed by `object.move` moves everything. The filter's own input is the one it + was given when the run started; an edit still in progress (typing, or a shape being drawn) is kept as its own undo + step before that input is made. +- A plug-in never calls a command that reads or writes a file or folder, uses the clipboard, changes preferences or + the view, runs a script, an action or a plug-in (a `plugin.*` command, or arguments naming one, such as an + `effect.apply` of `plugin.`), opens, closes or switches documents, or undoes or redoes, whatever its manifest + lists. The same goes for a command that changes a tool's options, keeps a drag's state or adds font names for the + whole app, and for a command VectorCraft adds later until it has been checked for plug-in calls. Installing a + manifest that lists such a command is refused, and the error names it; `plugin.inspect` lists them as + `refusedCommands`. +- A call whose arguments hold a file or folder key (`path`, `paths`, `file`, `files`, `folder`, `folders`, `dir`, + `directory`, `destinationFolder`, `sourceFolder` or `url`) at any depth, such as an effect's `textureImage.path`, + returns `-6`; only a key that names part of the document in that command, as its own param, is let through. A + command a plug-in calls can't read or write any file or folder. +- An id in `commandAllowlist` that no command has installs, so a plug-in can list a command a later version adds; + `plugin.install` and `plugin.inspect` list such ids as `unknownCommands`, and calling one returns `-5` (`-6` without + `doc.read`). +- Without `doc.read`, every call of a listed id fails with `-6`, since a command's result describes the document. + Without `doc.write`, a call that changes the document fails with `-6`. +- These limits are VectorCraft's own values: at most 1,000 calls a run, 8 MiB of arguments or result a call and 64 MiB + of arguments and results a run. Each call costs 10,000 instructions of the run's budget, plus one for every 64 bytes + of its arguments and its result, and the run checks Cancel and its time budget before and after each call. +- A filter that calls commands runs on the app's main thread, so it can't ask for a heavy budget: a manifest with + `commandAllowlist` and `budget: "heavy"` is refused. + ### Manifest ```json @@ -437,6 +485,10 @@ A live effect runs while the art draws, so keep the entries it uses small. `a-z 0-9 _` that starts with a letter, and appears once. A `label` is 1–64 printable characters; menus show it with control and bidirectional characters escaped. `params` are declared as the plug-in's own `params` are. A malformed entry is refused when the module is installed, and the error names the command by its id (or its place, `[0]`). +- `commandAllowlist` (filters at `api` 2 with the usual budget, and only with the `commands` permission, which needs + it): the ids of the commands the filter may [call](#command-calls), at most 256, each once (`"commandAllowlist": + ["select.all", "object.move"]`). An id is 1–128 characters from `A-Z a-z 0-9 . _ -` that starts with a letter, with + no empty part between dots. A malformed list is refused when the module is installed, and the error names the id. - `params`: in dialog order. Names are `[A-Za-z0-9_]`, not starting with `_`, and not `id`, `ids`, `params` or `preview`. The host validates the user's values before calling: missing values take the default, numbers are clamped to `min..max` (ints rounded), a wrong type or an unknown choice is an error. Numeric defaults diff --git a/docs/revolve.md b/docs/revolve.md index 6ecd4957eb..18be779d23 100644 --- a/docs/revolve.md +++ b/docs/revolve.md @@ -2,7 +2,7 @@ This initial implementation follows the scope agreed in [issue #605](https://github.com/storytold/vectorcraft/issues/605#issuecomment-6070543567). -Select a path, compound path, type, or a group or layer of them, then choose **Effect > 3D and Materials > Revolve**. +Select a path, compound path, type, clipping group, blend, symbol instance, or a group or layer of them, then choose **Effect > 3D and Materials > Revolve**. On a group or layer, every visible member sweeps about one axis, as [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html) describes for a group. The following rules are VectorCraft's own: type stays editable and sweeps as its glyph outlines, the shared axis lies on the chosen edge of the members' bounds together, and each member keeps its own paint. @@ -96,7 +96,7 @@ with the standard command. - Lighting offers Standard, Diffuse, Top Left and Right, using the [shared original rigs](three-d.md#presets). Other effective settings show Custom; changing the view does not change the recognized lighting preset. -- Paths, compound paths, type, and groups or layers of them only. Images and other objects must be converted to paths first. +- Paths, compound paths, type, clipping groups, blends, symbol instances, and groups or layers of them. A clipping group, a blend or a symbol instance sweeps the art it shows about one axis, as described in [three-d.md](three-d.md#clipping-groups-blends-and-symbol-instances). Images must be traced first with Object › Image Trace › Make, and other live objects expanded. - Open profiles have circular end caps by default; turning Cap off keeps them open. Partial-sweep angular cut sides remain open. Closed profile boundaries are swept as provided. - One Revolve per source object. Edit its options rather than applying another. - Object-level Revolve uses the top visible fill, falling back to a stroke. Per-item Revolve uses that item's paint. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 4a4b917ffd..6bf45e9c82 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -558,6 +558,7 @@ since 2026-10-01. - 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo. - Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab. +- 3D effects on clipping groups, blends and symbol instances (#6140, #5725): every 3D type builds from the art the object shows (the art inside the clipping path, the blend's keys and steps, the symbol's art where the instance places it), alone or in a group, on the canvas, in exports, Object › Rasterize and `assets.add3D`; an image is refused with a pointer to Object › Image Trace › Make. `crates/effects/src/solids/tests_sources.rs`, `crates/engine/src/cmd/effectcmd/three_d_source_tests.rs` and `fx::tests::a_symbol_instance_a_blend_and_a_clipping_group_draw_their_solids` cover it. Scores and estimates unchanged. - **Status-bar pointer readout (2026-10-18):** uses the same effective ruler origin as the position fields, then formats the relative X/Y in General units. The absolute pointer position, document, selection, Undo/Redo and saved state are preserved. Three `chrome::tests::status_coordinates_*` painted-text regressions cover zero/positive/negative origins, unit conversion, global/artboard mode, active artboard, reset and missing pointer/document. Original headless status-bar captures were reviewed before and after the change. Scores and hours are unchanged. @@ -1410,7 +1411,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Convert to Shape on a whole path or type object opens as a live Rectangle, Rounded Rectangle or Ellipse effect with its Absolute or Relative size, its corner radius, its place among the object's effects and whether it is hidden. A relative size in the file is added to each side. A relative Ellipse, or a setting VectorCraft doesn't read, keeps the drawn art (`crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). In a `.ai` opened from its editing data, Bas Relief in an art style takes its Detail, Smoothness and Light direction from the style's settings block, and an object other than type with it opens as itself with the live effect. A settings block that VectorCraft can't read (malformed, another effect's, a value out of range or a key it doesn't know) keeps the object's drawn look (part of #637; [raster effects reference](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/raster-effects-reference.html), [Photoshop File Formats Specification](https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/), [scripting the filter gallery](https://community.adobe.com/questions-712/scripting-support-for-the-filter-gallery-1064646); `crates/eps/src/import/ai/style/tests.rs`, `crates/eps/src/import/ai/tests.rs`). - PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); in PDF 1.3 to 1.5 files and PDF/X files such a page is written in points. + PDF export and `.ai` saves write a page with a side longer than 14,400 pt with a `UserUnit` (PDF 1.6), its longer side divided by 14,400 and rounded up to the next thousandth, so that no side is longer than 14,400 units (ISO 32000-1, Annex C.2); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392). @@ -1627,6 +1628,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged. - **A plug-in with no permissions ends its id's grant (G17):** installing a module that lists no permissions under a granted id forgets the grant, in the process and in `grants.json`, so the formerly approved bytes need a new approval. Attaching a `Plug-ins` folder whose module for that id lists no permissions forgets it too, and plug-in folders forget the process's grant. A refused install leaves the grant. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_safe_mode.rs`. Scores and hours unchanged. - **Plug-in commands (G17):** a filter or live effect may declare up to 32 `commands` (`{id, label, params?}`); each is the command `plugin..` while the plug-in is installed, in a submenu named after the plug-in under Object › Plug-ins (Effect › Plug-ins for a live effect) whatever menu the manifest names, with its label escaped. Commands are recorded in actions, listed in Keyboard Shortcuts for the user to give a shortcut, and run through `run` and MCP with their parameters checked first (a command with parameters opens a dialog from its menu item or shortcut). A run uses the plug-in's permissions (a live effect with commands may also hold `doc.write` and `state`, and gets them without a `permissions` list), is one undo step named after the command, and on failure (a trap or an exhausted instruction budget) leaves the document and the undo history as they were with an error naming the plug-in and the command. For a command and for `plugin.run`, an `ids` that is not a list of object ids is an error rather than the selection. A malformed entry is refused by name when the module is installed. Regressions: `crates/plugins/src/manifest.rs`, `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. +- **Filter plug-ins call commands (G17, #2186):** a filter at plug-in API level 2 with the `commands` permission names the commands it may run in its manifest's `commandAllowlist` and runs them with `env.vc_call`, reading each result with `env.vc_call_result`. Each call sees what the calls before it changed; the calls and the filter's output are one undo step, and a run that fails, is canceled or makes a call that fails leaves every document, its selection and its history as they were. Commands that read or write files, use the clipboard, change preferences or the view, run scripts, actions or plug-ins, switch documents or undo are never called, and a manifest that lists one is refused when the module is installed. The install dialog lists the allowed commands. A run makes at most 1,000 calls, and each call costs 10,000 instructions of its budget. Regressions: `crates/plugins/tests/call.rs`, `crates/engine/tests/plugin_call.rs`, `crates/engine/src/cmd/plugin_call.rs`. Scores and hours unchanged. - **Plug-in progress, Cancel and log lines (G17):** at plug-in API level 2 a plug-in with the `progress` permission imports `env.vc_progress`, `env.vc_cancelled` and `env.vc_log`. A heavy filter's and an export's progress windows show its progress as a percentage bar, their Cancel reaches it through `vc_cancelled`, and its log lines go to the app's log with its id, capped per line and per run. Installing checks every import and names the one it refuses. Regressions: `crates/plugins/src/host.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. - **Live-effect plug-ins paint their output (G17, #121):** a live effect whose manifest has `"api": 2` and `"paintOutput": true` returns pieces, each drawn by itself in order with fills and strokes of its own in the filter's paint forms (a piece without them keeps the object's; an empty list paints none; an effect on a fill returns only fills, one on a stroke only strokes). The whole result is checked first: limits, numbers in range with nothing clamped, known keys only, and the swatches and patterns it names in the document; one fault draws that step of the stack unchanged, keeps the effect record and puts the plug-in's name and the field in `plugin.info`'s `lastError`. The pieces are drawn, measured and exported to PDF and SVG from the appearance stack without changing the document, and Expand Appearance writes them as ordinary paths in one undo step. Effects without the key behave as before. Regressions: `crates/plugins/src/painted/tests.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. - **Plug-in settings and cache (G17, #2191):** at plug-in API level 2 a plug-in with the `settings` permission keeps settings of its own (`env.vc_settings_get`, `_set`, `_delete`) and one with `cache` a cache the user can clear (`env.vc_cache_read`, `_write`, `_clear`), under its id in the `Plug-ins` folder. Keys are plain names, never paths; VectorCraft's own caps refuse a write past 256 settings, 1 MiB of settings or 512 MiB of cache; a damaged settings file is moved aside and the settings start empty. `plugin.clearCache` empties a cache, `plugin.list` and `plugin.info` give `cacheBytes`, replacing a plug-in keeps its storage and `plugin.remove` deletes it. Another module under an id that is installed or has storage installs only with `replace: true`, which the app asks the user for; each storage call counts the whole settings file or cache entry it reads and writes toward the run's 1 GiB. Regressions: `crates/plugins/src/storage.rs`, `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_clear_cache.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged. diff --git a/docs/three-d.md b/docs/three-d.md index e541a078af..0a9ac897d5 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -4,7 +4,8 @@ The other three 3D types of **Effect › 3D and Materials** next to [Revolve](re live effect: the source path stays editable, the effect draws shaded vector faces, and SVG/PDF export, native saves and **Object › Expand Appearance** use the same evaluator. -Select a path or compound path, then choose **Effect › 3D and Materials › Extrude & Bevel…**, **Inflate…** or +Select a path, compound path, type, clipping group, blend, symbol instance, or a group or layer of them, then choose +**Effect › 3D and Materials › Extrude & Bevel…**, **Inflate…** or **Rotate…**. The options dialog opens beside the artboard with tabs: - **Object** (Extrude & Bevel and Inflate): the shape's own options, below. @@ -118,13 +119,43 @@ it, at any depth of its groups, each from its own fills and strokes as above ([F and they turn, twist and taper together about the center of their bounds together; with Perspective one eye sees them all. The members stay editable: moving or editing one reshapes the solids. Our reading: -- Each member's own geometry effects shape it first; the group's geometry effects before the 3D effect reshape the +- Each member's own geometry effects shape it first, then those of each group inside the 3D group that holds it, + applied to that group's members together; the 3D group's geometry effects before the 3D effect reshape the members, and those after it bend the result as a whole. The members' other effects, and the group's own fills and strokes, are not drawn. A member's opacity applies to its solids; its blending mode does not. - When every solid is opaque, all members' faces are drawn in one back-to-front order; otherwise each solid is drawn on its own, the backmost member's first. -- Hidden members and guides are left out. A group holding an image, a symbol instance, a clipping group or another - live object is refused with a message saying what to release or expand; so is one with more than 4,096 shapes. +- Hidden members and guides are left out. A group holding a live object other than a blend (an envelope, a mesh, a + repeat) is refused with a message saying what to release or expand; so is one with more than 4,096 shapes. + +## Clipping groups, blends and symbol instances + +Every 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Inflate, Rotate and Revolve) also applies to a clipping +group, a blend or a symbol instance, alone or inside a group or layer. The help page says that effects apply to +objects, groups or layers ([Apply and modify effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)), +that a clipping mask hides everything outside its shape ([Clipping masks](https://helpx.adobe.com/illustrator/using/clipping-masks.html)), +and that a blend is treated as one object ([Blending objects](https://helpx.adobe.com/illustrator/using/blending-objects.html)). +How the solid is built from each is VectorCraft's own rule: it is built from what the object shows, as a group's +solids are ([Groups](#groups)), turned about one shared axis. + +- A clipping group (or a layer with a clipping mask) builds from its art inside the clipping path: each shape's fill + area cut to the clip, and each stroke's outline cut to the clip and filled in the stroke's paint. The clipping path + draws no solid. A clipping group inside another keeps what both clips show. A clip that shows none of the art + leaves nothing to build, and the effect is refused. +- A blend builds from its key objects and its steps, each in its own paint, in their order. +- A symbol instance builds from its symbol's art where the instance places it. Redefining the symbol reshapes the + solid. An instance of a symbol that is not in the document, a symbol that holds an instance of itself, or art + nested more than 64 levels deep is refused. +- Inside a 3D group, the geometry effects of a clipping group, a blend or a symbol instance reshape the art it shows, + as a group's do. Inside a clipping group, a group's geometry effects reshape its members before the clip cuts them. +- Art whose symbol instances, blends and clipping groups take more than 262,144 objects to go through (counting + hidden objects, and a symbol's art once for each instance that shows it) is refused. +- The objects stay live: editing the clipping path, the blend's keys or the symbol reshapes the solid. +- An image is refused, alone or in a group: trace it first with Object › Image Trace › Make. The help page routes + images to 3D through Image Trace ([Create 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-vector-artwork.html)). + A hidden image in a group is left out like any hidden member, and so is an image in a clipping group whose bounds + lie wholly outside the clipping path's bounds, when the image has no visible fills or strokes of its own and + neither the image nor a group holding it inside the clipping group has effects. ## Rotate @@ -232,9 +263,10 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. drawn in pieces about as long as a wall slice is wide (fewer near the limit of 32,768 facets). The piece drawn on top can still lie a few points behind another nearby piece. - Extrude & Bevel and Rotate retain planar shading. Colored Inflate uses smooth vector lighting; white-light Inflate keeps its original polygon shading; bounded cell triangulation leaves a cell flat when it contains a complete hole or an unusually complex/degenerate contour. Its geometric silhouette is still a polygon approximation. -- Paths, compound paths, type and groups or layers of them (see [Groups](#groups)); images, symbol instances, - clipping groups and other live objects have to be converted first. Revolve on a group sweeps its members about - one axis ([revolve.md](revolve.md)). One 3D effect per object. +- Paths, compound paths, type, clipping groups, blends, symbol instances and groups or layers of them (see + [Groups](#groups) and [Clipping groups, blends and symbol instances](#clipping-groups-blends-and-symbol-instances)); + images have to be traced first, and other live objects expanded. Revolve on a group sweeps its members about one + axis ([revolve.md](revolve.md)). One 3D effect per object. - Curves are followed within 1/2000 of the shape's size (at least 0.05 pt), so a small curve takes a few points and a large one up to 32. Extrude & Bevel and Inflate take up to 65,536 outline points and 163,840 faces for each solid (a stroke's outline is counted on its own), and Rotate (which only turns the outline) takes 65,536 points.