From d56e241a43e76d501575ebce626b691a426fd3a4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:30:45 -0800 Subject: [PATCH 01/33] 3D and Materials: Expand as Wireframes turns a 3D object into its edges as paths Window > 3D and Materials > Quick Actions > Expand as Wireframes, and the command effect.expandAsWireframes, replace each selected object that has a visible 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Revolve, Inflate or Rotate) with a group of paths: the edges of the faces the effect draws for the object as it is turned and projected now. - Each edge appears once. Edges that meet end to end form one path, closed where it comes back to its start, and curved edges stay curves. Geometry effects after the 3D effect reshape the edges as they reshape the drawn surface. - The paths have a 0.5 pt black stroke with round joins and no fill. The group keeps the object's id, name, transparency, attributes, slice and text wrap, and is selected. A layer stays a layer holding the edges. - It is one undo step. Nothing selected, no visible 3D effect, a solid that can't be built or is drawn as its source art, or more than 1,000,000 edges in one object is an error, and the document does not change. Docs: docs/mcp.md, docs/three-d.md, docs/effects-parity.md, docs/target-app-parity.md. Fixes #6354 --- crates/effects/src/lib.rs | 4 +- crates/effects/src/revolve.rs | 49 ++++ crates/effects/src/solids.rs | 3 + crates/effects/src/solids/wireframe.rs | 262 +++++++++++++++++++ crates/effects/src/solids/wireframe/tests.rs | 156 +++++++++++ crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/wireframe.rs | 118 +++++++++ crates/engine/src/cmd/wireframe/tests.rs | 143 ++++++++++ crates/ui-egui/src/panels/tests_three_d.rs | 26 ++ crates/ui-egui/src/panels/three_d.rs | 29 +- docs/effects-parity.md | 2 +- docs/mcp.md | 22 ++ docs/target-app-parity.md | 1 + docs/three-d.md | 13 + 14 files changed, 826 insertions(+), 4 deletions(-) create mode 100644 crates/effects/src/solids/wireframe.rs create mode 100644 crates/effects/src/solids/wireframe/tests.rs create mode 100644 crates/engine/src/cmd/wireframe.rs create mode 100644 crates/engine/src/cmd/wireframe/tests.rs diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 67b4b464fd..1a838fb28f 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -87,8 +87,8 @@ pub use revolve::{REVOLVE, has_revolve, revolve_art, revolve_art_in, revolve_opt 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, 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, + three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, 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 4795e8848a..31377318cc 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -455,6 +455,55 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul Ok(out) } +/// The outline of every face [`revolve_art`] draws for `n` (its symbol instances, blends and clipping +/// groups already resolved), in document coordinates: with the effect on the object, the surface in +/// its top visible fill (else its stroke); with it on fills and strokes, one surface for each of +/// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for +/// each member, about one shared axis. +pub(crate) fn revolve_face_paths(n: &Node) -> Result, String> { + let faces = |path: &PathData, b: Rect, options: Revolve| -> Result, String> { + Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect()) + }; + if is_container(n) { + let index = + n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE).ok_or("a 3D effect on a group's fill or stroke draws nothing")?; + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let mut shapes = members(n, "Revolve")?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; + let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let mut out = vec![]; + for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) { + out.extend(faces(&s.path, b, options)?); + } + return Ok(out); + } + let (path, _) = object_profile(n, "Revolve")?; + let ctx = GeomContext::of(n); + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { + let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; + let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); + if surface_item(&solid_paints(n)).is_none() { + return Err("the revolved object has no fill or stroke".into()); + } + let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + return faces(&path, b, revolve_options(&merged_params(REVOLVE, &fx.params))); + } + let path = geometry(&path, &n.appearance.effects, &ctx); + let mut out = vec![]; + for item in n.appearance.items.iter().filter(|i| crate::paints(i)) { + if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) + && let Some(fx) = item.effects().get(index) + { + let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); + let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?; + let surface = faces(&p, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &ctx)); + } + } + Ok(out) +} + /// [`revolve_meshes`] of group or layer `n`: one mesh for each member, about one shared axis. fn group_meshes(n: &Node, total: &mut usize, limit: usize) -> Result, String> { let index = n diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index ff5b1c9711..f9d3a68ac9 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -22,6 +22,9 @@ pub(crate) use source::{resolve, resolve_for}; pub(crate) mod shadow; +pub(crate) mod wireframe; +pub use wireframe::three_d_wireframe_in; + pub const EXTRUDE: &str = "threeD.extrude"; pub const INFLATE: &str = "threeD.inflate"; pub const ROTATE: &str = "threeD.rotate"; diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs new file mode 100644 index 0000000000..eb74546225 --- /dev/null +++ b/crates/effects/src/solids/wireframe.rs @@ -0,0 +1,262 @@ +//! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that +//! can be edited on their own. +use std::collections::{HashMap, HashSet, VecDeque}; + +use vectorcraft_doc::{AppearanceItem, Document, Effect, Node}; +use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; +use vectorcraft_three_d::Facet; + +use super::{ + INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_three_d, label_of, members, object_profile, region, + reshape_members, resolve, solid, solid_paints, solid_parts, union_bounds, view_options, +}; +use crate::{GeomContext, apply_geometry_with, is_geometry}; + +/// The most distinct edges one object's wireframe may have. +pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; + +/// The grid points are rounded to before edges are compared, in points: two faces that share an +/// edge give it once. +const GRID: f64 = 1.0 / 1024.0; + +const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)"; + +/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Revolve, Inflate +/// or Rotate), in document coordinates: the edges of every face the effect draws for the object as +/// it is turned and projected, each edge once. Edges that meet end to end are joined into one path; +/// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry +/// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a +/// group or layer, the edges of the solids of all its members. An error when `n` has no visible 3D +/// effect, when its solids can't be built, when the canvas draws the source art in their place, when +/// they draw no face, or past [`MAX_WIRE_EDGES`] edges. +pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result, String> { + if !crate::has_revolve(n) && !has_solid(n) { + return Err(NO_EFFECT.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)); + // The faces come from the effect whose art the canvas draws (Revolve first, as the canvas tries + // it first). When neither draws, past their limits, the canvas shows the source art and there + // is no surface to expand. + let revolve = crate::has_revolve(n) && crate::revolve_art_in(doc, n).is_some(); + if !revolve && !(has_solid(n) && super::solid_art_in(doc, n).is_some()) { + let n = &*resolve(doc, n, label)?; + // The builders' own error says why, when there is one. + if crate::has_revolve(n) { + crate::revolve::revolve_face_paths(n)?; + } else { + solid_face_paths(n)?; + } + return Err(format!("{label} draws the source art for this object instead of its 3D surface")); + } + let n = &*resolve(doc, n, label)?; + let faces = if revolve { crate::revolve::revolve_face_paths(n)? } else { solid_face_paths(n)? }; + let faces = after_geometry(n, faces); + let wire = edges(&faces)?; + if wire.is_empty() { + return Err(format!("{label} draws no faces for this object")); + } + Ok(wire) +} + +/// `faces` reshaped by the visible geometry effects after `n`'s own 3D effect, which act on the +/// projected art as a whole, about the bounds of all the faces. +fn after_geometry(n: &Node, faces: Vec) -> Vec { + let fx = &n.appearance.effects; + let Some(index) = fx.iter().position(|e| e.visible && is_three_d(&e.id)) else { return faces }; + reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext::of(n)) +} + +/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), +/// which act on the faces as a whole, about their bounds, as they act on the drawn surface. +pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { + let after: Vec = later.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect(); + if after.is_empty() { + return faces; + } + let joined = PathData::new(faces.into_iter().flat_map(|f| f.subpaths).collect()); + let Some(bounds) = joined.bounds() else { return vec![joined] }; + vec![apply_geometry_with(&after, &joined, bounds, ctx)] +} + +/// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect +/// on the object, its solids; with it on fills and strokes, the solid of each; on a group or layer, +/// the solids of its members, about one shared axis. +fn solid_face_paths(n: &Node) -> Result, String> { + if is_container(n) { + let (index, fx) = solid(&n.appearance.effects).ok_or("a 3D effect on a group's fill or stroke draws nothing")?; + let mut shapes = members(n, label_of(&fx.id))?; + reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); + return facet_paths(fx, &shapes); + } + 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 (path, rule) = object_profile(n, label)?; + let ctx = GeomContext::of(n); + let paints = solid_paints(n); + if let Some((index, fx)) = solid(&n.appearance.effects) { + let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); + return facet_paths(fx, &[Profile { path, rule, items: paints, opacity: 1.0, scopes: vec![] }]); + } + let path = geometry(&path, &n.appearance.effects, &ctx); + let mut out = vec![]; + for item in &paints { + if let Some((index, fx)) = solid(item.effects()) { + let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); + let faces = facet_paths(fx, &[Profile { path: p, rule, items: vec![item.clone()], opacity: 1.0, scopes: vec![] }])?; + out.extend(reshaped(faces, item.effects().get(index + 1..).unwrap_or_default(), &ctx)); + } + } + Ok(out) +} + +/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: +/// Rotate turns every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's +/// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, +/// as it is left out of the drawn art. +fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { + let label = label_of(&fx.id); + let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; + let p = crate::merged_params(&fx.id, &fx.params); + let mut out = vec![]; + if fx.id == ROTATE { + for s in shapes { + for item in &s.items { + let (area, rule) = region(&s.path, s.rule, item); + out.extend(facets(ROTATE, &area, rule, b, &p)?.iter().map(Facet::path)); + } + } + return Ok(out); + } + let (parts, bounds) = solid_parts(shapes, b); + let built: Vec, String>> = if fx.id == INFLATE { + let shapes: Vec<(&PathData, vectorcraft_geom::FillRule)> = parts.iter().map(|(_, _, area, rule, ..)| (area, *rule)).collect(); + vectorcraft_three_d::inflate_together(&shapes, bounds, inflate_options(&p), view_options(&p)) + } else { + parts.iter().map(|(_, _, area, rule, ..)| facets(&fx.id, area, *rule, bounds, &p)).collect() + }; + for ((item, ..), f) in parts.iter().zip(built) { + match f { + Ok(f) => out.extend(f.iter().map(Facet::path)), + Err(_) if matches!(item, AppearanceItem::Stroke(_)) => {} + Err(e) => return Err(e), + } + } + Ok(out) +} + +/// A point on the [`GRID`]. +type Snap = (i64, i64); + +fn snap(p: Point) -> Snap { + ((p.x / GRID).round() as i64, (p.y / GRID).round() as i64) +} + +fn reversed(c: CubicBez) -> CubicBez { + CubicBez::new(c.p3, c.p2, c.p1, c.p0) +} + +/// The edges of `faces`, each once, joined end to end into paths ([`three_d_wireframe_in`]). +pub(crate) fn edges(faces: &[PathData]) -> Result, String> { + let mut seen: HashSet<[Snap; 4]> = HashSet::new(); + let mut segments: Vec = vec![]; + for sp in faces.iter().flat_map(|f| &f.subpaths) { + for i in 0..sp.segment_count() { + let mut c = sp.segment(i); + if sp.segment_is_line(i) { + c = CubicBez::new(c.p0, c.p0, c.p3, c.p3); + } + if [c.p0, c.p1, c.p2, c.p3].iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { + continue; + } + let key = [c.p0, c.p1, c.p2, c.p3].map(snap); + // A segment that starts and ends on one grid point with its handles there too draws nothing. + if key.iter().all(|k| *k == key[0]) { + continue; + } + let back = [key[3], key[2], key[1], key[0]]; + if seen.contains(&back) || !seen.insert(key) { + continue; + } + if segments.len() >= MAX_WIRE_EDGES { + return Err(format!("the wireframe has more than {MAX_WIRE_EDGES} edges")); + } + segments.push(c); + } + } + Ok(chain(&segments)) +} + +/// `segments` joined end to end: each path starts at the first segment not yet used and takes in +/// the unused segments that meet its ends until none is left at either end, or it closes. +fn chain(segments: &[CubicBez]) -> Vec { + let mut at: HashMap> = HashMap::new(); + for (i, c) in segments.iter().enumerate() { + at.entry(snap(c.p0)).or_default().push(i); + if snap(c.p3) != snap(c.p0) { + at.entry(snap(c.p3)).or_default().push(i); + } + } + let mut used = vec![false; segments.len()]; + // The next unused segment at `point`, turned to leave it (`leave`) or to arrive at it. + let mut take = |used: &mut Vec, point: Snap, leave: bool| -> Option { + let list = at.get_mut(&point)?; + while let Some(&i) = list.last() { + if used.get(i).copied().unwrap_or(true) { + list.pop(); + continue; + } + if let Some(u) = used.get_mut(i) { + *u = true; + } + let c = *segments.get(i)?; + let starts = snap(c.p0) == point; + return Some(if starts == leave { c } else { reversed(c) }); + } + None + }; + let mut out = vec![]; + for (i, first) in segments.iter().enumerate() { + if used.get(i).copied().unwrap_or(true) { + continue; + } + if let Some(u) = used.get_mut(i) { + *u = true; + } + let mut run: VecDeque = VecDeque::from([*first]); + // A path of one anchor has no segment (`SubPath::segment_count`), so a run of one segment + // that comes back to its start stays open, with its two ends on one point. + let closes = |run: &VecDeque| run.len() > 1 && run.front().zip(run.back()).is_some_and(|(f, b)| snap(f.p0) == snap(b.p3)); + while !closes(&run) { + let Some(end) = run.back().map(|c| snap(c.p3)) else { break }; + let Some(c) = take(&mut used, end, true) else { break }; + run.push_back(c); + } + while !closes(&run) { + let Some(start) = run.front().map(|c| snap(c.p0)) else { break }; + let Some(c) = take(&mut used, start, false) else { break }; + run.push_front(c); + } + out.push(PathData::single(subpath(&run, closes(&run)))); + } + out +} + +/// `run`, segments that meet end to end, as one subpath; a closed one ends at its first anchor. +fn subpath(run: &VecDeque, closed: bool) -> SubPath { + let mut anchors: Vec = vec![]; + if let Some(first) = run.front() { + let h_in = if closed { run.back().map_or(first.p0, |b| b.p2) } else { first.p0 }; + anchors.push(Anchor::with_handles(first.p0, h_in, first.p1)); + } + for (k, c) in run.iter().enumerate() { + let h_out = run.get(k + 1).map_or(c.p3, |next| next.p1); + anchors.push(Anchor::with_handles(c.p3, c.p2, h_out)); + } + // A closed run's last anchor is its first, whose in handle already comes from the last segment. + if closed { + anchors.pop(); + } + SubPath::new(anchors, closed) +} + +#[cfg(test)] +mod tests; diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs new file mode 100644 index 0000000000..980e67bbeb --- /dev/null +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -0,0 +1,156 @@ +use serde_json::{Value, json}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Node, NodeId}; +use vectorcraft_geom::{BezPath, Rect}; + +use super::*; + +fn square(x: f64, y: f64, size: f64) -> PathData { + let mut b = BezPath::new(); + b.move_to((x, y)); + b.line_to((x + size, y)); + b.line_to((x + size, y + size)); + b.line_to((x, y + size)); + b.close_path(); + PathData::from_bezpath(&b) +} + +/// A filled 100 pt square without a stroke, with effect `id` and `params`. +fn solid_square(id: &str, params: Value) -> Node { + let mut n = Node::path(NodeId(1), square(100.0, 100.0, 100.0), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + n.appearance.effects.push(crate::new_effect(id, ¶ms).unwrap()); + n +} + +/// Every segment of `wire`, each as its two ends on the grid. +fn segments(wire: &[PathData]) -> Vec<(Snap, Snap)> { + wire.iter() + .flat_map(|p| &p.subpaths) + .flat_map(|sp| (0..sp.segment_count()).map(move |i| sp.segment(i))) + .map(|c| (snap(c.p0), snap(c.p3))) + .collect() +} + +fn bounds(paths: &[PathData]) -> Rect { + paths.iter().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +/// The paths of the faces `art` draws (every leaf of the art). +fn face_paths(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |c| out.extend(c.path_data().cloned())); + out +} + +#[test] +fn two_faces_that_share_an_edge_give_it_once() { + let wire = edges(&[square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)]).unwrap(); + let segs = segments(&wire); + assert_eq!(segs.len(), 7, "{segs:?}"); + for (i, a) in segs.iter().enumerate() { + for b in segs.iter().skip(i + 1) { + assert!(a != b && (a.1, a.0) != *b, "{a:?} twice"); + } + } +} + +#[test] +fn a_loop_of_edges_is_one_closed_path_and_a_curve_stays_a_curve() { + let wire = edges(&[square(0.0, 0.0, 10.0)]).unwrap(); + assert_eq!(wire.len(), 1); + assert!(wire[0].subpaths[0].closed); + assert_eq!(wire[0].subpaths[0].anchors.len(), 4); + + let mut b = BezPath::new(); + b.move_to((0.0, 0.0)); + b.curve_to((0.0, 10.0), (10.0, 10.0), (10.0, 0.0)); + b.close_path(); + let wire = edges(&[PathData::from_bezpath(&b)]).unwrap(); + let curved = wire.iter().flat_map(|p| &p.subpaths).any(|sp| (0..sp.segment_count()).any(|i| !sp.segment_is_line(i))); + assert!(curved, "{wire:?}"); +} + +/// A single curve that comes back to its start keeps its segment: it stays open, with two anchors on +/// one point, since a path of one anchor has no segment. +#[test] +fn a_single_curve_that_comes_back_to_its_start_keeps_its_segment() { + let p = Point::new(0.0, 0.0); + let anchors = vec![Anchor::with_handles(p, p, Point::new(0.0, 10.0)), Anchor::with_handles(p, Point::new(10.0, 10.0), p)]; + let face = PathData::single(SubPath::new(anchors, false)); + assert_eq!(face.subpaths[0].segment_count(), 1); + let wire = edges(&[face]).unwrap(); + assert_eq!(wire.len(), 1); + let sp = &wire[0].subpaths[0]; + assert_eq!(sp.segment_count(), 1, "{sp:?}"); + assert!(!sp.segment_is_line(0)); +} + +#[test] +fn edges_without_length_or_with_non_finite_points_are_left_out() { + let point = PathData::single(SubPath::polyline(&[Point::new(5.0, 5.0), Point::new(5.0, 5.0)], false)); + let bad = PathData::single(SubPath::polyline(&[Point::new(f64::NAN, 0.0), Point::new(1.0, 1.0)], false)); + assert!(edges(&[point, bad]).unwrap().is_empty()); + assert!(edges(&[]).unwrap().is_empty()); +} + +#[test] +fn a_box_turned_off_axis_shows_the_nine_edges_of_its_three_faces() { + let n = solid_square(super::super::EXTRUDE, json!({})); + let wire = three_d_wireframe_in(None, &n).unwrap(); + assert_eq!(segments(&wire).len(), 9, "{wire:?}"); + // The wireframe covers what the effect draws, in the same place. + let art = super::super::solid_art(&n).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&art))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{w:?} {a:?}"); + } +} + +#[test] +fn the_classic_wireframe_surface_expands_to_all_twelve_edges() { + let n = solid_square(super::super::CLASSIC_EXTRUDE, json!({"surface": "wireframe"})); + assert_eq!(segments(&three_d_wireframe_in(None, &n).unwrap()).len(), 12); +} + +#[test] +fn revolve_inflate_and_rotate_expand_too() { + for id in [crate::REVOLVE, super::super::INFLATE, ROTATE] { + let wire = three_d_wireframe_in(None, &solid_square(id, json!({}))).unwrap_or_else(|e| panic!("{id}: {e}")); + assert!(!wire.is_empty(), "{id}"); + assert!(wire.iter().flat_map(|p| &p.subpaths).flat_map(|sp| &sp.anchors).all(|a| a.p.x.is_finite() && a.p.y.is_finite()), "{id}"); + } + // Rotate is one flat face: its outline. + let plane = three_d_wireframe_in(None, &solid_square(ROTATE, json!({}))).unwrap(); + assert_eq!(segments(&plane).len(), 4); +} + +/// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. +#[test] +fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { + for id in [super::super::EXTRUDE, crate::REVOLVE] { + let mut n = solid_square(id, json!({})); + let fx = n.appearance.effects.remove(0); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(fx.clone()); + } + } + let plain = bounds(&three_d_wireframe_in(None, &n).unwrap_or_else(|e| panic!("{id}: {e}"))); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap()); + } + } + let moved = bounds(&three_d_wireframe_in(None, &n).unwrap()); + assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{id}: {plain:?} {moved:?}"); + } +} + +#[test] +fn an_object_without_a_visible_3d_effect_is_an_error() { + let mut n = solid_square(super::super::EXTRUDE, json!({})); + n.appearance.effects[0].visible = false; + assert!(three_d_wireframe_in(None, &n).unwrap_err().contains("no 3D effect")); + n.appearance.effects.clear(); + assert!(three_d_wireframe_in(None, &n).is_err()); +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 72e33b8993..f773c8716d 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -105,6 +105,7 @@ mod variablecmds; pub(crate) mod views; pub mod wand; pub mod webexport; +mod wireframe; mod xform; use serde::Serialize; @@ -308,6 +309,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(draw2::specs()); v.extend(xform::specs()); v.extend(effectcmd::specs()); + v.extend(wireframe::specs()); v.extend(pathops::specs()); v.extend(compoundshape::specs()); v.extend(typecmd::specs()); diff --git a/crates/engine/src/cmd/wireframe.rs b/crates/engine/src/cmd/wireframe.rs new file mode 100644 index 0000000000..5e7dd3f0d4 --- /dev/null +++ b/crates/engine/src/cmd/wireframe.rs @@ -0,0 +1,118 @@ +//! Window › 3D and Materials › Quick Actions › Expand as Wireframes: each object with a 3D effect +//! becomes a group of stroked paths, the edges of the faces its effect draws. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{Appearance, LineJoin, Node, NodeId, NodeKind, StrokeLayer}; +use vectorcraft_render::effects; + +use super::{CommandSpec, Result, Session, bad, checked_ids_or_selection, cmd, has_doc}; + +const C: &str = "effect.expandAsWireframes"; + +/// The name of the undo step. +const LABEL: &str = "Expand as Wireframes"; + +/// The weight of a wireframe edge's stroke, in points (VectorCraft's own). +pub const WIRE_WEIGHT: f64 = 0.5; + +pub fn specs() -> Vec { + vec![cmd!( + "effect.expandAsWireframes", + "Expand as Wireframes", + [], + None, + "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Revolve, Inflate or Rotate, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", + has_doc, + expand_as_wireframes + )] +} + +/// A wireframe edge's appearance: a 0.5 pt black stroke with round joins and no fill. +fn wire_appearance() -> Appearance { + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), WIRE_WEIGHT); + stroke.join = LineJoin::Round; + Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() } +} + +fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result { + let roots = checked_ids_or_selection(s, p, C)?; + if roots.is_empty() { + return Err(bad(C, "select an object with a 3D effect, or give its id in ids")); + } + // Every wireframe is built before the edit, so a failure leaves the document and its history as + // they are. + let d = &s.doc()?.doc; + let mut wires = vec![]; + for id in roots { + let Some(n) = d.node(id) else { continue }; + if !effects::has_revolve(n) && !effects::has_solid(n) { + continue; + } + let wire = effects::three_d_wireframe_in(Some(d), n).map_err(|e| bad(C, format!("object {}: {e}", id.0)))?; + wires.push((id, wire)); + } + if wires.is_empty() { + return Err(bad(C, "no selected or given object has a visible 3D effect")); + } + let ids: Vec = s.edit(LABEL, |d, sel| { + let mut out = vec![]; + let mut selected = vec![]; + for (id, wire) in wires { + let Some(source) = d.node(id) else { continue }; + if matches!(source.kind, NodeKind::Layer { .. }) { + // A layer stays a layer: its members become the edges, and its 3D effect is removed. + let mut layer = source.clone(); + let children: Vec> = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); + selected.extend(children.iter().map(|c| c.id)); + if let Some(members) = layer.children_mut() { + *members = children; + } + layer.appearance = Default::default(); + if let Some(slot) = d.node_mut(id) { + *slot = layer; + out.push(id); + } + continue; + } + // The group keeps the object's name, visibility, lock, bounding box angle, transparency + // (opacity, blending mode, isolation, knockout and opacity mask), attributes, slice and text + // wrap. + let mut group = Node::group(id, vec![]); + group.name = source.name.clone(); + group.visible = source.visible; + group.locked = source.locked; + group.opacity = source.opacity; + group.blend = source.blend; + group.isolate = source.isolate; + group.knockout = source.knockout; + group.knockout_shape = source.knockout_shape; + group.bbox_angle = source.bbox_angle; + let extras = source.extras(); + let (mask, attrs, slice, wrap) = (extras.mask.clone(), extras.attrs.clone(), extras.slice.clone(), extras.wrap); + if mask.is_some() || attrs.is_some() || slice.is_some() || wrap.is_some() { + let mut e = group.extras_mut(); + e.mask = mask; + e.attrs = attrs; + e.slice = slice; + e.wrap = wrap; + } + let children = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); + group.kind = NodeKind::Group { children, clip: false }; + if let Some(slot) = d.node_mut(id) { + *slot = group; + out.push(id); + selected.push(id); + } + } + sel.set(selected); + Ok(out) + })?; + Ok(json!({ "ids": ids.iter().map(|id| id.0).collect::>() })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/wireframe/tests.rs b/crates/engine/src/cmd/wireframe/tests.rs new file mode 100644 index 0000000000..69e83d4b4a --- /dev/null +++ b/crates/engine/src/cmd/wireframe/tests.rs @@ -0,0 +1,143 @@ +#![allow(clippy::unwrap_used, clippy::panic)] +use serde_json::{Value, json}; +use vectorcraft_doc::appearance::AppearanceItem; +use vectorcraft_doc::{NodeId, NodeKind}; + +use crate::Session; + +/// A new document with a filled 100 pt square; `effect` is applied to it when given. +fn setup(effect: Option<&str>) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width":400,"height":400})).unwrap(); + let id = NodeId(s.execute("path.create", &json!({"d":"M100 100L200 100L200 200L100 200Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"color":"#338ad6"})).unwrap(); + if let Some(effect) = effect { + s.execute("effect.apply", &json!({"effect":effect,"item":null,"params":{}})).unwrap(); + } + (s, id) +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn run(s: &mut Session, p: Value) -> crate::Result { + s.execute("effect.expandAsWireframes", &p) +} + +#[test] +fn a_3d_object_becomes_a_selected_group_of_stroked_edges_in_one_undo_step() { + for effect in ["threeD.extrude", "threeD.classicExtrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"] { + let (mut s, id) = setup(Some(effect)); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().name = Some("Box".into()); + let before = s.doc().unwrap().doc.clone(); + let history = undo_len(&s); + let out = run(&mut s, json!({})).unwrap_or_else(|e| panic!("{effect}: {e}")); + assert_eq!(out["ids"], json!([id.0]), "{effect}"); + let st = s.doc().unwrap(); + let group = st.doc.node(id).unwrap(); + let NodeKind::Group { children, clip: false } = &group.kind else { panic!("{effect}: a group") }; + assert!(!children.is_empty(), "{effect}"); + assert_eq!(group.name.as_deref(), Some("Box"), "{effect}"); + assert!(group.appearance.effects.is_empty(), "{effect}: the effect is gone"); + for c in children { + assert!(c.path_data().is_some(), "{effect}: paths only"); + let [AppearanceItem::Stroke(stroke)] = c.appearance.items.as_slice() else { panic!("{effect}: one stroke and no fill") }; + assert_eq!(stroke.width, super::WIRE_WEIGHT); + } + assert_eq!(st.selection.objects, vec![id], "{effect}"); + assert_eq!(undo_len(&s), history + 1, "{effect}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before, "{effect}"); + } +} + +#[test] +fn the_group_keeps_the_object_s_transparency() { + let (mut s, id) = setup(Some("threeD.extrude")); + s.execute("transparency.set", &json!({"opacity": 50, "knockout": "on"})).unwrap(); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().bbox_angle = 0.25; + let before = s.doc().unwrap().doc.node(id).unwrap().clone(); + run(&mut s, json!({})).unwrap(); + let group = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!((group.opacity - 0.5).abs() < 1e-6, "{}", group.opacity); + assert_eq!((group.opacity, group.blend, group.knockout), (before.opacity, before.blend, before.knockout)); + assert_eq!(group.bbox_angle, 0.25, "the bounding box keeps its angle"); +} + +#[test] +fn a_layer_with_a_3d_effect_stays_a_layer_holding_the_edges() { + let (mut s, _) = setup(None); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + let history = undo_len(&s); + let out = run(&mut s, json!({"ids":[layer.0]})).unwrap(); + assert_eq!(out["ids"], json!([layer.0])); + let st = s.doc().unwrap(); + let node = st.doc.node(layer).unwrap(); + assert!(matches!(node.kind, NodeKind::Layer { .. })); + assert!(node.appearance.effects.is_empty()); + let children = node.children().unwrap(); + assert!(!children.is_empty() && children.iter().all(|c| c.path_data().is_some())); + assert_eq!(st.selection.objects, children.iter().map(|c| c.id).collect::>()); + assert_eq!(undo_len(&s), history + 1); +} + +/// The number of segments in the wireframe group `id`. +fn segments(s: &Session, id: NodeId) -> usize { + let st = s.doc().unwrap(); + st.doc.node(id).unwrap().children().unwrap().iter().flat_map(|c| &c.path_data().unwrap().subpaths).map(|sp| sp.segment_count()).sum() +} + +#[test] +fn a_box_expands_to_the_nine_edges_of_its_three_faces() { + let (mut s, id) = setup(Some("threeD.extrude")); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + run(&mut s, json!({"ids":[id.0]})).unwrap(); + assert_eq!(segments(&s, id), 9); + // A stroke is outlined before the effect, so its own solid adds its edges. + let (mut s, id) = setup(Some("threeD.extrude")); + run(&mut s, json!({"ids":[id.0]})).unwrap(); + assert!(segments(&s, id) > 9); +} + +#[test] +fn objects_without_a_3d_effect_are_left_and_none_at_all_is_an_error() { + let (mut s, plain) = setup(None); + let history = undo_len(&s); + let before = s.doc().unwrap().doc.clone(); + let e = run(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("no selected or given object has a visible 3D effect"), "{e}"); + assert_eq!(undo_len(&s), history, "no undo step when nothing changes"); + assert_eq!(s.doc().unwrap().doc, before); + + // A hidden 3D effect draws nothing to expand. + s.execute("effect.apply", &json!({"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + s.execute("effect.setParams", &json!({"index":0,"item":null,"visible":false})).unwrap(); + assert!(run(&mut s, json!({})).is_err()); + + // With nothing selected. + s.execute("select.none", &json!({})).unwrap(); + let e = run(&mut s, json!({})).unwrap_err().to_string(); + assert!(e.contains("select an object with a 3D effect"), "{e}"); + + // A second object with a 3D effect expands; the plain one is left as it is. + let other = NodeId(s.execute("path.create", &json!({"d":"M250 250L300 250L300 300Z"})).unwrap()["id"].as_u64().unwrap()); + s.execute("effect.remove", &json!({"ids":[plain.0],"index":0,"item":null})).unwrap(); + s.execute("paint.setFill", &json!({"ids":[other.0],"color":"#ff0000"})).unwrap(); + s.execute("effect.apply", &json!({"ids":[other.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + let kept = s.doc().unwrap().doc.node(plain).unwrap().clone(); + let out = run(&mut s, json!({"ids":[plain.0, other.0]})).unwrap(); + assert_eq!(out["ids"], json!([other.0])); + assert_eq!(s.doc().unwrap().doc.node(plain).unwrap(), &kept); +} + +#[test] +fn bad_ids_are_errors() { + let (mut s, _) = setup(Some("threeD.extrude")); + for p in [json!({"ids":[9999]}), json!({"ids":"x"}), json!({"ids":[-1]})] { + let history = undo_len(&s); + assert!(run(&mut s, p.clone()).is_err(), "{p}"); + assert_eq!(undo_len(&s), history, "{p}"); + } +} diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 3c94bf88a5..e8bfede3fd 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -401,6 +401,32 @@ fn a_mixed_revolve_cap_shows_a_dash() { assert_eq!(undo_len(&app), history); } +/// Quick Actions › Expand as Wireframes shows for every object type, and turns the selected 3D +/// object into a group of stroked edges in one undo step. +#[test] +fn expand_as_wireframes_replaces_the_object_with_its_edges() { + for kind in ["extrude", "inflate", "revolve", "plane"] { + let mut app = app(); + set_type(&mut app, kind).unwrap(); + let text = painted_text(&mut app, show); + assert!(text.contains("Quick Actions") && text.contains("Expand as Wireframes"), "{kind}: {text}"); + let id = app.session.active().unwrap().selection.objects[0]; + let history = undo_len(&app); + super::expand_as_wireframes(&mut app).unwrap(); + assert_eq!(undo_len(&app), history + 1, "{kind}"); + let st = app.session.active().unwrap(); + assert!(matches!(st.doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Group { .. }), "{kind}"); + assert_eq!(st.selection.objects, vec![id], "{kind}"); + // The group has no 3D effect: the panel offers the object types again. + assert!(target(&app).is_none(), "{kind}"); + } + // Without a 3D effect in the selection, nothing changes. + let mut app = app(); + let history = undo_len(&app); + assert!(super::expand_as_wireframes(&mut app).is_err()); + assert_eq!(undo_len(&app), history); +} + #[test] fn changed_settings_lists_only_new_values() { let before = json!({"depth": 50.0, "cap": true, "bevel": "none"}); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index 25dfaa6842..5d4763090e 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -7,11 +7,12 @@ use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Effect, Node}; -use vectorcraft_effects::{THREE_D_TYPES, is_three_d}; +use vectorcraft_effects::{CLASSIC_EXTRUDE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d}; use super::{live_run, pstate, set_pstate}; use crate::VectorcraftApp; use crate::state::Dialog; +use crate::theme::Tokens; use crate::widgets::{self, Live, dim_label}; /// The panel's id (`window.panel`). @@ -242,6 +243,32 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let changed = changed_settings(&before, &after); let dragging = ctx.input(|i| i.pointer.any_down()); send(app, &ctx, changed, dragging); + if quick_actions_shown(&d) { + ui.add_space(10.0); + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tl!("Quick Actions")).font(crate::theme::semibold(13.0)).color(t.text)); + let tip = tl!("Replace the selected 3D objects with the edges of their faces, as stroked paths."); + if ui.button(tl!("Expand as Wireframes")).on_hover_text(tip).clicked() { + finish(app, &ctx); + if let Err(e) = expand_as_wireframes(app) { + app.ui.status = e; + } + } + } +} + +/// Does the panel show its Quick Actions? On the Object tab of the effects that have one, and on +/// the first tab of the others (Revolve, Rotate), never on Lighting. +fn quick_actions_shown(d: &Dialog) -> bool { + let effect = d.str("__effect"); + let object_tab = [EXTRUDE, INFLATE, CLASSIC_EXTRUDE].contains(&effect.as_str()); + !crate::dialogs::revolve_gizmo::lighting(d) && (!object_tab || d.str("__tab") != "rotation") +} + +/// Quick Actions › Expand as Wireframes: each selected object with a 3D effect becomes a group of +/// the edges of its faces (`effect.expandAsWireframes`), one undo step. +pub(crate) fn expand_as_wireframes(app: &mut VectorcraftApp) -> Result<(), String> { + app.run("effect.expandAsWireframes", json!({})).map(|_| ()) } /// Sets to null each setting in `fields` (the first selected object's 3D effect) that the 3D effect diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 2602b78bc4..d9752aff51 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims, smooth vector shading and round seam joins, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); no materials, soft shadows or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); no materials, soft shadows or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom or no Shading Color, Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic), Rotate (Classic) and Map Art: none | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object collects an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/mcp.md b/docs/mcp.md index da260b6823..98b64d58f6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3094,6 +3094,28 @@ checked as that effect's. It is one undo step. Any other `threeDType` value, or {"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"item":null,"threeDType":"inflate","params":{"volume":70}}}} ``` +## Expand as Wireframes + +`effect.expandAsWireframes {ids?}` (**Window › 3D and Materials** › Quick Actions › Expand as Wireframes) replaces +each selected object, or each object in `ids`, that has a visible 3D effect (Extrude & Bevel, Extrude & Bevel +(Classic), Revolve, Inflate or Rotate, on the object or on its fills and strokes) with a group of paths: the edges of +the faces the effect draws for the object as it is turned and projected now +([three-d.md](three-d.md#3d-and-materials-panel)). Each edge appears once; edges that meet end to end form one +path, closed where it comes back to its start, and curved edges stay curves. Geometry effects after a 3D effect, +on the object or on a fill or stroke, reshape its edges as they reshape the drawn surface. The paths have a 0.5 pt +black stroke with round joins and no fill (VectorCraft's own choice). The group keeps the object's place, id, name, +visibility, lock, opacity, blending mode, knockout, opacity mask, attributes, slice and text wrap, and the groups +are selected. +A layer in `ids` stays a layer: its members are replaced by the edges, which are selected. Objects without a visible 3D effect do not change. It is one undo step and +returns `{ids}`, the groups. It is an error, and nothing changes, when nothing is selected or given, when no object +has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than +1,000,000 edges. + +```json +{"name":"run_command","arguments":{"command":"effect.expandAsWireframes","params":{}}} +{"name":"run_command","arguments":{"command":"effect.expandAsWireframes","params":{"ids":[12]}}} +``` + ## Extrude & Bevel, Inflate and Rotate `effect.apply {effect: "threeD.extrude" | "threeD.inflate" | "threeD.rotate", params: {...}, ids?, item?}` applies diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 18d50447ff..b3276d581b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -560,6 +560,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. - 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged. - 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 and Materials › Quick Actions › Expand as Wireframes (#6354): `effect.expandAsWireframes` replaces each selected 3D object with a group of 0.5 pt black stroked paths, the edges of the faces its effect draws, each edge once and joined end to end, curves kept, in one undo step ([three-d.md](three-d.md#3d-and-materials-panel)); `crates/effects/src/solids/wireframe/tests.rs`, `crates/engine/src/cmd/wireframe/tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. Scores and hours unchanged. - 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. diff --git a/docs/three-d.md b/docs/three-d.md index 1026a9e1be..283d4a3632 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -51,6 +51,19 @@ pages describe it. unavailable while a setting of a single light differs between the selected effects. - Each change is one undo step. Dragging a value or a slider previews it on the artboard and records one step when the pointer is released; a typed value is recorded when it is entered. Drawing the panel records nothing. +- **Quick Actions › Expand as Wireframes** sits under the Object tab (under the first tab for Revolve and Rotate, + which have no Object tab). It replaces each selected object that has a 3D effect with a group of paths, the + edges of the faces the effect draws for the object as it is turned and projected now (`effect.expandAsWireframes`), + as the public [Render 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/render-3d-vector-artwork.html) + page describes for converting the wireframe into editable paths. Each edge appears once: edges that meet end to + end form one path, closed where it comes back to its start, and curved edges stay curves. A face partly covered + by another face gives its whole outline. Faces turned away from the viewer are included where the effect draws + them (Draw Hidden Faces and the Wireframe surface of Extrude & Bevel (Classic)). Geometry effects after a 3D + effect, on the object or on a fill or stroke, reshape the edges as they reshape the drawn art. Shadows are not + part of the wireframe. The paths have a 0.5 pt black stroke with round joins and no fill, which is VectorCraft's + own choice. The group keeps the object's place, id, name, opacity, blending mode, opacity mask, attributes + and text wrap and is selected; objects without a visible 3D effect do not change. It is one undo step, and an error changes nothing + when no selected object has a visible 3D effect. - The Lighting tab also holds the Shadows switch and its settings ([Shadows](#shadows)). The Materials tab and ray-traced rendering are not built (see below). The rotation and light rings on the artboard are part of the options dialog only. From a90a803cfba2856f748a0d9132bbe4f19c0bbe27 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 21:42:57 -0800 Subject: [PATCH 02/33] 3D and Materials: Expand as Wireframes expands an id given twice once An object or layer named twice in ids is expanded once, so the selection holds only the edges that are in the document. --- crates/engine/src/cmd/wireframe.rs | 5 +++++ crates/engine/src/cmd/wireframe/tests.rs | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/wireframe.rs b/crates/engine/src/cmd/wireframe.rs index 5e7dd3f0d4..27a35a793b 100644 --- a/crates/engine/src/cmd/wireframe.rs +++ b/crates/engine/src/cmd/wireframe.rs @@ -47,7 +47,12 @@ fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result { // they are. let d = &s.doc()?.doc; let mut wires = vec![]; + let mut seen = std::collections::HashSet::new(); for id in roots { + // An id given twice is expanded once. + if !seen.insert(id) { + continue; + } let Some(n) = d.node(id) else { continue }; if !effects::has_revolve(n) && !effects::has_solid(n) { continue; diff --git a/crates/engine/src/cmd/wireframe/tests.rs b/crates/engine/src/cmd/wireframe/tests.rs index 69e83d4b4a..67e338b781 100644 --- a/crates/engine/src/cmd/wireframe/tests.rs +++ b/crates/engine/src/cmd/wireframe/tests.rs @@ -71,7 +71,8 @@ fn a_layer_with_a_3d_effect_stays_a_layer_holding_the_edges() { let layer = s.doc().unwrap().doc.layers[0].id; s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); let history = undo_len(&s); - let out = run(&mut s, json!({"ids":[layer.0]})).unwrap(); + // An id given twice is expanded once. + let out = run(&mut s, json!({"ids":[layer.0, layer.0]})).unwrap(); assert_eq!(out["ids"], json!([layer.0])); let st = s.doc().unwrap(); let node = st.doc.node(layer).unwrap(); From e6f330afd23abc78514265cd078ab1cd384bb803 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 23:59:18 -0800 Subject: [PATCH 03/33] Automation: ui.dialog.set cannot change the command a dialog runs ui.dialog.set took every field whose name starts with `__`, so a control request (or MCP's answer_dialog, which goes through it) could rewrite the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command`, or the paste a swatch conflict waits to finish, after a person opened the dialog. The person's OK then ran something else. A `__` field is now settable only when it is a control of that kind of dialog: a section or tab shown, a link between two fields, a name or search being typed (for example Save PDF's `__section`, Transform Each's `__constrain`, the Preferences `__search`). Every other `__` field, held or not, is refused with "the `` dialog cannot set protected field ``". The request sets no field, and with `action: "confirm"` OK does not run. Flags a button sets together with other fields are refused too: the style dialogs' `__reset*`, Artboard Options' `__fit`, `__sizeChoice`, `__refx` and `__refy`, and Scribble's `__scribbleSetting`. Recolor's Merge takes a row listed twice in the selection once, and Randomize keeps a seed at u64::MAX instead of overflowing it. Docs: docs/control-protocol.md, docs/mcp.md, docs/target-app-parity.md. --- crates/ui-egui/src/control.rs | 5 + crates/ui-egui/src/control/tests.rs | 8 +- crates/ui-egui/src/dialogs.rs | 69 +++++- .../src/dialogs/brush_options/tests.rs | 10 +- crates/ui-egui/src/dialogs/recolor.rs | 27 ++- crates/ui-egui/src/placing/tests.rs | 3 +- crates/ui-egui/src/tests/automation.rs | 204 +++++++++++++++++- docs/control-protocol.md | 2 +- docs/mcp.md | 2 +- docs/target-app-parity.md | 1 + 10 files changed, 312 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 11edb6de6e..1c09f918f9 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -18,6 +18,8 @@ //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` //! - `ui.dialog.set {field, value}` or `{fields: [{field, value}…]}` (all or none; setting a field //! the dialog does not read is an error that lists its fields: [`crate::dialogs::accepts_field`]; +//! a `__` field other than the controls of the dialog's kind is an error too, so a request cannot +//! change the command, targets or file the dialog's OK acts on: [`crate::dialogs::protected_field`]; //! `action: confirm | cancel` then confirms or cancels that dialog in the same request and replies //! `{dialog, result}`) / `ui.dialog.confirm` / `ui.dialog.cancel` //! - `ui.resize {width, height}`, `ui.focus`, `ui.screenshot {path?, data?}` (`data: true`: the PNG @@ -603,6 +605,9 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques }; // Every field is checked before any is set, so a request sets all of them or none. if let Some((f, _)) = fields.iter().find(|(f, _)| !crate::dialogs::accepts_field(d, f)) { + if crate::dialogs::protected_field(d, f) { + return err(format!("the `{}` dialog cannot set protected field `{f}`", d.kind)); + } let names = crate::dialogs::field_names(d).join(", "); return err(format!("the `{}` dialog has no field `{f}`; its fields: {names}", d.kind)); } diff --git a/crates/ui-egui/src/control/tests.rs b/crates/ui-egui/src/control/tests.rs index 1763fd679a..d441946622 100644 --- a/crates/ui-egui/src/control/tests.rs +++ b/crates/ui-egui/src/control/tests.rs @@ -767,7 +767,8 @@ fn save_and_close_apply_a_merge_on_another_thread_first() { /// `ui.dialog.set` of a field the open dialog does not have is an error that lists its fields, /// and the dialog stays as it was. Fields a dialog may not hold yet are still set: `discard` -/// with a discard button, `preview` with a live preview, `__` fields and the spec's `inputs`. +/// with a discard button, `preview` with a live preview and the spec's `inputs`. A `__` field that +/// is not one of the controls of the dialog's kind is refused. #[test] fn dialog_set_refuses_a_field_the_dialog_does_not_have() { let mut app = VectorcraftApp::new(Session::new(), Services::default()); @@ -776,8 +777,11 @@ fn dialog_set_refuses_a_field_the_dialog_does_not_have() { let r = input_request(&mut app, "ui.dialog.set", json!({"field": "discrad", "value": true})); assert_eq!(r["ok"], false, "{r}"); assert_eq!(r["error"], "the `saveChanges` dialog has no field `discrad`; its fields: discard, index, name, then, uid"); + assert_eq!(app.ui.dialog.as_ref().map(|d| Value::Object(d.fields.clone())), Some(fields.clone())); + let r = input_request(&mut app, "ui.dialog.set", json!({"field": "__note", "value": true})); + assert_eq!(r["error"], "the `saveChanges` dialog cannot set protected field `__note`", "{r}"); assert_eq!(app.ui.dialog.as_ref().map(|d| Value::Object(d.fields.clone())), Some(fields)); - for field in ["name", "discard", "__note"] { + for field in ["name", "discard"] { let r = input_request(&mut app, "ui.dialog.set", json!({"field": field, "value": true})); assert_eq!(r["ok"], true, "{field}: {r}"); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f9788d59a8..9274bbd40c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -481,13 +481,69 @@ fn spec(kind: &str) -> &'static DialogSpec { DialogKind::of(kind).map_or(&FALLBACK, DialogKind::spec) } -/// Whether `ui.dialog.set` can set `field` on `d`: a field it holds, a `__` field (the dialog's -/// own state), `discard` on a dialog with a discard button, `preview` on one with a live preview, -/// one of its spec's `inputs` for its kind, or one it `passes` on. +/// The `__` fields that `ui.dialog.set` can set on `d`: controls of its kind that the dialog holds +/// under a `__` name, each set as the control sets it. Every other `__` field of a dialog holds +/// what its OK acts on (the command and its fixed params, the targets, a file, the preset being +/// edited) or state the dialog keeps for itself, and `ui.dialog.set` refuses it +/// ([`protected_field`]), so a request cannot change what OK does after a person opened the dialog. +/// Flags that a button sets together with other fields are refused too: the style dialogs' +/// `__reset*` (Reset Panel also clears the section's fields, so scripts run +/// `ui.charStyleOptions.resetPanel` or `ui.paraStyleOptions.resetPanel`) and Artboard Options' +/// `__fit`, `__sizeChoice`, `__refx` and `__refy` (set with the size and position they record), and +/// Scribble's `__scribbleSetting` (the menu sets the preset's parameters with it). +fn hidden_controls(d: &Dialog) -> &'static [&'static str] { + match DialogKind::of(&d.kind) { + // Duotone's tone row, and the 3D effects' tab, gizmo, light and Show axis. + Some(DialogKind::Effect) => &["__gizmo", "__light", "__showAxis", "__tab", "__tone"], + // The preset name being typed and the format whose settings the gear shows. + Some(DialogKind::ExportForScreens) => &["__savePreset", "__settings"], + // Keywords typed but not added yet. + Some(DialogKind::FileInfo) => &["__keyword"], + // The preset name being typed. + Some(DialogKind::FlattenTransparency) => &["__presetName"], + // The Resolution menu's Other. + Some(DialogKind::RasterOptions | DialogKind::RasterFormatOptions | DialogKind::PsdOptions) => &["__otherPpi"], + // The category shown, the search text and the three settings kept outside the preferences. + Some(DialogKind::Preferences) => &["__category", "__search", "__smartGuides", "__snapToGrid", "__taskBar"], + // The section shown, the sheet the preview shows and the preset name being typed. + Some(DialogKind::Print | DialogKind::PrintPreset) => &["__savePresetAs", "__section", "__sheet"], + // The section shown, All or a range of artboards, the two password checkboxes and the + // preset name being typed. + Some(DialogKind::SavePdf | DialogKind::PdfPreset) => { + &["__allArtboards", "__requireOpenPassword", "__restrictPermissions", "__savePresetAs", "__section"] + } + // The selected rows and Randomize's seed. + Some(DialogKind::Recolor) => &["__seed", "__sel"], + // The view, zoom, download speed, selected color table entry and the preset name being typed. + Some(DialogKind::SaveForWeb) => &["__color", "__kbps", "__presetName", "__view", "__zoom"], + // The link that keeps width and height in proportion. + Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], + // The attention filter, the Keys section, the search text and the key being recorded. + Some(DialogKind::ShortcutImport) => &["__attention", "__keysOpen", "__query", "__recording"], + // Set Size of Each's Width and Height checkboxes. + Some(DialogKind::ArrangeTools) if d.kind == crate::addons::arrange::SIZE => &["__height", "__width"], + // The search field. + Some(DialogKind::SelectByArtboards | DialogKind::SelectByLinkStatus) => &["__search"], + _ => &[], + } +} + +/// Whether `field` is a `__` field of `d` that `ui.dialog.set` refuses: any `__` field, held or +/// not, except the controls of `d`'s kind ([`hidden_controls`]). +pub fn protected_field(d: &Dialog, field: &str) -> bool { + field.starts_with("__") && !hidden_controls(d).contains(&field) +} + +/// Whether `ui.dialog.set` can set `field` on `d`: a `__` field only when it is one of the controls +/// of `d`'s kind ([`protected_field`]); otherwise a field it holds, `discard` on a dialog with a +/// discard button, `preview` on one with a live preview, one of its spec's `inputs` for its kind, +/// or one it `passes` on. pub fn accepts_field(d: &Dialog, field: &str) -> bool { + if field.starts_with("__") { + return !protected_field(d, field); + } let spec = spec(&d.kind); d.fields.contains_key(field) - || field.starts_with("__") || (field == "discard" && spec.discard.is_some()) || (field == "preview" && spec.preview) || (spec.inputs)(&d.kind).contains(&field) @@ -520,11 +576,12 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { } } -/// The fields `ui.dialog.set` can set on `d`, sorted, without the `__` ones: those it holds, -/// `discard`, `preview` and the spec's `inputs` for its kind. +/// The fields `ui.dialog.set` can set on `d`, sorted: those it holds other than its `__` ones, the +/// `__` controls of its kind, `discard`, `preview` and the spec's `inputs` for its kind. pub fn field_names(d: &Dialog) -> Vec { let spec = spec(&d.kind); let mut names: Vec = d.fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); + names.extend(hidden_controls(d).iter().map(|f| f.to_string())); names.extend(spec.discard.map(|_| "discard".to_string())); names.extend(spec.preview.then(|| "preview".to_string())); names.extend((spec.inputs)(&d.kind).iter().map(|i| i.to_string())); diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 3ae028bb05..f2fcc88981 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -436,13 +436,17 @@ fn each_tips_sample_paints_the_brush_with_its_method() { assert!(tints != hue && tints != shades && none != shades, "four different samples"); } -/// `ui.dialog.set` writes any field, `__def` included. With a brush definition that is not -/// an object, Brush Options and Colorization Tips still draw. +/// With a brush definition that is not an object, Brush Options and Colorization Tips still draw. +/// `ui.dialog.set` refuses `__def`, which holds the brush OK saves. #[test] fn a_brush_definition_that_is_not_an_object_still_draws() { let (mut app, ctx) = (app(), ctx()); app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); - crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "__def", "value": 5})); + let (req, _) = crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "__def", "value": 5})); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("not done") }; + assert_eq!(r["error"], "the `brushOptions` dialog cannot set protected field `__def`", "{r}"); + assert_ne!(app.ui.dialog.as_ref().unwrap().fields.get("__def"), Some(&json!(5)), "the request is refused"); + set(&mut app, json!({"__def": 5})); crate::tests_synthetic::control(&mut app, &ctx, "ui.dialog.set", json!({"field": "tips", "value": true})); let text = shown(&mut app); assert!(text.contains("Scatter Brush Options") && text.contains("Colorization Tips"), "{text}"); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index 6f696f4302..784a19007b 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -262,6 +262,11 @@ fn excluded(row: &Value) -> bool { row["exclude"].as_bool().unwrap_or(false) } +/// The seed for the next Randomize: one past the last, held at `u64::MAX`. +fn next_seed(d: &Dialog) -> u64 { + (d.f64("__seed", 0.0) as u64).saturating_add(1) +} + fn selection(d: &Dialog) -> Vec { d.fields.get("__sel").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_u64).map(|i| i as usize).collect()).unwrap_or_default() } @@ -546,7 +551,7 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [("arrow-left-right", tl!("Randomly change color order"), false), ("sparkles", tl!("Randomly change saturation and brightness"), true)] { if widgets::icon_button_enabled(ui, icon, tip, false, rows.len() > 1 || sb, 24.0).clicked() { - let seed = d.f64("__seed", 0.0) as u64 + 1; + let seed = next_seed(d); d.fields.insert("__seed".into(), json!(seed)); let p = json!({"map": rows, "order": !sb, "saturationBrightness": sb, "seed": seed}); match app.session.execute("recolor.randomize", &p) { @@ -897,6 +902,7 @@ fn sliders(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value] fn merge(rows: &mut Vec, sel: &[usize]) { let mut sel: Vec = sel.iter().copied().filter(|i| *i < rows.len()).collect(); sel.sort_unstable(); + sel.dedup(); let Some((&first, rest)) = sel.split_first() else { return }; let mut moved = vec![]; for &i in rest.iter().rev() { @@ -1208,6 +1214,25 @@ mod tests { assert_eq!(r[2]["to"], "rgb 0 0 128"); } + /// A selection that lists a row twice merges it once, as `ui.dialog.set` can store one. + #[test] + fn merge_takes_a_repeated_row_once() { + let mut r = rows(); + merge(&mut r, &[0, 2, 2]); + assert_eq!(r.len(), 2); + assert_eq!(r[0]["from"], json!(["rgb 255 0 0", "rgb 0 255 0"])); + merge(&mut r, &[1, 1]); + assert_eq!(r.len(), 2); + } + + /// Randomize after a seed past `u64::MAX` keeps the largest seed. + #[test] + fn next_seed_holds_at_the_largest() { + assert_eq!(next_seed(&Dialog::new("recolor", json!({}))), 1); + assert_eq!(next_seed(&Dialog::new("recolor", json!({"__seed": 4}))), 5); + assert_eq!(next_seed(&Dialog::new("recolor", json!({"__seed": 1e30}))), u64::MAX); + } + #[test] fn linked_handles_move_together() { let mut r = rows(); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 96492a6512..9afe94b9ee 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -587,7 +587,8 @@ fn a_deferred_swatch_paste_rejects_a_changed_token_or_closed_document() { &crate::control::ControlRequest::new("ui.dialog.set", json!({"field": "__deferredPaste", "value": 999999})).0, ); let crate::control::Outcome::Done(result) = result else { panic!("expected dialog result") }; - assert_eq!(result["ok"], true, "{result}"); + assert_eq!(result["error"], "the `swatchConflict` dialog cannot set protected field `__deferredPaste`", "{result}"); + app.ui.dialog.as_mut().unwrap().fields.insert("__deferredPaste".into(), json!(999999)); } let error = crate::dialogs::confirm(&mut app).unwrap_err(); assert!( diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index df2fe29912..d2d0a8c4b6 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -10,6 +10,7 @@ use vectorcraft_engine::file_access::AutomationRoots; use crate::background::SharedWriteFn; use crate::control::ControlRequest; +use crate::state::Dialog; use crate::{Services, VectorcraftApp}; /// A folder holding `in` (the read root, with `a.svg`), `out` (the write root) and `outside` @@ -658,12 +659,12 @@ fn automation_cannot_approve_a_plugin_install() { assert!(app.ui.dialog.is_some(), "the refused answer leaves it open"); assert!(vectorcraft_plugins::registry::get(id).is_none()); - // What the dialog installs isn't in its fields. + // What the dialog installs isn't in its fields, and its `__` fields can't be set. let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__params", "value": {"dataBase64": "AAAA"}})); - assert!(r.get("error").is_none(), "{r}"); + refused(&r, "cannot set protected field `__params`"); // What MCP's `answer_dialog` sends: `ui.dialog.set {fields}`, then `ui.dialog.confirm`. let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "__params", "value": {"dataBase64": "AAAA"}}]})); - assert!(r.get("error").is_none(), "{r}"); + refused(&r, "cannot set protected field `__params`"); let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); refused(&r, ASKED); assert!(app.ui.dialog.is_some() && vectorcraft_plugins::registry::get(id).is_none()); @@ -691,6 +692,200 @@ fn automation_cannot_approve_a_plugin_install() { app.run("plugin.remove", json!({"id": id})).unwrap(); } +/// An app with a control channel and a new document. +fn controlled() -> (VectorcraftApp, std::sync::mpsc::Sender) { + let (tx, rx) = std::sync::mpsc::channel(); + let mut app = VectorcraftApp::new(Session::new(), Default::default()).with_control(rx); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + (app, tx) +} + +/// The fields of the open dialog. +fn dialog_fields(app: &VectorcraftApp) -> Option> { + app.ui.dialog.as_ref().map(|d| d.fields.clone()) +} + +/// The objects on the document's first layer. +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len()) +} + +/// The left edge and width of the first object on the document's first layer. +fn first_object(app: &VectorcraftApp) -> (f64, f64) { + let b = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + (b.x0, b.width()) +} + +/// Each of `sets` sent as `ui.dialog.set` is refused with the protected-field error of the +/// `kind` dialog, sets no field, and runs nothing. +fn refused_sets(app: &mut VectorcraftApp, tx: &std::sync::mpsc::Sender, kind: &str, sets: &[Value]) { + for set in sets { + let before = dialog_fields(app); + let r = request(app, tx, "ui.dialog.set", set.clone()); + let says = format!("the `{kind}` dialog cannot set protected field `__"); + assert!(r["error"].as_str().is_some_and(|e| e.starts_with(&says)), "{set}: {r}"); + assert_eq!(dialog_fields(app), before, "{set}: no field changes and the dialog stays open"); + assert_eq!(objects(app), 0, "{set}: nothing ran"); + } +} + +/// A confirmation a person opened runs the command it was opened with: `ui.dialog.set` can't +/// change its `__command` or `__params`, alone or in a list with other fields and `action: +/// "confirm"`, and OK then runs the command it asked about. +#[test] +fn dialog_set_cannot_redirect_person_opened_confirm() { + let (mut app, tx) = controlled(); + let rect = json!({"x": 10, "y": 10, "width": 20, "height": 20}); + crate::dialogs::confirm::ask(&mut app, "Add a rectangle?", "", "shape.rectangle", rect); + let other = json!({"x": 0, "y": 0, "width": 90, "height": 90}); + refused_sets( + &mut app, + &tx, + crate::dialogs::confirm::KIND, + &[ + json!({"field": "__command", "value": "file.close"}), + json!({"field": "__params", "value": other}), + json!({"fields": [{"field": "detail", "value": "Sure?"}, {"field": "__command", "value": "file.close"}], "action": "confirm"}), + json!({"fields": [{"field": "__params", "value": other}, {"field": "detail", "value": "Sure?"}], "action": "confirm"}), + ], + ); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "detail", "value": "Sure?"}], "action": "confirm"})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ui.dialog.is_none() && objects(&app) == 1, "OK ran the command it asked about"); + assert_eq!(first_object(&app), (10.0, 20.0)); +} + +/// The generic parameter dialog runs its command with its fixed parameters: `ui.dialog.set` can +/// change the parameters it shows, not `__command`, `__params` or `__label`. +#[test] +fn dialog_set_cannot_redirect_parameter_dialog() { + let (mut app, tx) = controlled(); + let fields = json!({"__command": "shape.rectangle", "__label": "Rectangle", "__params": {"x": 10, "y": 10}, "width": 20, "height": 20}); + app.ui.dialog = Some(Dialog::new("command", fields)); + refused_sets( + &mut app, + &tx, + "command", + &[ + json!({"field": "__command", "value": "file.close"}), + json!({"field": "__params", "value": {"x": 500, "y": 500}}), + json!({"field": "__label", "value": "Close"}), + json!({"fields": [{"field": "width", "value": 30}, {"field": "__command", "value": "file.close"}], "action": "confirm"}), + ], + ); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "width", "value": 30, "action": "confirm"})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ui.dialog.is_none() && objects(&app) == 1, "OK ran the dialog's command"); + assert_eq!(first_object(&app), (10.0, 30.0), "with its fixed x and the width set"); +} + +/// A plug-in command's dialog runs that command of that plug-in: `ui.dialog.set` can't change its +/// `__command` or `__plugin`. +#[test] +fn dialog_set_cannot_redirect_plugin_command() { + let (mut app, tx) = controlled(); + let fields = json!({"__plugin": "test.ui.redirect", "__command": "plugin.test.ui.redirect.a", "__label": "A", "amount": 1}); + app.ui.dialog = Some(Dialog::new(crate::dialogs::plugin::KIND, fields)); + refused_sets( + &mut app, + &tx, + crate::dialogs::plugin::KIND, + &[ + json!({"field": "__command", "value": "plugin.test.ui.redirect.b"}), + json!({"field": "__plugin", "value": "test.ui.other"}), + json!({"fields": [{"field": "amount", "value": 2}, {"field": "__command", "value": ""}], "action": "confirm"}), + ], + ); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "amount", "value": 2})); + assert_eq!(r["ok"], true, "{r}"); +} + +/// A `__` field the dialog does not hold is refused as a protected field too, and so is a control +/// of another kind of dialog; the error for an unknown field lists the dialog's own controls only. +#[test] +fn dialog_set_rejects_unknown_hidden_field() { + let (mut app, tx) = controlled(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + for field in ["__anything", "__section", "__ratio", "__constrainApplied"] { + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": field, "value": true})); + assert_eq!(r["error"], format!("the `transformEach` dialog cannot set protected field `{field}`"), "{r}"); + assert!(!dialog_fields(&app).unwrap().contains_key("__anything")); + } + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "nosuch", "value": true})); + let error = r["error"].as_str().unwrap_or_default(); + assert!(error.contains("has no field `nosuch`") && error.contains("__constrain"), "{r}"); + assert!(!error.contains("__ratio") && !error.contains("__section"), "{r}"); + + // Artboard Options' Fit, size preset and reference point flags are set by their buttons + // together with the size and position they record. + app.ui.dialog = Some(Dialog::new("artboardOptions", json!({"width": 60, "height": 20}))); + for (field, value) in [("__fit", json!(true)), ("__sizeChoice", json!({"landscape": true})), ("__refx", json!(2)), ("__refy", json!(2))] { + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": field, "value": value})); + assert_eq!(r["error"], format!("the `artboardOptions` dialog cannot set protected field `{field}`"), "{r}"); + assert!(!dialog_fields(&app).unwrap().contains_key(field)); + } + // Scribble's Settings menu sets the preset's parameters along with its name. + app.ui.dialog = Some(Dialog::new("effect", json!({"__effect": "scribble", "angle": 30}))); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__scribbleSetting", "value": "sharp"})); + assert_eq!(r["error"], "the `effect` dialog cannot set protected field `__scribbleSetting`", "{r}"); +} + +/// The dialog controls held under a `__` name are still set: Transform Each's link, the Save PDF +/// section and its All artboards checkbox, and the Preferences search. +#[test] +fn dialog_set_allows_hidden_controls() { + let (mut app, tx) = controlled(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 60, "height": 20})).unwrap(); + app.run("select.all", json!({})).unwrap(); + crate::menus::invoke(&mut app, "object.transformEach", json!({})); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__constrain", "value": true})); + assert_eq!(r["ok"], true, "{r}"); + assert!(app.ui.dialog.as_ref().is_some_and(|d| d.bool("__constrain"))); + app.ui.dialog = None; + + app.run("ui.savePdfDialog", json!({})).unwrap(); + let set = json!({"fields": [{"field": "__section", "value": "Security"}, {"field": "__allArtboards", "value": false}]}); + let r = request(&mut app, &tx, "ui.dialog.set", set); + assert_eq!(r["ok"], true, "{r}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.str("__section"), d.bool("__allArtboards")), ("Security".to_string(), false)); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__save", "value": "file.saveCopy"})); + assert_eq!(r["error"], "the `savePdf` dialog cannot set protected field `__save`", "{r}"); + app.ui.dialog = None; + + // The raster options dialogs share the Resolution menu's Other, PSD Options included. + for kind in ["pngOptions", "tiffOptions", "psdOptions"] { + app.ui.dialog = Some(Dialog::new(kind, json!({"ppi": 72}))); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__otherPpi", "value": true})); + assert_eq!(r["ok"], true, "{kind}: {r}"); + } + app.ui.dialog = None; + + // A style section's reset flag alone would keep the section's values: scripts run the Reset + // Panel commands, which clear them. Which of the two styles a new style is stays fixed. + for (kind, para, flag) in [ + ("charStyleOptions", false, "__resetColor"), + ("paraStyleOptions", true, "__resetHyphenation"), + ("newTextStyle", false, "__resetColor"), + ("newTextStyle", true, "__resetHyphenation"), + ] { + app.ui.dialog = Some(Dialog::new(kind, json!({"name": "A", "__para": para}))); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": flag, "value": true})); + assert_eq!(r["error"], format!("the `{kind}` dialog cannot set protected field `{flag}`"), "{r}"); + assert!(!app.ui.dialog.as_ref().is_some_and(|d| d.bool(flag)), "{kind}"); + } + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__para", "value": false})); + assert_eq!(r["error"], "the `newTextStyle` dialog cannot set protected field `__para`", "{r}"); + app.ui.dialog = None; + + crate::prefs_dialog::open(&mut app, None); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__search", "value": "grid"})); + assert_eq!(r["ok"], true, "{r}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__search")), Some("grid".to_string())); +} + /// The refusal of an OK on an install question automation asked. const ASKED: &str = "Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself."; @@ -934,7 +1129,8 @@ fn automation_cannot_approve_replacing_a_plugin() { assert_eq!(r, json!({"pending": crate::dialogs::plugin::INSTALL_KIND})); let evil = vectorcraft_format::base64_encode(&plain(r#"{"objects":[{"name":"x"}]}"#)); let r = request(&mut app, &tx, "ui.dialog.set", json!({"fields": [{"field": "__params", "value": {"dataBase64": evil, "replace": true}}]})); - assert!(r.get("error").is_none(), "{r}"); + let protected = format!("the `{}` dialog cannot set protected field `__params`", crate::dialogs::plugin::INSTALL_KIND); + assert_eq!(r["error"], protected, "{r}"); super::plugins::show_approval(&mut app); let r = request(&mut app, &tx, "ui.dialog.confirm", json!({})); assert!(r["error"].as_str().is_some_and(|e| e.contains("Only the person at the keyboard")), "{r}"); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 640f1e805a..0fdfbc8231 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -102,7 +102,7 @@ the two can still win that race. | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do | | `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | -| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`), `__` fields, `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | +| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | diff --git a/docs/mcp.md b/docs/mcp.md index aeed51157a..24d264cd38 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -509,7 +509,7 @@ applied colors still join the list while it is hidden. | `set_paint` | `{fill?, stroke?, strokeWidth?, ids?}` | Applies to the selection (or `ids`) and becomes the default for new art. Returns `{applied, objects}`: `objects` is the number of objects painted, as the `objects` of the `paint.setFill`, `paint.setStroke` and `stroke.set` replies (the largest of them): a selected group counts the objects inside it. When it is 0, a `note` says that only the paint for new art changed. | | `press_key` | `{key, mods?}` | Remote: a real key event. Headless: runs the command or tool bound to that shortcut, or sends the key to the busy tool (digits too: `5` while dragging with the Perspective Selection tool; `e` while dragging a Selection or Group Selection marquee; `c` and `f` while dragging out an arc; `f`, `v`, `x` and `c` while dragging out a rectangular or polar grid). | | `type_text` | `{text}` | Remote only. | -| `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | +| `answer_dialog` | `{set?: [{field, value?}], action?}` | Remote only. Sets fields of the app's open dialog in the order given with one `ui.dialog.set {fields, action?}` (a missing `value` is `null`). The app stores all of them or none, then answers that same dialog with `action` in the same request: `confirm` (OK) or `cancel`. Another connection cannot open a dialog between the two steps. When the app refuses the `ui.dialog.set`, for example because no dialog is open, the call is an error and the dialog is not confirmed or canceled. `set` cannot change a `__` field other than the dialog's controls held under a `__` name (such as Save PDF's `__section` or the Preferences `__search`): the `__command` and `__params` of a `confirm` or `command` dialog, and every other `__` field that holds what OK acts on, are refused with "the `` dialog cannot set protected field ``", so OK runs what the dialog was opened for. `action` alone is sent as `ui.dialog.confirm` or `ui.dialog.cancel`. Give `set`, `action` or both; `set` holds at most 256 fields. `inspect_ui` shows the open dialog and its fields as `ui.dialog`. Returns `{dialog, result}`: the dialog after the fields were set (or `null`) and the reply to `confirm` or `cancel` (or `null`). After `invoke_menu` `app.quit`, `file.close` or `file.closeAll` replies `{"pending": "saveChanges"}`, `{action: "confirm"}` saves, `{set: [{field: "discard", value: true}], action: "confirm"}` closes without saving and `{action: "cancel"}` cancels the close or quit. | | `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). | | `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. | | `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e0cf03a3a..660051393d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1703,6 +1703,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Filter plug-ins read type, images and symbol instances (G17, #4333):** a filter at plug-in API level 2 lists `inputs` (`type`, `image`, `symbolInstance`) with `doc.read` in its `permissions`, so installing it asks for approval, and is also given the selected objects of those kinds, read only: type with its runs, character and paragraph attributes (no text past 256 KiB or 4,096 runs or paragraphs, or 16 MiB of runs over the input), images with their size, color mode and, when embedded and at most 1 MiB in base64 (16 MiB over the input), their RGBA pixels (a CMYK image's through the working CMYK profile; never a linked file's), and symbol instances with their symbol and transform. The objects come in paint order from the bottom, and an image that reaches the decoder counts toward the 16 MiB of pixels even when decoding fails. Every object counts toward the input's half of the memory cap; one whose fields besides its pixels and runs don't fit fails the run naming it and its size, a path or compound path that doesn't fit fails it too, and so do more than 100,000 of these objects. Its output returns each as `{id}` or exactly as given; any change or omission is refused before the document changes. Filters without `inputs` get the same input as before, except that compound paths that clip a clip group and paths inside a group that clips one are left out for every filter. Regressions: `crates/plugins/src/objects/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 grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **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 dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `` dialog cannot set protected field ``"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged. - **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user, the unsigned `grants.json`). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. - **Plug-in approval waits before OK (G17):** the approval dialog's OK stays disabled until its question has been on screen in the focused window for half a second, VectorCraft's own value; a click, Enter, Space, or a press begun before then installs nothing, and the dialog stays open. The wait starts over for every new question, even one that reads the same, and when the window gets the focus back, so a question swapped in just before a click is not approved by it. Cancel works at once. Regressions: `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. - **An install automation asked for needs the person to start it (G17):** an approval question that a control request, MCP, injected input or a file dialog one of them opened leads to keeps OK disabled and refuses every confirm, a person's click included; it says to choose Object › Plug-ins › Install Plug-in…, and `ui.installPlugin` answers `approval: "personMustStartInstall"`. The person's own Install Plug-in…, File › Open or drop inspects the module again and asks a new question. Automation's `replace: true` no longer skips the question about taking another module's place, and that question now opens in the approval dialog for everyone. VectorCraft's own rule. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged. From 18fe6ad6fd33eb55f024a30f076ab24339873864 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 00:37:35 -0800 Subject: [PATCH 04/33] Automation: ui.dialog.set cannot open Save Preset in Save PDF or Print `__savePresetAs` makes OK save a preset instead of writing the PDF or printing. ui.dialog.set now accepts it only while Save Preset... has added the field, so a request cannot add it and confirm in one step. --- crates/ui-egui/src/dialogs.rs | 17 +++++++++++--- crates/ui-egui/src/tests/automation.rs | 31 ++++++++++++++++++++++++++ docs/control-protocol.md | 2 +- 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9274bbd40c..838fc8161d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -528,10 +528,21 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] { } } +/// The controls of [`hidden_controls`] that a button adds to the dialog, which `ui.dialog.set` can +/// set only while the dialog holds them: Save PDF's and Print's `__savePresetAs`, whose presence +/// makes OK save a preset instead of writing the PDF or printing. +const ADDED_CONTROLS: &[&str] = &["__savePresetAs"]; + +/// Whether `field` is a control of `d` that `ui.dialog.set` can set: one of the controls of `d`'s +/// kind ([`hidden_controls`]), and for one that a button adds ([`ADDED_CONTROLS`]), one `d` holds. +fn settable_control(d: &Dialog, field: &str) -> bool { + hidden_controls(d).contains(&field) && (!ADDED_CONTROLS.contains(&field) || d.fields.contains_key(field)) +} + /// Whether `field` is a `__` field of `d` that `ui.dialog.set` refuses: any `__` field, held or -/// not, except the controls of `d`'s kind ([`hidden_controls`]). +/// not, except the controls of `d`'s kind ([`settable_control`]). pub fn protected_field(d: &Dialog, field: &str) -> bool { - field.starts_with("__") && !hidden_controls(d).contains(&field) + field.starts_with("__") && !settable_control(d, field) } /// Whether `ui.dialog.set` can set `field` on `d`: a `__` field only when it is one of the controls @@ -581,7 +592,7 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { pub fn field_names(d: &Dialog) -> Vec { let spec = spec(&d.kind); let mut names: Vec = d.fields.keys().filter(|k| !k.starts_with("__")).cloned().collect(); - names.extend(hidden_controls(d).iter().map(|f| f.to_string())); + names.extend(hidden_controls(d).iter().filter(|f| settable_control(d, f)).map(|f| f.to_string())); names.extend(spec.discard.map(|_| "discard".to_string())); names.extend(spec.preview.then(|| "preview".to_string())); names.extend((spec.inputs)(&d.kind).iter().map(|i| i.to_string())); diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d2d0a8c4b6..36908ec3e6 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -886,6 +886,37 @@ fn dialog_set_allows_hidden_controls() { assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("__search")), Some("grid".to_string())); } +/// Save PDF's and Print's OK save a preset while Save Preset… asks for its name: `ui.dialog.set` +/// can't add `__savePresetAs` to turn OK into saving a preset, alone or with `action: "confirm"`, +/// and can type the name once Save Preset… has added the field. +#[test] +fn dialog_set_cannot_open_save_preset() { + let (mut app, tx) = controlled(); + let saved = |app: &VectorcraftApp| (app.session.prefs.pdf_presets.len(), app.session.prefs.print_presets.len()); + for (open, kind) in [("ui.savePdfDialog", "savePdf"), ("file.print", "print")] { + app.run(open, json!({})).unwrap(); + let presets = saved(&app); + for set in [ + json!({"field": "__savePresetAs", "value": "Proofs"}), + json!({"fields": [{"field": "__savePresetAs", "value": "Proofs"}], "action": "confirm"}), + ] { + let before = dialog_fields(&app); + let r = request(&mut app, &tx, "ui.dialog.set", set.clone()); + assert_eq!(r["error"], format!("the `{kind}` dialog cannot set protected field `__savePresetAs`"), "{set}: {r}"); + assert_eq!(dialog_fields(&app), before, "{set}: no field changes and the dialog stays open"); + } + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "nosuch", "value": true})); + assert!(!r["error"].as_str().unwrap_or_default().contains("__savePresetAs"), "{kind}: {r}"); + assert_eq!(saved(&app), presets, "{kind}: no preset saved"); + // Save Preset… adds the field; the name can then be typed and OK saves the preset. + app.ui.dialog.as_mut().unwrap().fields.insert("__savePresetAs".into(), json!("")); + let r = request(&mut app, &tx, "ui.dialog.set", json!({"field": "__savePresetAs", "value": "Proofs", "action": "confirm"})); + assert_eq!(r["result"]["result"]["name"], "Proofs", "{kind}: {r}"); + app.ui.dialog = None; + } + assert_eq!(saved(&app), (1, 1)); +} + /// The refusal of an OK on an install question automation asked. const ASKED: &str = "Automation asked to install this plug-in. To install it, choose Object › Plug-ins › Install Plug-in… yourself."; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0fdfbc8231..53ce5d35f9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -102,7 +102,7 @@ the two can still win that race. | `ui.click` / `ui.drag` | `{x, y, button?, count?, shift?, alt?, ctrl?, cmd?}` / `{x, y, toX, toY, steps?, count?, button?, shift?, alt?, ctrl?, cmd?}` | egui pointer input; see synthetic input budgets above | | `ui.wheel` | `{x, y, dy?, dx?, unit?: "line"\|"point", shift?, alt?, cmd?}` | a mouse wheel turn over screen point (x, y): `dy` notches up (+) or down, `dx` sideways. Over the canvas the wheel scrolls, Cmd-wheel (Ctrl on Windows and Linux) scrolls sideways and Alt-wheel (Option on the Mac) zooms about the pointer (with the `ctrlWheelScrollsSideways` preference off, Cmd-wheel zooms too); with the `zoomWithMouseWheel` preference the wheel and Alt-wheel zoom about the pointer, Shift-wheel scrolls up and down and Cmd-wheel (Ctrl on Windows and Linux) sideways. Over a focused numeric field (click it first) each notch steps its value as Up/Down do (Shift: ten, Cmd/Ctrl: a tenth) and the panel stays put; over anything else in a panel the wheel scrolls it. Over the canvas, the wheel preferences in `docs/mcp.md` change what these keys do | | `ui.set` | `{brightness?, panel?, rulers?, outline?, grid?, smartGuides?, boundingBox?, controlBar?, imageTracePreview?}` | `outline`: View › Outline for the active document only (each document has its own, a document opens in Preview, and `ui.inspect` shows it as `view.outline`; an error without a document). `imageTracePreview`: the Image Trace panel's Preview (`ui.inspect` shows it as `ui.image_trace_preview`) | -| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | +| `ui.dialog.set` / `.confirm` / `.cancel` | `{field, value, action?}` or `{fields: [{field, value}…], action?}` | fill and submit the open dialog. `ui.dialog.set` takes the fields the dialog has (`ui.inspect`) other than its `__` fields, the `__` fields that are controls of the dialog (such as `__section` and `__allArtboards` in Save PDF, `__constrain` in Transform Each and the shape dialogs, and `__search` and `__category` in Preferences; Save PDF's and Print's `__savePresetAs`, the preset name, only while Save Preset… asks for it, since OK then saves a preset), `discard` on a dialog with a discard button, `preview` on one with a live preview, the fields that the dialog reads but adds only when a control changes (such as `searchFolder`, or `copy` in the Transform dialogs), and the fields it passes to the command it runs: every parameter of the `command` dialog's command (`ui.paramDialog`), and the `textureImage` that Load Texture… sets in the Glass and Texturizer effects; any other field is an error that lists the dialog's fields, and the dialog stays as it was. Any other `__` field, held or not, holds what the dialog's OK acts on (such as the `__command` and `__params` of a `confirm` or `command` dialog) or the dialog's own state: setting it is the error "the `` dialog cannot set protected field ``", and the dialog stays as it was. `fields` sets the list (at most 256 items) in order (a missing `value` is `null`) and checks every item first: when one is refused, the call is an error and no field changes. `action: "confirm"` or `"cancel"` on `ui.dialog.set` then confirms or cancels the same dialog in the same request, as `ui.dialog.confirm` and `ui.dialog.cancel` do, and the reply is `{dialog, result}`: the dialog after the fields were set and the reply to confirm (`null` for cancel); any other `action` is an error and no field changes | | `ui.screenshot` | `{path?, data?}` | capture the window (PNG), written to `path`; `data: true` sends it back as `pngBase64` too. The inline PNG is capped at 64 MiB: with a `path` the file is still written and `pngBase64` is omitted when the image is larger, while a path-less `data: true` request fails if either the raw RGBA image or the encoded PNG exceeds the cap. Needs a presented frame: with the screen locked or the window minimized/covered it fails after ~8 s with an explanatory error | | `ui.render` | `{path?, scale?, artboard?, data?, traceViews?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first; `traceViews: true`: Image Trace objects draw in their View, as on the canvas, instead of their tracing result): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | | `ui.render` | `{path?, scale?, artboard?, data?}` | render an artboard headlessly (PNG with the pixels of `app.export {format: "png", background: "white"}` at the same scale; `artboard`: its 0-based index, default the first): written to `path`, else (or with `data: true` as well) sent back as `pngBase64` | From 6ccb7c907756400aa6c360edaa350834716ecac7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:36:03 -0800 Subject: [PATCH 05/33] 3D and Materials: Expand as Wireframes expands Revolve (Classic) and Rotate (Classic) effect.expandAsWireframes returned "draws no faces" for an object with Revolve (Classic). It now takes the faces of Revolve (Classic) with that effect's own options, and Rotate (Classic) is expanded as Rotate is: every fill and stroke turned as one plane. Docs: docs/mcp.md, docs/three-d.md. --- crates/effects/src/revolve.rs | 24 ++++++++------ crates/effects/src/solids/wireframe.rs | 14 ++++----- crates/effects/src/solids/wireframe/tests.rs | 33 ++++++++++++++++++++ crates/engine/src/cmd/wireframe.rs | 2 +- crates/engine/src/cmd/wireframe/tests.rs | 10 +++++- docs/mcp.md | 4 +-- docs/three-d.md | 2 +- 7 files changed, 67 insertions(+), 22 deletions(-) diff --git a/crates/effects/src/revolve.rs b/crates/effects/src/revolve.rs index 9d31e8372d..8d05ab38ed 100644 --- a/crates/effects/src/revolve.rs +++ b/crates/effects/src/revolve.rs @@ -507,9 +507,9 @@ pub(crate) fn revolve_meshes(n: &Node, total: &mut usize, limit: usize) -> Resul Ok(out) } -/// The outline of every face [`revolve_art`] draws for `n` (its symbol instances, blends and clipping -/// groups already resolved), in document coordinates: with the effect on the object, the surface in -/// its top visible fill (else its stroke); with it on fills and strokes, one surface for each of +/// The outline of every face [`revolve_art`] draws for `n`'s Revolve or Revolve (Classic) (its symbol +/// instances, blends and clipping groups already resolved), in document coordinates: with the +/// effect on the object, the surface in its top visible fill (else its stroke); with it on fills and strokes, one surface for each of /// them, reshaped by the geometry effects after each one's Revolve; on a group or layer, one for /// each member, about one shared axis. pub(crate) fn revolve_face_paths(n: &Node) -> Result, String> { @@ -517,13 +517,17 @@ pub(crate) fn revolve_face_paths(n: &Node) -> Result, String> { Ok(vectorcraft_three_d::revolve(path, b, options)?.iter().map(vectorcraft_three_d::Face::path).collect()) }; if is_container(n) { - let index = - n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE).ok_or("a 3D effect on a group's fill or stroke draws nothing")?; + let index = n + .appearance + .effects + .iter() + .position(|e| e.visible && is_revolve(&e.id)) + .ok_or("a 3D effect on a group's fill or stroke draws nothing")?; let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let mut shapes = members(n, "Revolve")?; reshape_members(n, n.appearance.effects.get(..index).unwrap_or_default(), &mut shapes); let b = union_bounds(&shapes).ok_or("Revolve requires a group holding a shape with at least two anchors")?; - let options = shared_options(&shapes, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let options = shared_options(&shapes, fx_options(fx))?; let mut out = vec![]; for s in shapes.iter().filter(|s| surface_item(&s.items).is_some()) { out.extend(faces(&s.path, b, options)?); @@ -532,24 +536,24 @@ pub(crate) fn revolve_face_paths(n: &Node) -> Result, String> { } let (path, _) = object_profile(n, "Revolve")?; let ctx = GeomContext::of(n); - if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && e.id == REVOLVE) { + if let Some(index) = n.appearance.effects.iter().position(|e| e.visible && is_revolve(&e.id)) { let Some(fx) = n.appearance.effects.get(index) else { return Ok(vec![]) }; let path = geometry(&path, n.appearance.effects.get(..index).unwrap_or_default(), &ctx); if surface_item(&solid_paints(n)).is_none() { return Err("the revolved object has no fill or stroke".into()); } let b = path.bounds().ok_or("Revolve requires a shape with at least two anchors")?; - return faces(&path, b, revolve_options(&merged_params(REVOLVE, &fx.params))); + return faces(&path, b, fx_options(fx)); } let path = geometry(&path, &n.appearance.effects, &ctx); let mut out = vec![]; for item in n.appearance.items.iter().filter(|i| crate::paints(i)) { - if let Some(index) = item.effects().iter().position(|e| e.visible && e.id == REVOLVE) + if let Some(index) = item.effects().iter().position(|e| e.visible && is_revolve(&e.id)) && let Some(fx) = item.effects().get(index) { let p = geometry(&path, item.effects().get(..index).unwrap_or_default(), &ctx.item(item)); let b = p.bounds().ok_or("Revolve requires a shape with at least two anchors")?; - let surface = faces(&p, b, revolve_options(&merged_params(REVOLVE, &fx.params)))?; + let surface = faces(&p, b, fx_options(fx))?; out.extend(crate::solids::wireframe::reshaped(surface, item.effects().get(index + 1..).unwrap_or_default(), &ctx)); } } diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index eb74546225..e2656222b3 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -7,8 +7,8 @@ use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; use super::{ - INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_three_d, label_of, members, object_profile, region, - reshape_members, resolve, solid, solid_paints, solid_parts, union_bounds, view_options, + INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile, + region, reshape_members, resolve, solid, solid_paints, solid_parts, union_bounds, view_options, }; use crate::{GeomContext, apply_geometry_with, is_geometry}; @@ -21,8 +21,8 @@ const GRID: f64 = 1.0 / 1024.0; const NO_EFFECT: &str = "the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate)"; -/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Revolve, Inflate -/// or Rotate), in document coordinates: the edges of every face the effect draws for the object as +/// The wireframe of `n`'s 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D +/// (Classic) forms), in document coordinates: the edges of every face the effect draws for the object as /// it is turned and projected, each edge once. Edges that meet end to end are joined into one path; /// a run that comes back to where it started is closed. A curved edge stays a curve. The geometry /// effects after the object's 3D effect reshape the wireframe as they reshape the drawn art. On a @@ -108,8 +108,8 @@ fn solid_face_paths(n: &Node) -> Result, String> { Ok(out) } -/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: -/// Rotate turns every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's +/// The outlines of the facets effect `fx` builds from `shapes`, as `art_for` builds them: Rotate and +/// Rotate (Classic) turn every fill and stroke; Extrude & Bevel and Inflate build a solid from each shape's /// top fill and from the outline of each stroke. A stroke whose solid is past the limits is left out, /// as it is left out of the drawn art. fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> { @@ -117,7 +117,7 @@ fn facet_paths(fx: &Effect, shapes: &[Profile]) -> Result, String> let b = union_bounds(shapes).ok_or_else(|| format!("{label} requires a shape with at least two anchors"))?; let p = crate::merged_params(&fx.id, &fx.params); let mut out = vec![]; - if fx.id == ROTATE { + if is_plane(&fx.id) { for s in shapes { for item in &s.items { let (area, rule) = region(&s.path, s.rule, item); diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index 980e67bbeb..8498885776 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -124,6 +124,39 @@ fn revolve_inflate_and_rotate_expand_too() { assert_eq!(segments(&plane).len(), 4); } +/// Revolve (Classic) and Rotate (Classic) expand to the edges of the faces they draw, in the same +/// place. +#[test] +fn revolve_classic_and_rotate_classic_expand_too() { + let n = solid_square(crate::CLASSIC_REVOLVE, json!({})); + let wire = three_d_wireframe_in(None, &n).unwrap(); + assert!(!wire.is_empty()); + let art = crate::revolve_art(&n).unwrap(); + let (w, a) = (bounds(&wire), bounds(&face_paths(&art))); + for (x, y) in [(w.x0, a.x0), (w.y0, a.y0), (w.x1, a.x1), (w.y1, a.y1)] { + assert!((x - y).abs() < 1e-6, "{w:?} {a:?}"); + } + // On a fill, with a geometry effect after it. + let mut n = solid_square(crate::CLASSIC_REVOLVE, json!({})); + let fx = n.appearance.effects.remove(0); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(fx.clone()); + } + } + let plain = bounds(&three_d_wireframe_in(None, &n).unwrap()); + for item in &mut n.appearance.items { + if matches!(item, AppearanceItem::Fill(_)) { + item.effects_mut().push(crate::new_effect("distort.transform", &json!({"moveH": 50.0})).unwrap()); + } + } + let moved = bounds(&three_d_wireframe_in(None, &n).unwrap()); + assert!((moved.x0 - plain.x0 - 50.0).abs() < 1e-6 && (moved.y0 - plain.y0).abs() < 1e-6, "{plain:?} {moved:?}"); + // Rotate (Classic) is one flat face: its outline. + let plane = three_d_wireframe_in(None, &solid_square(super::super::CLASSIC_ROTATE, json!({}))).unwrap(); + assert_eq!(segments(&plane).len(), 4); +} + /// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. #[test] fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { diff --git a/crates/engine/src/cmd/wireframe.rs b/crates/engine/src/cmd/wireframe.rs index 27a35a793b..42dfaf8a33 100644 --- a/crates/engine/src/cmd/wireframe.rs +++ b/crates/engine/src/cmd/wireframe.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Expand as Wireframes", [], None, - "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Extrude & Bevel (Classic), Revolve, Inflate or Rotate, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", + "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", has_doc, expand_as_wireframes )] diff --git a/crates/engine/src/cmd/wireframe/tests.rs b/crates/engine/src/cmd/wireframe/tests.rs index 67e338b781..ce881982cd 100644 --- a/crates/engine/src/cmd/wireframe/tests.rs +++ b/crates/engine/src/cmd/wireframe/tests.rs @@ -27,7 +27,15 @@ fn run(s: &mut Session, p: Value) -> crate::Result { #[test] fn a_3d_object_becomes_a_selected_group_of_stroked_edges_in_one_undo_step() { - for effect in ["threeD.extrude", "threeD.classicExtrude", "threeD.revolve", "threeD.inflate", "threeD.rotate"] { + for effect in [ + "threeD.extrude", + "threeD.classicExtrude", + "threeD.revolve", + "threeD.classicRevolve", + "threeD.inflate", + "threeD.rotate", + "threeD.classicRotate", + ] { let (mut s, id) = setup(Some(effect)); std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).node_mut(id).unwrap().name = Some("Box".into()); let before = s.doc().unwrap().doc.clone(); diff --git a/docs/mcp.md b/docs/mcp.md index a1d1f60c2f..10e3905982 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3228,8 +3228,8 @@ checked as that effect's. It is one undo step. Any other `threeDType` value, or ## Expand as Wireframes `effect.expandAsWireframes {ids?}` (**Window › 3D and Materials** › Quick Actions › Expand as Wireframes) replaces -each selected object, or each object in `ids`, that has a visible 3D effect (Extrude & Bevel, Extrude & Bevel -(Classic), Revolve, Inflate or Rotate, on the object or on its fills and strokes) with a group of paths: the edges of +each selected object, or each object in `ids`, that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, +Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws for the object as it is turned and projected now ([three-d.md](three-d.md#3d-and-materials-panel)). Each edge appears once; edges that meet end to end form one path, closed where it comes back to its start, and curved edges stay curves. Geometry effects after a 3D effect, diff --git a/docs/three-d.md b/docs/three-d.md index ca21b815e2..820bc1e805 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -52,7 +52,7 @@ pages describe it. - Each change is one undo step. Dragging a value or a slider previews it on the artboard and records one step when the pointer is released; a typed value is recorded when it is entered. Drawing the panel records nothing. - **Quick Actions › Expand as Wireframes** sits under the Object tab (under the first tab for Revolve and Rotate, - which have no Object tab). It replaces each selected object that has a 3D effect with a group of paths, the + which have no Object tab). It replaces each selected object that has a 3D effect, the 3D (Classic) effects included, with a group of paths, the edges of the faces the effect draws for the object as it is turned and projected now (`effect.expandAsWireframes`), as the public [Render 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/render-3d-vector-artwork.html) page describes for converting the wireframe into editable paths. Each edge appears once: edges that meet end to From ac79ae55ba055830d6a9372eb2071bba80a57795 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 05:52:39 -0800 Subject: [PATCH 06/33] 3D and Materials: Expand as Wireframes keeps a layer's ruler guides and reshapes each face - Expanding a layer removed its ruler guides with its members. The guides of the layer and of its sublayers now stay on the layer, after the edges. - Geometry effects after a 3D effect reshaped all the faces as one path, so Offset Path merged faces that touch. Each effect now reshapes each face on its own, about the bounds of all the faces, within one shared budget of anchors, as it reshapes the drawn surface. Docs: docs/mcp.md. --- crates/effects/src/solids/wireframe.rs | 34 ++++++++++++-------- crates/effects/src/solids/wireframe/tests.rs | 13 ++++++++ crates/engine/src/cmd/wireframe.rs | 27 ++++++++++++++-- crates/engine/src/cmd/wireframe/tests.rs | 20 ++++++++++++ docs/mcp.md | 2 +- 5 files changed, 80 insertions(+), 16 deletions(-) diff --git a/crates/effects/src/solids/wireframe.rs b/crates/effects/src/solids/wireframe.rs index e2656222b3..5f2275d8eb 100644 --- a/crates/effects/src/solids/wireframe.rs +++ b/crates/effects/src/solids/wireframe.rs @@ -1,8 +1,10 @@ //! Expand as Wireframes: the edges of the faces a 3D effect draws, as open and closed paths that //! can be edited on their own. use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; -use vectorcraft_doc::{AppearanceItem, Document, Effect, Node}; +use vectorcraft_doc::color::{Color, Paint}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId}; use vectorcraft_geom::{Anchor, CubicBez, PathData, Point, SubPath}; use vectorcraft_three_d::Facet; @@ -10,7 +12,7 @@ use super::{ INFLATE, Profile, ROTATE, facets, geometry, has_solid, inflate_options, is_container, is_plane, is_three_d, label_of, members, object_profile, region, reshape_members, resolve, solid, solid_paints, solid_parts, union_bounds, view_options, }; -use crate::{GeomContext, apply_geometry_with, is_geometry}; +use crate::{GeomContext, is_geometry}; /// The most distinct edges one object's wireframe may have. pub(crate) const MAX_WIRE_EDGES: usize = 1_000_000; @@ -50,7 +52,7 @@ pub fn three_d_wireframe_in(doc: Option<&Document>, n: &Node) -> Result, n: &Node) -> Result) -> Vec { +/// `faces` reshaped by the visible geometry effects after `n`'s own 3D effect ([`reshaped`]). +fn after_geometry(doc: Option<&Document>, n: &Node, faces: Vec) -> Vec { let fx = &n.appearance.effects; let Some(index) = fx.iter().position(|e| e.visible && is_three_d(&e.id)) else { return faces }; - reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext::of(n)) + reshaped(faces, fx.get(index + 1..).unwrap_or_default(), &GeomContext { doc, ..GeomContext::of(n) }) } -/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), -/// which act on the faces as a whole, about their bounds, as they act on the drawn surface. +/// `faces` reshaped by the visible geometry effects in `later` (the effects after a 3D effect), as +/// they reshape the faces of the drawn surface ([`crate::reshape::reshape_leaves`]): each effect +/// reshapes each face on its own, about the bounds all the faces have before it, and the faces keep +/// to one budget of anchors together. `ctx` gives the object's id, the seed of a random Transform, +/// and the document. pub(crate) fn reshaped(faces: Vec, later: &[Effect], ctx: &GeomContext) -> Vec { - let after: Vec = later.iter().filter(|e| e.visible && is_geometry(&e.id)).cloned().collect(); + let after: Vec<&Effect> = later.iter().filter(|e| e.visible && is_geometry(&e.id)).collect(); if after.is_empty() { return faces; } - let joined = PathData::new(faces.into_iter().flat_map(|f| f.subpaths).collect()); - let Some(bounds) = joined.bounds() else { return vec![joined] }; - vec![apply_geometry_with(&after, &joined, bounds, ctx)] + let id = NodeId(ctx.seed); + let fill = Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut art = Node::group(id, faces.into_iter().map(|f| Arc::new(Node::path(id, f, fill.clone()))).collect()); + crate::reshape::reshape_leaves(&mut art, &after, later, ctx.doc); + let mut out = vec![]; + art.walk(&mut |c| out.extend(c.path_data().cloned())); + out } /// The outline of every face [`super::solid_art`] draws for `n` (already resolved): with the effect diff --git a/crates/effects/src/solids/wireframe/tests.rs b/crates/effects/src/solids/wireframe/tests.rs index 8498885776..158e42d98f 100644 --- a/crates/effects/src/solids/wireframe/tests.rs +++ b/crates/effects/src/solids/wireframe/tests.rs @@ -157,6 +157,19 @@ fn revolve_classic_and_rotate_classic_expand_too() { assert_eq!(segments(&plane).len(), 4); } +/// The geometry effects after a 3D effect reshape each face on its own, as they reshape each face +/// of the drawn surface: two faces that touch stay two outlines. +#[test] +fn later_geometry_effects_reshape_each_face_on_its_own() { + let n = solid_square(super::super::EXTRUDE, json!({})); + let fx = [crate::new_effect("path.offsetPath", &json!({"offset": 1.0})).unwrap()]; + let out = reshaped(vec![square(0.0, 0.0, 10.0), square(10.0, 0.0, 10.0)], &fx, &GeomContext::of(&n)); + assert_eq!(out.len(), 2, "{out:?}"); + let (a, b) = (out[0].bounds().unwrap(), out[1].bounds().unwrap()); + assert!((a.x0 + 1.0).abs() < 1e-3 && (a.x1 - 11.0).abs() < 1e-3, "{a:?}"); + assert!((b.x0 - 9.0).abs() < 1e-3 && (b.x1 - 21.0).abs() < 1e-3, "{b:?}"); +} + /// A geometry effect after a fill's 3D effect moves that fill's edges, as it moves its drawn surface. #[test] fn a_geometry_effect_after_a_fill_s_3d_effect_reshapes_its_edges() { diff --git a/crates/engine/src/cmd/wireframe.rs b/crates/engine/src/cmd/wireframe.rs index 42dfaf8a33..ccd82dd0c3 100644 --- a/crates/engine/src/cmd/wireframe.rs +++ b/crates/engine/src/cmd/wireframe.rs @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Expand as Wireframes", [], None, - "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", + "{ids?: [..] (default: the selected objects)} replace each object that has a visible 3D effect (Extrude & Bevel, Revolve, Inflate, Rotate or one of their 3D (Classic) forms, on the object or on its fills and strokes) with a group of paths: the edges of the faces the effect draws, as the object is turned and projected now, each edge once (edges that meet end to end make one path, closed where it comes back to its start; curved edges stay curves; geometry effects after the 3D effect, on the object or on a fill or stroke, reshape them too), stroked 0.5 pt black with round joins and no fill (VectorCraft's own); the group takes the object's place, id, name, opacity, blending mode, opacity mask, attributes, slice and text wrap and is selected (a layer stays a layer holding the edges, which are selected, and its ruler guides); objects without a visible 3D effect are left as they are; one undo step. An error, with nothing changed, when no object is selected or given, when none has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges → {ids}", has_doc, expand_as_wireframes )] @@ -38,6 +38,25 @@ fn wire_appearance() -> Appearance { Appearance { items: vec![AppearanceItem::Stroke(stroke)], ..Default::default() } } +/// The ruler guides of layer `n` and then those of the sublayers inside it, in order, added to +/// `out`. A guide from a hidden or locked sublayer, or from one inside a hidden or locked group or +/// sublayer, is hidden or locked itself. +fn ruler_guides(n: &Node, hidden: bool, locked: bool, out: &mut Vec>) { + let Some(children) = n.children() else { return }; + for c in children.iter().filter(|c| c.is_ruler_guide()) { + let mut g = c.clone(); + if hidden || locked { + let g = Arc::make_mut(&mut g); + g.visible &= !hidden; + g.locked |= locked; + } + out.push(g); + } + for c in children.iter().filter(|c| !c.is_ruler_guide()) { + ruler_guides(c, hidden || !c.visible, locked || c.locked, out); + } +} + fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result { let roots = checked_ids_or_selection(s, p, C)?; if roots.is_empty() { @@ -70,9 +89,13 @@ fn expand_as_wireframes(s: &mut Session, p: &Value) -> Result { let Some(source) = d.node(id) else { continue }; if matches!(source.kind, NodeKind::Layer { .. }) { // A layer stays a layer: its members become the edges, and its 3D effect is removed. + // Its ruler guides and those of its sublayers are not art: they stay, after the edges. let mut layer = source.clone(); - let children: Vec> = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); + let mut guides = vec![]; + ruler_guides(source, false, false, &mut guides); + let mut children: Vec> = wire.into_iter().map(|path| Arc::new(Node::path(d.alloc_id(), path, wire_appearance()))).collect(); selected.extend(children.iter().map(|c| c.id)); + children.extend(guides); if let Some(members) = layer.children_mut() { *members = children; } diff --git a/crates/engine/src/cmd/wireframe/tests.rs b/crates/engine/src/cmd/wireframe/tests.rs index ce881982cd..ab51c81282 100644 --- a/crates/engine/src/cmd/wireframe/tests.rs +++ b/crates/engine/src/cmd/wireframe/tests.rs @@ -92,6 +92,26 @@ fn a_layer_with_a_3d_effect_stays_a_layer_holding_the_edges() { assert_eq!(undo_len(&s), history + 1); } +/// A layer's ruler guides are not art: they stay on the layer, after the edges, and are not selected. +#[test] +fn a_layer_keeps_its_ruler_guides() { + let (mut s, _) = setup(None); + let layer = s.doc().unwrap().doc.layers[0].id; + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + let guides = |s: &Session| -> Vec { + s.doc().unwrap().doc.node(layer).unwrap().children().unwrap().iter().filter(|c| c.is_ruler_guide()).map(|c| c.id).collect() + }; + let before = guides(&s); + assert_eq!(before.len(), 1); + s.execute("effect.apply", &json!({"ids":[layer.0],"effect":"threeD.extrude","item":null,"params":{}})).unwrap(); + run(&mut s, json!({"ids":[layer.0]})).unwrap(); + assert_eq!(guides(&s), before); + let st = s.doc().unwrap(); + let children = st.doc.node(layer).unwrap().children().unwrap(); + assert!(children.len() > 1 && children.last().is_some_and(|c| c.is_ruler_guide())); + assert!(!st.selection.objects.is_empty() && st.selection.objects.iter().all(|id| !before.contains(id))); +} + /// The number of segments in the wireframe group `id`. fn segments(s: &Session, id: NodeId) -> usize { let st = s.doc().unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 10e3905982..7457e6faa3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3237,7 +3237,7 @@ on the object or on a fill or stroke, reshape its edges as they reshape the draw black stroke with round joins and no fill (VectorCraft's own choice). The group keeps the object's place, id, name, visibility, lock, opacity, blending mode, knockout, opacity mask, attributes, slice and text wrap, and the groups are selected. -A layer in `ids` stays a layer: its members are replaced by the edges, which are selected. Objects without a visible 3D effect do not change. It is one undo step and +A layer in `ids` stays a layer: its members are replaced by the edges, which are selected, and its ruler guides stay. Objects without a visible 3D effect do not change. It is one undo step and returns `{ids}`, the groups. It is an error, and nothing changes, when nothing is selected or given, when no object has a visible 3D effect, when an object's solid can't be built or the canvas draws its source art in its place, or when one object's wireframe has more than 1,000,000 edges. From e29f5e51a0e14719b99849c69c6b38e7b7814793 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:00:40 -0800 Subject: [PATCH 07/33] New Document: each preset category starts documents from its own profile Each built-in category (Mobile, Web, Print, Film & Video, Art & Illustration, Branding, Social) has a New Document profile, a native document in the New Document Profiles folder next to the preferences. file.new copies the profile's swatches, graphic styles, brushes, symbols, patterns, character and paragraph styles, rulers, Document Setup options, assigned color profiles and print settings into the new document. The preset's size, units, artboards, bleed, background, color mode and resolution still apply, and the profile's art and layers are not copied. - file.newProfiles lists the profiles, file.newProfiles.edit opens one as a document (writing the shipped profile first), and file.newProfiles.reset deletes its file. file.new takes `profile`. - Saved and Recent presets keep the profile of the preset they came from. - A profile that cannot be read, is larger than 64 MiB or is not a native document leaves the defaults, and file.new reports it in profileError. - New Document has a Manage Profiles pop-up with Edit and Reset. Docs: docs/mcp.md, docs/target-app-parity.md. --- apps/vectorcraft-cli/src/main.rs | 4 +- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/prefs_dir.rs | 8 + crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 303 ++++++++++++++++++++- crates/engine/src/lib.rs | 3 + crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/newdoc.rs | 170 ++++++++++++ crates/ui-egui/src/dialogs.rs | 1 + crates/ui-egui/src/dialogs/new_document.rs | 138 +++++++++- docs/mcp.md | 40 +++ docs/target-app-parity.md | 1 + 12 files changed, 655 insertions(+), 17 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 57ab103590..9a92efb37e 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,9 +238,11 @@ 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), 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, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`). `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and +/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); prefs_dir::attach_plugin_store(&mut h.session); diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 33e03b1f72..d6baab7e2b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -476,6 +476,7 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_plugin_store(&mut session); // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); + prefs_dir::attach_new_doc_profiles(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 96e09f5e78..775ef73841 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -65,6 +65,14 @@ pub fn attach_scripts_dir(session: &mut vectorcraft_engine::Session) { } } +/// Have File › New start each category's documents from its profile in the `New Document +/// Profiles` folder, which `file.newProfiles.edit` makes. +pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("New Document Profiles") { + session.attach_new_doc_profiles(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 108b8593c9..0713273f2c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792, units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index bd15d748ca..59bcb0614a 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -1,10 +1,21 @@ //! File → New: the settings `file.new` takes, the New Document presets (generated in code, by //! category), the user's saved presets and the recently used sizes (both kept in the //! preferences), and the artboard grid layout shared with Rearrange All Artboards. +//! +//! New Document profiles: each built-in category has a profile, a native document in the +//! `New Document Profiles` folder next to the preferences ([`Session::attach_new_doc_profiles`]). +//! `file.new` starts a document of that category with the profile's swatches, graphic styles, +//! brushes, symbols, character and paragraph styles, rulers, document setup and print settings +//! ([`DocSettings::document_from_profile`]). The grid stays that of Preferences › Guides & Grid, +//! which applies to every open document. A category without a profile file starts with the +//! defaults, and a profile that can't be read leaves them in place and is reported in `file.new`'s +//! result. + +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_doc::{Artboard, Background, ColorMode, Document, Unit}; +use vectorcraft_doc::{Artboard, Background, ColorMode, Document, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, str_param, switch_or}; @@ -38,6 +49,33 @@ pub fn specs() -> Vec { |s| if s.prefs.new_doc_presets.is_empty() { Err("no saved presets".into()) } else { Ok(()) }, delete ), + cmd!( + query "file.newProfiles", + "New Document Profiles", + [], + None, + "{} the New Document profiles, one per built-in category of file.newPresets: native documents in the New Document Profiles folder next to the preferences, whose swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and mode, transparency grid, document setup (other than bleed, background and Align New Objects to Pixel Grid), assigned color profiles, Document Raster Effects Settings (other than the resolution) and print settings a new document of that category starts with → {profiles: [{name, customized?: a profile file exists (else the shipped profile, today's defaults, applies), path?; both left out for a request that may not read the folder}], folder?: the folder (none in runs without preferences and on the web)}", + always, + list_profiles + ), + cmd!( + "file.newProfiles.edit", + "Edit Profile", + [], + None, + "{name: a category of file.newPresets} open the category's New Document profile as a document to edit (File › Save keeps the changes for the next file.new); a category without a profile file gets the shipped profile written first → document.open's result", + always, + edit_profile + ), + cmd!( + "file.newProfiles.reset", + "Reset Profile", + [], + None, + "{name: a category of file.newPresets} delete the category's profile file, so the shipped profile (today's defaults) applies again; an open copy of it stays open → {name, reset: whether a file was deleted}", + always, + reset_profile + ), ] } @@ -148,6 +186,11 @@ pub struct DocSettings { /// on in the Mobile and Web presets, off in the others and in a saved or Recent preset from /// before it. pub align_new_objects_to_pixel_grid: bool, + /// The New Document profile the document starts from (a built-in category's name): the + /// category of a built-in preset, kept by the saved and Recent presets made from it; `None`: + /// the defaults. + #[serde(skip_serializing_if = "Option::is_none")] + pub profile: Option, } impl Default for DocSettings { @@ -168,6 +211,7 @@ impl Default for DocSettings { raster_effects_ppi: 72.0, preview_mode: PreviewMode::Default, align_new_objects_to_pixel_grid: false, + profile: None, } } } @@ -217,6 +261,7 @@ impl DocSettings { "rasterEffectsPpi": self.raster_effects_ppi, "previewMode": self.preview_mode.id(), "alignNewObjectsToPixelGrid": self.align_new_objects_to_pixel_grid, + "profile": self.profile, }) } @@ -280,6 +325,11 @@ impl DocSettings { self.preview_mode = m.as_str().and_then(PreviewMode::parse).ok_or_else(|| bad(cmd, "previewMode must be default, pixel or overprint"))?; } self.align_new_objects_to_pixel_grid = switch_or(p, "alignNewObjectsToPixelGrid", self.align_new_objects_to_pixel_grid, cmd)?; + match p.get("profile") { + None => {} + Some(Value::Null) => self.profile = None, + Some(v) => self.profile = Some(profile_name(v, cmd)?.to_string()), + } let extent = self.boards().iter().fold(Rect::ZERO, |a, r| a.union(*r)); if extent.width().max(extent.height()) + self.bleed.iter().fold(0.0f64, |a, b| a.max(*b)) * 2.0 > crate::MAX_COORD { return Err(bad(cmd, "the artboards don't fit on the canvas: fewer artboards, less spacing or a smaller size")); @@ -357,6 +407,101 @@ impl DocSettings { .collect(); d } + + /// The new document started from New Document profile `profile`: [`Self::document`] with the + /// profile's swatches, swatch groups, graphic styles, brushes, symbols, patterns and the images + /// they use, character and paragraph styles, composite fonts, SVG filters, graph designs, ruler + /// origin and mode, transparency grid, document setup (bleed, background and Align New Objects + /// to Pixel Grid stay these settings'), assigned color profiles, raster effects settings (the + /// resolution stays these settings') and print settings, in these settings' color mode (the + /// profile's colors converted as Document Color Mode converts them). The profile's art, + /// layers and artboards are left out: the document has one empty layer. + pub fn document_from_profile(&self, mut profile: Document) -> Document { + if profile.color_mode != self.color_mode { + super::colormgmt::set_color_mode(&mut profile, self.color_mode, true, None, super::colormgmt::Grays::Profile); + } + let profile_next_id = profile.peek_next_id(); + let mut d = self.document(); + d.swatches = profile.swatches; + d.swatch_groups = profile.swatch_groups; + d.graphic_styles = profile.graphic_styles; + d.char_styles = profile.char_styles; + d.para_styles = profile.para_styles; + d.composite_fonts = profile.composite_fonts; + d.symbols = profile.symbols; + d.graph_designs = profile.graph_designs; + d.patterns = profile.patterns; + d.images = profile.images; + d.svg_filters = profile.svg_filters; + d.spot_use_lab = profile.spot_use_lab; + d.ruler_origin = profile.ruler_origin; + d.rulers = profile.rulers; + d.artboard_ruler_origins = profile.artboard_ruler_origins.into_iter().filter(|(id, _)| d.artboards.iter().any(|a| a.id == *id)).collect(); + d.transparency_grid = profile.transparency_grid; + d.print_setup = profile.print_setup; + d.color_profiles = profile.color_profiles; + // The resolution stays the preset's (raster_effects_ppi); the other raster effects settings + // are the profile's. + d.raster_effects = profile.raster_effects; + let setup = std::mem::replace(&mut d.setup, profile.setup); + d.setup.bleed = setup.bleed; + d.setup.background = setup.background; + d.setup.align_new_objects_to_pixel_grid = setup.align_new_objects_to_pixel_grid; + if let Some(brushes) = profile.unknown.get("brushes") { + d.unknown.insert("brushes".into(), brushes.clone()); + } + // Symbol, pattern and graph design art keeps the profile's ids, which a damaged file can + // have above its counter: the counter goes past all of them, as it does for a loaded + // document's layers, before the new layer takes an id. + d.raise_next_id(profile_next_id); + d.layers = d + .symbols + .iter() + .map(|s| s.art.clone()) + .chain(d.graph_designs.iter().map(|g| g.art.clone())) + .chain(d.patterns.iter().flat_map(|p| p.art.iter().cloned())) + .collect(); + d.fix_next_id(); + let layer = d.alloc_id(); + d.layers = vec![Arc::new(Node::layer(layer, "Layer 1", LayerColor::Preset(0)))]; + // Images only the profile's art used stay behind: an image is kept when an object of the new + // document names it in its `key`, as a native save keeps only the images its objects name. + let images = std::mem::take(&mut d.images); + if !images.is_empty() { + d.images = match serde_json::to_value(&d) { + Ok(v) => { + let used = image_keys(&v); + images.into_iter().filter(|(k, _)| used.contains(k.as_str())).collect() + } + Err(_) => images, + }; + } + d + } +} + +/// The string values of every `key` member at any depth of `v`, which name the images a document's +/// objects use, collected in one pass. +fn image_keys(v: &Value) -> std::collections::HashSet<&str> { + let mut keys = std::collections::HashSet::new(); + let mut stack = vec![v]; + while let Some(v) = stack.pop() { + match v { + Value::Object(m) => { + for (k, v) in m { + match v.as_str() { + Some(s) if k == "key" => { + keys.insert(s); + } + _ => stack.push(v), + } + } + } + Value::Array(a) => stack.extend(a), + _ => {} + } + } + keys } /// Largest artboard side `file.new` accepts, points. @@ -573,6 +718,7 @@ fn builtin(c: &Category, general: Unit) -> impl Iterator + ' color_mode, raster_effects_ppi: ppi, align_new_objects_to_pixel_grid: align, + profile: Some(category.into()), ..DocSettings::default() }) } @@ -623,7 +769,18 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } - let mut d = settings.document(); + let (profile, profile_error) = match settings.profile.as_deref() { + Some(name) => match s.read_profile(name) { + Ok(p) => (p, None), + Err(e) => (None, Some(e)), + }, + None => (None, None), + }; + let applied = profile.is_some(); + let mut d = match profile { + Some(p) => settings.document_from_profile(p), + None => settings.document(), + }; d.grid = s.prefs.grid(); d.title = match str_param(p, "name").or(str_param(p, "title")).map(str::trim).filter(|t| !t.is_empty()) { // New Document offers the next untitled name: taking it uses it up. @@ -639,7 +796,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { s.execute("view.overprintPreview", &json!({ "on": true }))?; } remember(s, &settings); - Ok(json!({ "index": i, "previewMode": settings.preview_mode.id() })) + let mut out = json!({ "index": i, "previewMode": settings.preview_mode.id() }); + if applied { + out["profile"] = json!(settings.profile); + } + if let Some(e) = profile_error { + out["profileError"] = json!({ "profile": settings.profile, "reason": e }); + } + Ok(out) } /// Put `settings` first in Recent (one entry per size and units). @@ -693,3 +857,136 @@ fn delete(s: &mut Session, p: &Value) -> Result { let i = saved.iter().position(|q| q.name.eq_ignore_ascii_case(name)).ok_or_else(|| bad(C, format!("no saved preset called `{name}`")))?; Ok(json!({ "deleted": saved.remove(i).name })) } + +/// The largest New Document profile file `file.new` reads, bytes (VectorCraft's own limit); a +/// larger one is reported and the document starts with the defaults. +pub const MAX_PROFILE_BYTES: u64 = 64 << 20; + +/// The New Document profiles' names: the built-in categories, in tab order. +pub fn profile_names() -> impl Iterator { + CATEGORIES.iter().map(|c| c.0) +} + +/// The profile `v` names (a built-in category, any case). +fn profile_name(v: &Value, cmd: &str) -> Result<&'static str> { + let name = v.as_str().map(str::trim).unwrap_or_default(); + profile_names().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| { + let shown = v.as_str().map_or_else(|| v.to_string(), str::to_string); + bad(cmd, format!("no New Document profile called `{shown}` ({})", profile_names().collect::>().join(", "))) + }) +} + +impl Session { + /// Keep the New Document profiles in the folder `dir` (`New Document Profiles` next to the + /// preferences). The folder is made when a profile is first edited. + pub fn attach_new_doc_profiles(&mut self, dir: std::path::PathBuf) { + self.new_doc_profile_dir = Some(dir); + } + + /// The New Document profiles' folder ([`Session::attach_new_doc_profiles`]); none on the web. + pub fn new_doc_profile_dir(&self) -> Option<&std::path::Path> { + self.new_doc_profile_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + + /// The file of profile `name`, whether or not it exists. + fn profile_path(&self, name: &str) -> Option { + Some(self.new_doc_profile_dir()?.join(format!("{name}.{}", vectorcraft_format::EXTENSION))) + } + + /// Whether profile `name` has a file, which `file.newProfiles.reset` deletes. + pub fn new_doc_profile_customized(&self, name: &str) -> bool { + self.profile_path(name).is_some_and(|p| p.is_file()) + } + + /// Profile `name`'s document: `None` when it has no file (the shipped profile, the defaults), + /// the reason when the request being served may not read it, or its file can't be read, is + /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + fn read_profile(&self, name: &str) -> std::result::Result, String> { + let Some(path) = self.profile_path(name) else { return Ok(None) }; + // Checked before the file is looked for, so a request that may not read the folder learns + // nothing of its files. + crate::file_access::check_read(&path.to_string_lossy())?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&path.to_string_lossy())?; + let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let mut doc = vectorcraft_format::load(&bytes).map_err(|e| e.to_string())?; + // Linked images in its symbols, patterns and brushes are read from their files, as placing + // a document reads them. + super::links::resolve(&mut doc, super::links::LinkBase::file(Some(&path.to_string_lossy())), false, false); + Ok(Some(doc)) + } +} + +/// The shipped profile of category `name`: the defaults, as a document of the category's first +/// preset. +fn shipped_profile(s: &Session, name: &str) -> Document { + let first = CATEGORIES.iter().find(|c| c.0 == name).and_then(|c| builtin(c, s.default_units()).next()); + let mut d = first.unwrap_or_default().document(); + d.title = name.to_string(); + d +} + +/// `path` when the request being served may read it. +fn shown(path: &std::path::Path) -> Option { + let path = path.to_string_lossy().to_string(); + crate::file_access::check_read(&path).is_ok().then_some(path) +} + +fn list_profiles(s: &mut Session, _: &Value) -> Result { + let profiles: Vec = profile_names() + .map(|name| { + let mut v = json!({ "name": name }); + match s.profile_path(name) { + // A request that may not read the folder learns nothing of its files. + Some(path) => { + if let Some(p) = shown(&path) { + v["customized"] = json!(path.is_file()); + v["path"] = json!(p); + } + } + None => v["customized"] = json!(false), + } + v + }) + .collect(); + Ok(json!({ "profiles": profiles, "folder": s.new_doc_profile_dir().and_then(shown) })) +} + +/// The file of profile `name` for `cmd` to change, checked against the request's write access. +fn writable_profile(s: &Session, name: &str, cmd: &str) -> Result { + let path = s.profile_path(name).ok_or_else(|| bad(cmd, "New Document profiles need the preferences folder, which this run doesn't have"))?; + crate::file_access::check_write(&path.to_string_lossy()).map_err(super::EngineError::Other)?; + Ok(path) +} + +fn edit_profile(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.edit"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + // document.open reads it next: a profile it can't open is not written either. + crate::file_access::check_read(&path).map_err(super::EngineError::Other)?; + if !file.exists() { + let bytes = vectorcraft_format::save(&shipped_profile(s, name), false); + file.parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::write(&file, bytes)) + .map_err(|e| super::EngineError::Other(format!("{path}: {e}")))?; + } + s.execute("document.open", &json!({ "path": path })) +} + +fn reset_profile(s: &mut Session, p: &Value) -> Result { + const C: &str = "file.newProfiles.reset"; + let name = profile_name(p.get("name").unwrap_or(&Value::Null), C)?; + let file = writable_profile(s, name, C)?; + let path = file.to_string_lossy().to_string(); + let reset = match std::fs::remove_file(&file) { + Ok(()) => true, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => false, + Err(e) => return Err(super::EngineError::Other(format!("{path}: {e}"))), + }; + Ok(json!({ "name": name, "reset": reset })) +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 745a6fb62c..5600276b5c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -171,6 +171,9 @@ pub struct Session { /// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder /// ([`Session::attach_scripts_dir`]). scripts_dir: Option, + /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, + /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). + new_doc_profile_dir: Option, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 2d850fd44d..f55e2f1e25 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -87,6 +87,7 @@ impl Session { color_settings_file: None, plugin_dir: None, scripts_dir: None, + new_doc_profile_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 4bc58e5f6b..bf560156f2 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -455,3 +455,173 @@ fn rearrange_that_moves_no_artboard_records_no_undo_step() { assert_eq!(s.execute("artboard.rearrange", &p).unwrap(), json!({"artboards": 0, "rows": 1, "columns": 1})); assert_eq!(history(&s), before); } + +/// A session whose New Document profiles are in a fresh folder for test `name` (not made yet). +fn with_profiles(name: &str) -> (Session, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("vc-newdoc-profiles-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + (s, dir) +} + +fn swatch_names(s: &Session) -> Vec { + s.doc().unwrap().doc.swatches.iter().map(|w| w.name.clone()).collect() +} + +/// Edit the Print profile: Brand Red, the Brand Box style, the Badge and Logo symbols (Logo's art an +/// embedded image) and an image left on its layer, saved. +fn edit_print_profile(s: &mut Session, dir: &std::path::Path) { + // Edit writes the shipped profile and opens it. + s.execute("file.newProfiles.edit", &json!({"name": "print"})).unwrap(); + assert!(dir.join("Print.vectorcraft").is_file()); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + s.execute("swatch.new", &json!({"name": "Brand Red", "color": "#cc2200"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Brand Box"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Badge"})).unwrap(); + // One embedded image becomes a symbol's art, another stays on the profile's layer. + let png = |rgb: [u8; 3]| { + let mut out = vec![]; + image::RgbaImage::from_pixel(4, 4, image::Rgba([rgb[0], rgb[1], rgb[2], 255])) + .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png) + .unwrap(); + vectorcraft_format::base64_encode(&out) + }; + s.execute("file.place", &json!({"name": "red.png", "dataBase64": png([255, 0, 0]), "link": false})).unwrap(); + s.execute("symbol.new", &json!({"name": "Logo"})).unwrap(); + s.execute("file.place", &json!({"name": "blue.png", "dataBase64": png([0, 0, 255]), "link": false})).unwrap(); + assert_eq!(s.doc().unwrap().doc.images.len(), 2); + s.execute("document.save", &json!({})).unwrap(); + assert_eq!(s.execute("file.newProfiles", &json!({})).unwrap()["profiles"][2]["customized"], true); +} + +#[test] +fn an_edited_profile_starts_the_documents_of_its_category() { + let (mut s, dir) = with_profiles("edited"); + let listed = s.execute("file.newProfiles", &json!({})).unwrap(); + let names: Vec<&str> = listed["profiles"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["Mobile", "Web", "Print", "Film & Video", "Art & Illustration", "Branding", "Social"]); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p["customized"] == false), "{listed}"); + edit_print_profile(&mut s, &dir); + + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert_eq!(r["profile"], "Print", "{r}"); + assert!(swatch_names(&s).contains(&"Brand Red".to_string())); + let d = &s.doc().unwrap().doc; + assert!(d.graphic_styles.iter().any(|g| g.name == "Brand Box")); + let badge = d.symbols.iter().find(|y| y.name == "Badge").expect("the profile's symbol"); + assert!(d.symbols.iter().any(|y| y.name == "Logo")); + assert_eq!(d.images.len(), 1, "only the symbol's image comes along"); + // The profile's art stays behind: one empty layer, with an id the symbol's art doesn't use. + assert_eq!(d.layers.len(), 1); + assert!(d.layers[0].children().is_none_or(Vec::is_empty)); + let mut symbol_ids = vec![]; + badge.art.walk(&mut |n| symbol_ids.push(n.id)); + assert!(!symbol_ids.contains(&d.layers[0].id), "{symbol_ids:?}"); + assert_eq!(d.artboards[0].rect.width().round(), 595.0); + let red = d.swatches.iter().find(|w| w.name == "Brand Red").cloned().unwrap(); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Cmyk { .. }, .. }), "{:?}", red.paint); + // In RGB the profile's colors are converted, as Document Color Mode converts them. + s.execute("file.new", &json!({"preset": "A4", "colorMode": "rgb"})).unwrap(); + let red = s.doc().unwrap().doc.swatches.iter().find(|w| w.name == "Brand Red").cloned().expect("converted, not dropped"); + assert!(matches!(red.paint, vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. }), "{:?}", red.paint); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_profile_follows_the_preset_access_and_reset() { + let (mut s, dir) = with_profiles("choice"); + edit_print_profile(&mut s, &dir); + // A request that may not read the folder gets the defaults, and the reason; edit is refused + // before anything is written. + let elsewhere = dir.with_extension("elsewhere"); + std::fs::create_dir_all(&elsewhere).unwrap(); + let roots = crate::file_access::AutomationRoots::new(&[elsewhere.as_path()], &[dir.as_path()]).unwrap().unwrap(); + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "A4"}))).unwrap(); + assert!(r.get("profile").is_none() && r["profileError"]["profile"] == "Print", "{r}"); + assert!(!swatch_names(&s).contains(&"Brand Red".to_string())); + // Nothing tells such a request which profiles have files. + let r = crate::file_access::confine(Some(&roots), || s.execute("file.new", &json!({"preset": "Web 1920×1080"}))).unwrap(); + assert_eq!(r["profileError"]["profile"], "Web", "{r}"); + let listed = crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles", &json!({}))).unwrap(); + assert!(listed["profiles"].as_array().unwrap().iter().all(|p| p.get("customized").is_none() && p.get("path").is_none()), "{listed}"); + assert!(crate::file_access::confine(Some(&roots), || s.execute("file.newProfiles.edit", &json!({"name": "Web"}))).is_err()); + assert!(!dir.join("Web.vectorcraft").exists()); + let _ = std::fs::remove_dir_all(&elsewhere); + // A saved preset made from a Print preset keeps the profile. + s.execute("file.newPresets.save", &json!({"name": "Zine", "preset": "A5"})).unwrap(); + assert_eq!(presets(&mut s, "Saved")[0]["profile"], "Print"); + assert_eq!(s.execute("file.new", &json!({"preset": "Zine"})).unwrap()["profile"], "Print"); + + // Other categories, no preset and `profile: null` start with the defaults. + for p in [json!({"preset": "Web 1920×1080"}), json!({}), json!({"preset": "A4", "profile": null})] { + let r = s.execute("file.new", &p).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{p}: {r}"); + } + // `profile` picks one for any settings. + assert_eq!(s.execute("file.new", &json!({"width": 300, "height": 300, "profile": "PRINT"})).unwrap()["profile"], "Print"); + + // Reset deletes the file, once; the shipped profile applies again. + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": true})); + assert_eq!(s.execute("file.newProfiles.reset", &json!({"name": "Print"})).unwrap(), json!({"name": "Print", "reset": false})); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && !swatch_names(&s).contains(&"Brand Red".to_string()), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { + let (mut s, dir) = with_profiles("damaged"); + s.execute("file.new", &json!({"preset": "Letter", "profile": null})).unwrap(); + let defaults = swatch_names(&s); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + assert!(!r["profileError"]["reason"].as_str().unwrap_or("").is_empty(), "{r}"); + assert!(r.get("profile").is_none()); + assert_eq!(swatch_names(&s), defaults); + // Past the limit the file is not read at all (a sparse file of that length). + let big = std::fs::File::create(dir.join("Web.vectorcraft")).unwrap(); + big.set_len(crate::cmd::newdoc::MAX_PROFILE_BYTES + 1).unwrap(); + drop(big); + let r = s.execute("file.new", &json!({"preset": "Web 1920×1080"})).unwrap(); + assert!(r["profileError"]["reason"].as_str().unwrap_or("").contains("larger than"), "{r}"); + assert_eq!(s.doc().unwrap().doc.artboards[0].rect.width(), 1920.0); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn profile_names_are_checked_and_editing_needs_the_folder() { + let mut s = Session::new(); + for p in [json!({"profile": "Posters"}), json!({"profile": 5}), json!({"profile": ""})] { + let e = s.execute("file.new", &p).unwrap_err().to_string(); + assert!(e.contains("no New Document profile called") && e.contains("Film & Video"), "{p}: {e}"); + } + assert!(s.execute("file.newProfiles.edit", &json!({"name": "Posters"})).is_err()); + for cmd in ["file.newProfiles.edit", "file.newProfiles.reset"] { + let e = s.execute(cmd, &json!({"name": "Print"})).unwrap_err().to_string(); + assert!(e.contains("preferences folder"), "{cmd}: {e}"); + } + // Without a folder every profile is the shipped one and documents start with the defaults. + let r = s.execute("file.newProfiles", &json!({})).unwrap(); + assert!(r["folder"].is_null() && r["profiles"][0].get("path").is_none(), "{r}"); + let r = s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + assert!(r.get("profile").is_none() && r.get("profileError").is_none(), "{r}"); +} + +#[test] +fn the_new_layer_takes_an_id_no_profile_art_has() { + // A damaged profile whose symbol art has the id the new layer would otherwise take. + let settings = crate::cmd::newdoc::DocSettings::default(); + let mut profile = settings.document(); + let next = settings.document().peek_next_id().max(profile.peek_next_id()); + let art = std::sync::Arc::new(vectorcraft_doc::Node::group(vectorcraft_doc::NodeId(next), vec![])); + profile.symbols.push(vectorcraft_doc::Symbol { name: "Badge".into(), art, dynamic: false }); + let d = settings.document_from_profile(profile); + assert_eq!(d.layers.len(), 1); + assert_ne!(d.layers[0].id, vectorcraft_doc::NodeId(next)); + // Ids given out later skip the symbol's art too. + assert!(d.peek_next_id() > d.layers[0].id.0 && d.peek_next_id() > next); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f9788d59a8..9c1432d76d 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -365,6 +365,7 @@ registry! { JavaScriptFiles: [javascript_files::KIND] => javascript_files::SPEC, SvgFilter: [svg_filter::KIND] => svg_filter::SPEC, NewDocumentMore: [new_document::MORE] => new_document::MORE_SPEC, + NewDocumentProfiles: [new_document::PROFILES] => new_document::MORE_SPEC, Place: [place::KIND] => place::SPEC, RasterOptions: ["pngOptions", "jpgOptions", "webpOptions", "gifOptions", "png8Options"] => png_options::SPEC, ExportAs: ["exportAs"] => export_as::SPEC, diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 76403ff451..96e33684bc 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -4,11 +4,13 @@ //! Close and Create. More Settings opens a pop-up over the dialog with the artboard layout, spacing //! and columns, editing the same fields. Save Preset turns the top of Preset Details into the //! preset's name, Cancel and Save, and hides Close and Create until the preset is saved or canceled; -//! the rows under it stay editable and are what the preset stores. +//! the rows under it stay editable and are what the preset stores. Manage Profiles opens a pop-up +//! listing the New Document profiles (`file.newProfiles`), each with Edit, which closes the dialog +//! and opens the profile as a document, and Reset, which brings back the shipped profile. //! //! Fields: `file.new`'s params (`preset`, `name`, `width`, `height` (pt), `units`, `artboards`, //! `artboardLayout`, `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi`, -//! `previewMode`, `alignNewObjectsToPixelGrid`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and +//! `previewMode`, `alignNewObjectsToPixelGrid`, `profile`), plus `category` (the tab), `advanced` (Advanced Options open), `bleedLinked` and //! `presetName` (Save Preset's name). Setting `preset` fills the fields from that preset; changing //! any of them afterwards makes the settings custom. @@ -24,12 +26,14 @@ use crate::{VectorcraftApp, widgets}; pub(super) const KIND: &str = "newDocument"; /// New Document with its More Settings pop-up open. pub(super) const MORE: &str = "newDocumentMore"; +/// New Document with its Manage Profiles pop-up open. +pub(super) const PROFILES: &str = "newDocumentProfiles"; pub(super) const SPEC: DialogSpec = DialogSpec { inputs: |_| &["presetName"], ..DialogSpec::window(show, confirm) }; pub(super) const MORE_SPEC: DialogSpec = SPEC; /// The fields `file.new` takes. -const PARAMS: [&str; 13] = [ +const PARAMS: [&str; 14] = [ "preset", "name", "width", @@ -43,6 +47,7 @@ const PARAMS: [&str; 13] = [ "rasterEffectsPpi", "previewMode", "alignNewObjectsToPixelGrid", + "profile", ]; /// The preset the fields were last filled from, as `apply` set them; a Recent or Saved card keeps /// its own units here, which the units chosen in Preset Details don't change. @@ -139,12 +144,21 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } let p = params(app, d); let r = app.run("file.new", Value::Object(p)); - if r.is_ok() { + if let Ok(r) = &r { app.ui.dialog = None; + report_profile(app, r); } r } +/// Say in the status bar when `file.new`'s result `r` reports a profile it could not read. +fn report_profile(app: &mut VectorcraftApp, r: &Value) { + if let Some(e) = r.get("profileError") { + let (name, reason) = (e["profile"].as_str().unwrap_or_default(), e["reason"].as_str().unwrap_or_default()); + app.status(format!("The {name} profile could not be read, so the new document has the default settings: {reason}")); + } +} + /// New Without Dialog (`file.newWithoutDialog`, Cmd+Alt+N): create the document [`open`] would /// offer, as its Create would, without showing the dialog. A dialog already open stays open. pub fn create_without_dialog(app: &mut VectorcraftApp) -> Result { @@ -153,7 +167,11 @@ pub fn create_without_dialog(app: &mut VectorcraftApp) -> Result let offered = app.ui.dialog.take(); app.ui.dialog = shown; let p = offered.map(|d| params(app, &d)).unwrap_or_default(); - app.run("file.new", Value::Object(p)) + let r = app.run("file.new", Value::Object(p)); + if let Ok(r) = &r { + report_profile(app, r); + } + r } /// The `file.new` params of the fields. @@ -194,15 +212,15 @@ fn window(ctx: &egui::Context, id: &str, margin: i8, add: impl FnOnce(&mut egui: super::modal::show(ctx, id, egui::Id::unique(("dialog", id)), -20.0, margin, add); } -/// Whether More Settings' pop-up is open over New Document. +/// Whether More Settings' or Manage Profiles' pop-up is open over New Document. pub(crate) fn popup_open(d: &Dialog) -> bool { - d.kind == MORE + d.kind == MORE || d.kind == PROFILES } -/// Close New Document's More Settings pop-up, or else leave its Save Preset, keeping the fields. -/// False when neither is showing, or `d` is another dialog. +/// Close New Document's More Settings or Manage Profiles pop-up, or else leave its Save Preset, +/// keeping the fields. False when none is showing, or `d` is another dialog. pub(super) fn close_popup(d: &mut Dialog) -> bool { - if d.kind != KIND && d.kind != MORE { + if d.kind != KIND && !popup_open(d) { return false; } if popup_open(d) { @@ -461,12 +479,14 @@ fn details(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, b: &mut if saving { return; } + ui.add_space(6.0); + b.close |= manage_profiles(app, ui, d); // Close and Create at the bottom right. ui.add_space((HEIGHT - (ui.cursor().top() - top) - 28.0).max(12.0)); ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 28.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { b.create |= widgets::primary_button(ui, tl!("Create")).clicked(); ui.add_space(8.0); - b.close = widgets::secondary_button(ui, tl!("Close")).clicked(); + b.close |= widgets::secondary_button(ui, tl!("Close")).clicked(); }); } @@ -563,7 +583,60 @@ fn more_settings(ui: &mut egui::Ui, d: &mut Dialog) { .align(egui::RectAlign::TOP_END) .accessible_name(tl!("More Settings")) .show(|ui| done = more_settings_popup(ui, opening, d)); - d.kind = if open && !done { MORE } else { KIND }.into(); + if open && !done { + d.kind = MORE.into(); + } else if d.kind == MORE { + d.kind = KIND.into(); + } +} + +/// The Manage Profiles button and its pop-up: a row per New Document profile with Edit, which opens +/// the profile as a document and closes New Document (true then), and Reset, which deletes an edited +/// profile's file so the shipped profile applies again. A click outside it and Escape close it. +fn manage_profiles(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let button = widgets::flat_button(ui, tl!("Manage Profiles"), DETAILS); + let mut open = (d.kind == PROFILES) != button.clicked(); + let mut chosen: Option<(&str, &str)> = None; + let has_folder = app.session.new_doc_profile_dir().is_some(); + egui::Popup::from_response(&button) + .open_bool(&mut open) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .align(egui::RectAlign::TOP_END) + .accessible_name(tl!("Manage Profiles")) + .show(|ui| { + ui.set_width(MORE_WIDTH); + let t = Tokens::get(ui.ctx()); + ui.label(egui::RichText::new(tl!("NEW DOCUMENT PROFILES")).font(theme::semibold(11.0)).color(t.text_dim)); + ui.add_space(6.0); + for name in newdoc::profile_names() { + let customized = app.session.new_doc_profile_customized(name); + ui.horizontal(|ui| { + ui.label(tl!(name)); + ui.allocate_ui_with_layout(egui::vec2(ui.available_width(), 24.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add_enabled_ui(customized, |ui| widgets::secondary_button(ui, tl!("Reset"))).inner.clicked() { + chosen = Some(("file.newProfiles.reset", name)); + } + // Without a profiles folder (the web, runs without preferences) there is nothing to edit. + if ui.add_enabled_ui(has_folder, |ui| widgets::secondary_button(ui, tl!("Edit"))).inner.clicked() { + chosen = Some(("file.newProfiles.edit", name)); + } + }); + }); + } + }); + if open { + d.kind = PROFILES.into(); + } else if d.kind == PROFILES { + d.kind = KIND.into(); + } + let Some((cmd, name)) = chosen else { return false }; + match app.run(cmd, json!({ "name": name })) { + Ok(_) => cmd == "file.newProfiles.edit", + Err(e) => { + app.status(e); + false + } + } } /// More Settings' pop-up. True when Done (or Enter) finished with it. @@ -1518,4 +1591,45 @@ mod tests { assert!(screen.contains_rect(h.get_by_label(label).rect()), "{label} is off screen"); } } + + /// Manage Profiles lists a row per profile; Reset is off until a profile has been edited, Escape + /// closes only the pop-up, and Edit opens the profile as a document and closes New Document. + #[test] + fn manage_profiles_edits_and_resets_the_profiles() { + let dir = std::env::temp_dir().join(format!("vc-ui-newdoc-profiles-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut h = big(); + // Without a profiles folder Edit is off too. + h.get_by_label("Manage Profiles").click(); + h.run_steps(4); + assert!(h.get_all_by_label("Edit").all(|b| b.accesskit_node().is_disabled())); + h.key_press(egui::Key::Escape); + h.run_steps(3); + h.state_mut().session.attach_new_doc_profiles(dir.clone()); + h.get_by_label("Manage Profiles").click(); + h.run_steps(4); + assert_eq!(kind(&h), super::PROFILES); + assert_eq!(h.get_all_by_label("Edit").count(), 7); + assert!(h.get_all_by_label("Reset").all(|b| b.accesskit_node().is_disabled())); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(kind(&h), super::KIND, "Escape closes only the pop-up"); + // An edited profile's Reset deletes its file. + h.state_mut().run("file.newProfiles.edit", json!({"name": "Web"})).unwrap(); + h.state_mut().run("file.newDialog", json!({})).unwrap(); + h.run_steps(3); + h.get_by_label("Manage Profiles").click(); + h.run_steps(4); + assert_eq!(h.get_all_by_label("Reset").filter(|b| !b.accesskit_node().is_disabled()).count(), 1); + h.get_all_by_label("Reset").find(|b| !b.accesskit_node().is_disabled()).unwrap().click(); + h.run_steps(3); + assert!(!dir.join("Web.vectorcraft").exists()); + // Edit on the third row (Print). + h.get_all_by_label("Edit").nth(2).unwrap().click(); + h.run_steps(3); + assert!(h.state().ui.dialog.is_none(), "{:?}", h.state().ui.status); + assert_eq!(h.state().session.active().unwrap().doc.title, "Print"); + assert!(dir.join("Print.vectorcraft").is_file()); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/mcp.md b/docs/mcp.md index aeed51157a..90b2955832 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5337,6 +5337,46 @@ every group as it is. The groups and their contents are VectorCraft's own. {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} ``` +### New Document profiles + +Each built-in category (Mobile, Web, Print, Film & Video, Art & Illustration, Branding, Social) has a New Document +profile: a native document that holds the starting assets and settings of the documents made from that category's +presets ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). +`file.new` copies the profile's swatches, swatch groups, graphic styles, brushes, symbols, patterns, character and +paragraph styles, composite fonts, SVG filters, graph designs, ruler origin and ruler mode, transparency grid, Document +Setup options, assigned color profiles, Document Raster Effects Settings other than the resolution, and print settings +into the new document. The preset's size, units, artboards, bleed, background, color mode, raster effects resolution +and Align New Objects to Pixel Grid still apply. The profile's art, layers and artboards are not copied: the document +starts with one empty layer. The grid comes from Preferences › Guides & Grid, as it does for every document. When the +preset's color mode differs from the profile's, the profile's colors are converted as `file.documentColorMode` +converts them. + +A built-in preset names its category's profile in `file.newPresets` (`profile`). Saved and Recent presets keep the +profile of the preset they were made from. `file.new {profile: "Print"}` picks a profile for any settings, and +`profile: null` starts with the defaults. A document made without a preset starts with the defaults. + +The profiles are `.vectorcraft` files named after their category in the `New Document Profiles` folder next to the +preferences (VectorCraft's own place and form). A category without a file has the shipped profile, which holds the +defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts +with the defaults. + +- `file.newProfiles` lists `{profiles: [{name, customized?, path?}], folder?}`. `customized` is true when the category + has a file. A request whose read roots leave out the folder gets neither `customized` nor `path`. +- `file.newProfiles.edit {name}` opens the profile as a document and returns `document.open`'s result. A category + without a file gets the shipped profile written first. File › Save keeps the changes, and the next `file.new` reads + them. +- `file.newProfiles.reset {name}` deletes the category's file, so the shipped profile applies again, and returns + `{name, reset}`. `reset` is false when there was no file. A copy of the profile that is open stays open. + +The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it +runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. +When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the +folder (whether or not the file exists), the document starts with the defaults and +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. In +the New Document dialog, Manage Profiles lists the profiles with Edit and Reset buttons. Edit is available only when +there is a profiles folder, and Reset only for a profile that has a file. An unknown profile name is an error that +lists the names. + ## Place `file.place` puts another file's art into the active document as one undo step without touching the clipboard: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 5e0cf03a3a..d7d30d628c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -682,6 +682,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. +- **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Pattern names and swatch names:** `pattern.options` refuses a new name that another pattern, a swatch or a color group has. It takes a name that only the pattern's own swatches have. The reference page does not say what happens when the new name is taken; the refusal follows VectorCraft's rule that swatches and color groups share one namespace (`Document::swatch_name_taken`), which `swatch.new` and `swatch.edit` also follow. A rename gives the new name only to the pattern's swatches that had the old one; any other swatch with the old name keeps it, and art linked to that swatch stays linked. `object.pattern.make` and `object.pattern.saveCopy` number a color group's name as they number a swatch's. Tests in `tests/pattern.rs` cover each command. Public reference: [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copy). From 2e968acc47af9d1919d7d57254cf4483bf3f32c3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 06:46:06 -0800 Subject: [PATCH 08/33] Align: the Align panel aligns and distributes the selected artboards With the Artboard tool chosen, the Align panel's Align Objects, Distribute Objects and Distribute Spacing buttons, their UI commands and the Control bar's Align and Distribute buttons act on the artboards the tool has selected, as the public page describes: https://helpx.adobe.com/illustrator/desktop/create-manage-artboards/organize-manage-artboards/align-and-distribute-artboards.html - artboard.align, artboard.distribute and artboard.distributeSpacing move whole artboards with their guides, and with the art inside them when Move Artwork with Artboard is on, in one undo step. No undo step is recorded when no artboard moves. - Align To offers Align to Selection and Align to Artboard. Align to Artboard keeps the active artboard in place, and the Distribute buttons then send the Distribute Spacing value. A locked artboard stays where it is. These rules are VectorCraft's own. - The Control bar shows the Align buttons, the Align To menu and the Distribute buttons after the artboard controls while it has room. Docs: docs/mcp.md, docs/ui-parity.md. --- crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/artboardalign.rs | 262 +++++++++++++++++ crates/engine/src/cmd/artboardalign/tests.rs | 277 ++++++++++++++++++ crates/engine/src/cmd/panelcmds.rs | 4 +- crates/engine/src/cmd/plugin_call/reviewed.rs | 3 + crates/engine/src/command_sets.rs | 8 +- crates/mcp/src/ui_catalog.rs | 30 +- crates/ui-egui/src/chrome/control_bar.rs | 21 ++ crates/ui-egui/src/chrome/tests.rs | 43 +++ crates/ui-egui/src/menus/state.rs | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 30 +- crates/ui-egui/src/panels/align.rs | 98 ++++++- crates/ui-egui/src/panels/align/tests.rs | 93 ++++++ docs/mcp.md | 49 +++- docs/ui-parity.md | 1 + 15 files changed, 873 insertions(+), 50 deletions(-) create mode 100644 crates/engine/src/cmd/artboardalign.rs create mode 100644 crates/engine/src/cmd/artboardalign/tests.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 465025302f..038b6e9635 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -4,6 +4,7 @@ pub mod actionset; mod addons; mod apiref; pub(crate) mod appearance; +mod artboardalign; mod assets; mod attributes; pub mod brushlib; @@ -334,6 +335,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(variablecmds::specs()); v.extend(docinfo::specs()); v.extend(panelcmds::specs()); + v.extend(artboardalign::specs()); v.extend(buildcmds::specs()); v.extend(shaper::specs()); v.extend(brushsym::specs()); diff --git a/crates/engine/src/cmd/artboardalign.rs b/crates/engine/src/cmd/artboardalign.rs new file mode 100644 index 0000000000..9832133729 --- /dev/null +++ b/crates/engine/src/cmd/artboardalign.rs @@ -0,0 +1,262 @@ +//! Align and Distribute for artboards: what the Align panel's buttons run while the Artboard tool +//! is chosen. + +use serde_json::{Value, json}; +use vectorcraft_doc::Scaling; +use vectorcraft_geom::{Rect, Vec2}; + +use super::object::choice; +use super::panelcmds::{artboard_index, artboards_art, locked_and_hidden, named_or_selected, note_artboards}; +use super::{Affine, CommandSpec, NodeId, Result, Session, bad, check_switches, cmd, has_doc, switch_or}; +use crate::EngineError; + +pub fn specs() -> Vec { + vec![ + cmd!( + "artboard.align", + "Align", + [], + None, + "{index? | indices?: [n…], selectedArtboards?: [n…] (as artboard.duplicate; default: the artboards the Artboard tool has selected, else its active one), horizontal?: \"left\"|\"center\"|\"right\", vertical?: \"top\"|\"center\"|\"bottom\" (one of the two is needed), to?: \"selection\"|\"artboard\" (default \"selection\": the bounds of the artboards together; \"artboard\": artboard `artboard`, which stays where it is), artboard?: n (0-based; the artboard to align to with to: \"artboard\"; default: the Artboard tool's active one; it need not be one of the artboards aligned), activeArtboard?: n (the journal records that default here, for a replay; `artboard` goes ahead of it), moveArt?: bool (the art fully inside each artboard moves with it; default: the Artboard tool's Move Artwork with Artboard option), patterns?: bool, lockedAndHidden?: bool (as artboard.move)} (Align panel › Align Objects with the Artboard tool chosen) each artboard moves until its edge or center is on that edge or center of what it aligns to, with its guides, in one undo step; a locked artboard stays where it is and still counts in the bounds, and the call fails with `the artboard is locked` when every artboard it names is locked; when no artboard moves, no undo step is recorded → {moved: [index…]}", + has_doc, + align + ), + cmd!( + "artboard.distribute", + "Distribute", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), horizontal?: \"left\"|\"center\"|\"right\" | vertical?: \"top\"|\"center\"|\"bottom\" (one is needed; horizontal goes first), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.align; with `spacing` the artboard must be one of those distributed), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Objects with the Artboard tool chosen) the named edges or centers of the artboards are spaced evenly between the first and the last along the axis, which stay where they are (three or more artboards); with to: \"artboard\", the artboards are spaced the same way and then moved together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the edges or centers are placed `spacing` apart, outward from it in their order (two or more); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute + ), + cmd!( + "artboard.distributeSpacing", + "Distribute Spacing", + [], + None, + "{index? | indices?, selectedArtboards? (as artboard.align), axis?: \"horizontal\"|\"vertical\" (default horizontal), to?: \"selection\"|\"artboard\", artboard?: n, activeArtboard?: n (as artboard.distribute), spacing?: pt (used with to: \"artboard\"), moveArt?, patterns?, lockedAndHidden? (as artboard.align)} (Align panel › Distribute Spacing with the Artboard tool chosen) the gaps between the artboards along the axis become equal, the first and the last staying where they are (three or more artboards); with to: \"artboard\", the gaps become equal the same way and the artboards then move together so that artboard `artboard`, when it is one of them, stays where it is; with to: \"artboard\" and `spacing`, that artboard stays and the others are placed with a gap of `spacing` between neighbors (two or more; a negative spacing overlaps them); a locked artboard stays where it is and keeps its place in the order, and the call fails with `the artboard is locked` when every artboard it names is locked; a spacing that would move an artboard past the canvas is an error; with fewer artboards, or when none moves, no undo step is recorded → {moved: [index…]}", + has_doc, + distribute_spacing + ), + ] +} + +/// What an artboard Align or Distribute command acts on, read from its params. +struct Boards { + /// The artboards named, in artboard order, each with its rectangle. + items: Vec<(usize, Rect)>, + /// With `to: "artboard"`, the artboard to align to and its rectangle. + reference: Option<(usize, Rect)>, + /// Whether the art inside each artboard moves with it. + move_art: bool, + /// Whether locked and hidden art moves too. + locked_art: bool, +} + +/// Reads the params that `artboard.align`, `artboard.distribute` and `artboard.distributeSpacing` +/// (command `cmd`) share, and adds the artboards and the art choice to the journal entry. The +/// artboard to align to is `artboard`, else `activeArtboard` (a replay of the journal), else the +/// Artboard tool's active one, which the journal entry then records as `activeArtboard`. It fails +/// when every artboard named is locked. +fn boards(s: &mut Session, p: &Value, cmd: &str) -> Result { + check_switches(p, &["patterns"], cmd)?; + let to_artboard = choice(p, cmd, "to", &["selection", "artboard"])? == Some("artboard"); + let indices = named_or_selected(s, p, cmd)?; + let given = |key: &str| -> Result> { + match p.get(key).filter(|v| !v.is_null()) { + Some(v) => artboard_index(&s.doc()?.doc, &json!({ "index": v }), cmd).map(Some), + None => Ok(None), + } + }; + let (named, recorded) = (given("artboard")?, given("activeArtboard")?); + let move_art = switch_or(p, "moveArt", s.tool_options_of("artboard")["moveArt"].as_bool().unwrap_or(true), cmd)?; + let locked_art = locked_and_hidden(s, p, move_art, cmd)?; + note_artboards(s, p, &indices); + s.note_journal("moveArt", json!(move_art)); + let reference = match (to_artboard, named.or(recorded)) { + (false, _) => None, + (true, Some(i)) => Some(i), + (true, None) => { + let active = s.tool_options_of("artboard")["active"].clone(); + Some(artboard_index(&s.doc()?.doc, &json!({ "index": active }), cmd)?) + } + }; + if let Some(i) = reference.filter(|_| named.is_none()) { + s.note_journal("activeArtboard", json!(i)); + } + let d = &s.doc()?.doc; + let rect = |i: usize| d.artboards.get(i).map(|a| (i, a.rect)).ok_or_else(|| EngineError::Other("no such artboard".into())); + let items = indices.iter().map(|i| rect(*i)).collect::>>()?; + if indices.iter().all(|i| d.artboards.get(*i).is_some_and(|a| a.locked)) { + return Err(EngineError::Other("the artboard is locked".into())); + } + Ok(Boards { items, reference: reference.map(rect).transpose()?, move_art, locked_art }) +} + +/// `spacing` of the Distribute commands: a finite number, or `None` when it is missing or null. +fn spacing(p: &Value, cmd: &str) -> Result> { + p.get("spacing") + .filter(|v| !v.is_null()) + .map(|v| v.as_f64().filter(|g| g.is_finite()).ok_or_else(|| bad(cmd, "`spacing` must be a number"))) + .transpose() +} + +/// The place in `items` of the artboard `b` aligns to, which the Distribute commands keep where it +/// is. `None` without one, or when it is not one of `items`; with a `gap` that is an error +/// (`no such artboard`), since the gap is measured from it. +fn kept(b: &Boards, items: &[(usize, Rect)], gap: Option) -> Result> { + let Some((reference, _)) = b.reference else { return Ok(None) }; + match items.iter().position(|(i, _)| *i == reference) { + None if gap.is_some() => Err(EngineError::Other("no such artboard".into())), + at => Ok(at), + } +} + +/// Moves each artboard of `moves` by its offset as undo step `label`, with its guides and, when +/// `b` says so, the art inside it. Locked artboards stay where they are. When no artboard moves +/// more than 1e-9 pt on either axis, the document and its undo history stay as they are. The edit +/// fails with nothing changed when an artboard would end up past the canvas, as every edit does. +fn apply(s: &mut Session, label: &str, p: &Value, b: &Boards, moves: &[(usize, Vec2)]) -> Result { + let d = &s.doc()?.doc; + let moves: Vec<(usize, Vec2)> = + moves.iter().copied().filter(|(i, dv)| (dv.x.abs() > 1e-9 || dv.y.abs() > 1e-9) && d.artboards.get(*i).is_some_and(|a| !a.locked)).collect(); + let moved: Vec = moves.iter().map(|(i, _)| *i).collect(); + if moves.is_empty() { + return Ok(json!({ "moved": moved })); + } + let arts = artboards_art(s, &moved, b.move_art, b.locked_art, true)?; + let ids: Vec = arts.iter().flat_map(|(_, a)| a.iter().copied()).collect(); + let sc = Scaling { patterns: super::object::transform_patterns(s, p, &ids)?, ..Scaling::default() }; + s.edit(label, |d, _| { + for ((i, dv), (_, art)) in moves.iter().zip(&arts) { + let a = d.artboards.get_mut(*i).ok_or_else(|| EngineError::Other("no such artboard".into()))?; + a.rect = a.rect + *dv; + let id = a.id; + d.move_artboard_guides(id, *dv); + for id in art { + if let Some(n) = d.node_mut(*id) { + n.transform(Affine::translate(*dv), sc); + super::object::keep_pixel_aligned(n, sc); + } + } + } + Ok(()) + })?; + Ok(json!({ "moved": moved })) +} + +fn align(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.align"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + if h.is_none() && v.is_none() { + return Err(bad(C, "give horizontal or vertical")); + } + let b = boards(s, p, C)?; + let Some(r) = b.reference.map(|(_, r)| r).or_else(|| b.items.iter().map(|(_, r)| *r).reduce(|a, b| a.union(b))) else { + return Ok(json!({ "moved": [] })); + }; + let moves: Vec<(usize, Vec2)> = b + .items + .iter() + .map(|(i, a)| { + let dx = match h { + Some("left") => r.x0 - a.x0, + Some("center") => r.center().x - a.center().x, + Some("right") => r.x1 - a.x1, + _ => 0.0, + }; + let dy = match v { + Some("top") => r.y0 - a.y0, + Some("center") => r.center().y - a.center().y, + Some("bottom") => r.y1 - a.y1, + _ => 0.0, + }; + (*i, Vec2::new(dx, dy)) + }) + .collect(); + apply(s, "Align", p, &b, &moves) +} + +fn distribute(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.distribute"; + let h = choice(p, C, "horizontal", &["left", "center", "right"])?; + let v = choice(p, C, "vertical", &["top", "center", "bottom"])?; + let (horiz, line): (bool, fn(&Rect) -> f64) = match (h, v) { + (Some("left"), _) => (true, |r| r.x0), + (Some("right"), _) => (true, |r| r.x1), + (Some(_), _) => (true, |r| r.center().x), + (None, Some("top")) => (false, |r| r.y0), + (None, Some("bottom")) => (false, |r| r.y1), + (None, Some(_)) => (false, |r| r.center().y), + (None, None) => return Err(bad(C, "give horizontal or vertical")), + }; + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let mut items = b.items.clone(); + items.sort_by(|x, y| line(&x.1).total_cmp(&line(&y.1))); + let kept = kept(&b, &items, gap)?; + // With a spacing: the place in the order and the line of the artboard it is measured from. + let from = kept.zip(gap).and_then(|(at, gap)| items.get(at).map(|(_, r)| (at, gap, line(r)))); + let n = items.len(); + // Two artboards are the ends already; with a spacing the second is placed from the first. + if n < if from.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (first, last) = (line(first), line(last)); + let deltas: Vec = items + .iter() + .enumerate() + .map(|(k, (_, r))| { + let target = match from { + Some((at, gap, origin)) => origin + gap * (k as f64 - at as f64), + None => first + (last - first) * k as f64 / (n - 1) as f64, + }; + target - line(r) + }) + .collect(); + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).copied().unwrap_or(0.0); + let moves: Vec<(usize, Vec2)> = items.iter().zip(&deltas).map(|((i, _), d)| (*i, along(horiz, d - hold))).collect(); + apply(s, "Distribute", p, &b, &moves) +} + +fn distribute_spacing(s: &mut Session, p: &Value) -> Result { + const C: &str = "artboard.distributeSpacing"; + let horiz = choice(p, C, "axis", &["horizontal", "vertical"])? != Some("vertical"); + let gap = spacing(p, C)?; + let b = boards(s, p, C)?; + let start = |r: &Rect| if horiz { r.x0 } else { r.y0 }; + let size = |r: &Rect| if horiz { r.width() } else { r.height() }; + let mut items = b.items.clone(); + items.sort_by(|x, y| start(&x.1).total_cmp(&start(&y.1))); + let kept = kept(&b, &items, gap)?; + let gap = gap.filter(|_| kept.is_some()); + let n = items.len(); + if n < if gap.is_some() { 2 } else { 3 } { + return Ok(json!({ "moved": [] })); + } + let (Some((_, first)), Some((_, last))) = (items.first(), items.last()) else { return Ok(json!({ "moved": [] })) }; + let (lo, hi) = (start(first), start(last) + size(last)); + let gap = gap.unwrap_or_else(|| (hi - lo - items.iter().map(|(_, r)| size(r)).sum::()) / (n - 1) as f64); + let mut pos = lo; + let mut deltas = Vec::with_capacity(n); + for (i, r) in &items { + deltas.push((*i, pos - start(r))); + pos += size(r) + gap; + } + // The artboard aligned to stays where it is, and the others keep their places from it. + let hold = kept.and_then(|at| deltas.get(at)).map_or(0.0, |d| d.1); + let moves: Vec<(usize, Vec2)> = deltas.into_iter().map(|(i, d)| (i, along(horiz, d - hold))).collect(); + apply(s, "Distribute Spacing", p, &b, &moves) +} + +/// An offset of `d` along the axis: x when `horiz`, else y. +fn along(horiz: bool, d: f64) -> Vec2 { + if horiz { Vec2::new(d, 0.0) } else { Vec2::new(0.0, d) } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/artboardalign/tests.rs b/crates/engine/src/cmd/artboardalign/tests.rs new file mode 100644 index 0000000000..94733b099e --- /dev/null +++ b/crates/engine/src/cmd/artboardalign/tests.rs @@ -0,0 +1,277 @@ +//! Align and Distribute for artboards. + +use serde_json::{Value, json}; +use vectorcraft_doc::NodeId; + +use crate::Session; +use crate::tooling::ViewInfo; + +/// A document with three artboards, each with a 10 pt square 5 pt inside its top-left corner: +/// 0 at (0, 0) 100 × 100, 1 at (150, 40) 60 × 80 and 2 at (400, 10) 100 × 50 → the squares' ids. +fn three_boards() -> (Session, [u64; 3]) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + s.execute("artboard.new", &json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + s.execute("artboard.new", &json!({"x": 400, "y": 10, "width": 100, "height": 50})).unwrap(); + let mut sq = |x: u64, y: u64| s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let ids = [sq(5, 5), sq(155, 45), sq(405, 15)]; + s.execute("select.none", &json!({})).unwrap(); + (s, ids) +} + +/// The top-left corner of each artboard. +fn corners(s: &Session) -> Vec<(f64, f64)> { + s.doc().unwrap().doc.artboards.iter().map(|a| (a.rect.x0, a.rect.y0)).collect() +} + +/// The top-left corner of object `id`. +fn corner(s: &Session, id: u64) -> (f64, f64) { + let b = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap(); + (b.x0, b.y0) +} + +fn undo_steps(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +const ALL: [u64; 3] = [0, 1, 2]; + +/// Align Objects lines the artboards up on the bounds of all of them, each with the art inside +/// it, in one undo step. +#[test] +fn align_moves_the_artboards_to_their_common_edge_with_their_art() { + let (mut s, [a, b, c]) = three_boards(); + let before = corners(&s); + let steps = undo_steps(&s); + let out = s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + assert_eq!(out, json!({"moved": [1, 2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 0.0), (400.0, 0.0)]); + assert_eq!([corner(&s, a), corner(&s, b), corner(&s, c)], [(5.0, 5.0), (155.0, 5.0), (405.0, 5.0)], "each square stays on its artboard"); + assert_eq!(undo_steps(&s), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((corners(&s), corner(&s, b)), (before, (155.0, 45.0)), "one undo step"); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "right", "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(400.0, 20.0), (440.0, 40.0), (400.0, 70.0)], "the right edges at 500 and the bottom edges at 120"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "center", "moveArt": false})).unwrap(); + assert_eq!(corners(&s), [(200.0, 0.0), (220.0, 40.0), (200.0, 10.0)], "the centers at 250"); + assert_eq!(corner(&s, a), (5.0, 5.0), "moveArt false leaves the art"); +} + +/// Align to an artboard: that artboard stays where it is and the others line up on it. It need not +/// be one of the artboards aligned. +#[test] +fn align_to_an_artboard_keeps_that_artboard_in_place() { + let (mut s, _) = three_boards(); + let out = s.execute("artboard.align", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 2})).unwrap(); + assert_eq!(out, json!({"moved": [0, 1]})); + assert_eq!(corners(&s), [(400.0, 0.0), (400.0, 40.0), (400.0, 10.0)]); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"index": 0, "vertical": "center", "to": "artboard", "artboard": 1})).unwrap(); + assert_eq!(corners(&s), [(0.0, 30.0), (150.0, 40.0), (400.0, 10.0)], "artboard 1's center is at y 80"); +} + +/// With no artboard named, the commands act on the artboards the Artboard tool has selected and +/// align to its active one; the journal records both for a replay, and an action leaves them out. +#[test] +fn the_artboard_tools_selection_is_the_default_and_is_recorded() { + let (mut s, [_, _, c]) = three_boards(); + s.select_tool("artboard", ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([1, 2])); + let start = s.journal.len(); + assert_eq!(s.execute("artboard.align", &json!({"horizontal": "left"})).unwrap(), json!({"moved": [2]})); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (150.0, 10.0)]); + assert_eq!(corner(&s, c), (155.0, 15.0), "the tool's Move Artwork with Artboard option is on"); + let recorded = json!({"horizontal": "left", "selectedArtboards": [1, 2], "moveArt": true, "lockedAndHidden": false}); + assert_eq!(s.journal.last().unwrap(), &("artboard.align".to_string(), recorded)); + assert_eq!( + s.journal_for_action(start), + [("artboard.align".to_string(), json!({"horizontal": "left", "moveArt": true, "lockedAndHidden": false}))] + ); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + assert_eq!(corners(&s)[2], (150.0, 40.0), "artboard 2 lines up on the active artboard, 1"); + assert_eq!(s.journal.last().unwrap().1["activeArtboard"], json!(1)); + assert_eq!(s.journal_for_action(start)[1].1.get("activeArtboard"), None, "an action aligns to the artboard active when it plays"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard", "activeArtboard": 0})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 0.0), (150.0, 0.0)], "a replay aligns to the artboard it recorded, 0"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "bottom", "to": "artboard", "artboard": 0, "activeArtboard": 2})).unwrap(); + assert_eq!(corners(&s)[1..], [(150.0, 20.0), (150.0, 50.0)], "`artboard` goes ahead of the recorded one"); + let action = s.journal_for_action(start); + let entry = &action.last().unwrap().1; + assert_eq!((entry.get("artboard"), entry.get("activeArtboard")), (Some(&json!(0)), None), "an action keeps the artboard a call named"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.align", &json!({"vertical": "top", "to": "artboard"})).unwrap(); + s.set_tool_option("moveArt", &json!(false)); + s.execute("artboard.align", &json!({"horizontal": "right"})).unwrap(); + assert_eq!((corners(&s)[1], corner(&s, c)), ((190.0, 40.0), (155.0, 45.0)), "with the option off the art stays"); +} + +/// A command that moves no artboard leaves the document and its undo history as they are. +#[test] +fn nothing_to_move_records_no_undo_step() { + let (mut s, _) = three_boards(); + s.execute("artboard.align", &json!({"indices": ALL, "vertical": "top"})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"indices": ALL, "vertical": "top"})), + ("artboard.align", json!({"index": 1, "horizontal": "left", "vertical": "bottom"})), + ("artboard.align", json!({"index": 1, "horizontal": "center", "to": "artboard", "artboard": 1})), + ("artboard.distribute", json!({"indices": [0, 2], "horizontal": "center"})), + ("artboard.distribute", json!({"index": 2, "vertical": "top", "to": "artboard", "artboard": 2, "spacing": 30})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "axis": "horizontal"})), + ("artboard.distributeSpacing", json!({"indices": [1], "axis": "vertical"})), + ] { + assert_eq!(s.execute(id, &p).unwrap(), json!({"moved": []}), "{id} {p}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id} {p}"); + } +} + +/// A locked artboard stays where it is and still counts in the bounds and in the order. When every +/// artboard named is locked, the command fails. +#[test] +fn a_locked_artboard_stays_where_it_is() { + let (mut s, _) = three_boards(); + s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap(); + assert_eq!(s.execute("artboard.align", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(0.0, 20.0), (150.0, 40.0), (400.0, 70.0)], "the bottom edges at 120, the locked artboard's"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": []}), "the middle artboard is locked"); + let out = + s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 0, "spacing": 100})).unwrap(); + assert_eq!((out, corners(&s)), (json!({"moved": [2]}), vec![(0.0, 0.0), (150.0, 40.0), (200.0, 10.0)]), "the third left edge goes to 200"); + s.execute("edit.undo", &json!({})).unwrap(); + let (steps, before) = (undo_steps(&s), corners(&s)); + for (id, p) in [ + ("artboard.align", json!({"index": 1, "horizontal": "left", "to": "artboard", "artboard": 0})), + ("artboard.distribute", json!({"index": 1, "horizontal": "left"})), + ("artboard.distributeSpacing", json!({"indices": [1]})), + ] { + assert_eq!(s.execute(id, &p).unwrap_err().to_string(), "the artboard is locked", "{id}"); + assert_eq!((undo_steps(&s), corners(&s)), (steps, before.clone()), "{id}"); + } +} + +/// Distribute Objects spaces the named edges or centers evenly between the outermost artboards; +/// with a spacing and an artboard to align to, it places them that far apart from that artboard. +#[test] +fn distribute_spaces_the_edges_or_centers() { + let (mut s, [_, b, _]) = three_boards(); + assert_eq!(s.execute("artboard.distribute", &json!({"indices": ALL, "horizontal": "center"})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "the centers at 50, 250 and 450"); + assert_eq!(corner(&s, b), (225.0, 45.0)); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distribute", &json!({"indices": ALL, "vertical": "bottom"})).unwrap(); + assert_eq!(corners(&s), [(0.0, -10.0), (150.0, 40.0), (400.0, 10.0)], "the bottom edges at 60, 90 and 120"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "horizontal": "left", "to": "artboard", "artboard": 1, "spacing": 100}); + assert_eq!(s.execute("artboard.distribute", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(50.0, 0.0), (150.0, 40.0), (250.0, 10.0)], "the left edges 100 apart, artboard 1 in place"); + s.execute("edit.undo", &json!({})).unwrap(); + let two = json!({"indices": [0, 2], "horizontal": "right", "to": "artboard", "artboard": 2, "spacing": 150}); + assert_eq!(s.execute("artboard.distribute", &two).unwrap(), json!({"moved": [0]})); + assert_eq!(corners(&s)[0], (250.0, 0.0), "two artboards are enough with a spacing: the right edges at 350 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "horizontal": "center", "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distribute", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "the centers 200 apart, artboard 1 in place"); +} + +/// Distribute Spacing makes the gaps between the artboards equal; with a spacing and an artboard +/// to align to, the gaps are that wide and that artboard stays. +#[test] +fn distribute_spacing_makes_the_gaps_equal() { + let (mut s, _) = three_boards(); + assert_eq!(s.execute("artboard.distributeSpacing", &json!({"indices": ALL})).unwrap(), json!({"moved": [1]})); + assert_eq!(corners(&s), [(0.0, 0.0), (220.0, 40.0), (400.0, 10.0)], "gaps of 120 between 0 and 500"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": ALL, "axis": "vertical"})).unwrap(); + assert_eq!(corners(&s), [(0.0, 0.0), (150.0, 40.0), (400.0, 45.0)], "top to bottom: artboards 0, 2 and 1, overlapping by 55"); + s.execute("edit.undo", &json!({})).unwrap(); + let p = json!({"indices": ALL, "axis": "horizontal", "to": "artboard", "artboard": 1, "spacing": 20}); + assert_eq!(s.execute("artboard.distributeSpacing", &p).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(30.0, 0.0), (150.0, 40.0), (230.0, 10.0)], "gaps of 20 on both sides of artboard 1"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("artboard.distributeSpacing", &json!({"indices": [0, 2], "to": "artboard", "artboard": 0, "spacing": -25})).unwrap(); + assert_eq!(corners(&s)[2], (75.0, 10.0), "a negative spacing overlaps them"); + s.execute("edit.undo", &json!({})).unwrap(); + let held = json!({"indices": ALL, "to": "artboard", "artboard": 1}); + assert_eq!(s.execute("artboard.distributeSpacing", &held).unwrap(), json!({"moved": [0, 2]})); + assert_eq!(corners(&s), [(-70.0, 0.0), (150.0, 40.0), (330.0, 10.0)], "gaps of 120, artboard 1 in place"); +} + +/// A value outside what a param takes is an error, and nothing changes. +#[test] +fn bad_params_are_errors() { + let (mut s, _) = three_boards(); + let (steps, before) = (undo_steps(&s), corners(&s)); + let with = |extra: Value| { + let mut p = json!({"indices": ALL, "horizontal": "left"}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + p + }; + let shared = [ + json!({"horizontal": "middle"}), + json!({"horizontal": 1}), + json!({"to": "key"}), + json!({"to": "artboard", "artboard": 9}), + json!({"artboard": "1"}), + json!({"artboard": -1}), + json!({"moveArt": "yes"}), + json!({"patterns": 1}), + json!({"lockedAndHidden": "no"}), + json!({"indices": [9]}), + json!({"indices": []}), + json!({"indices": "0"}), + ]; + for id in ["artboard.align", "artboard.distribute", "artboard.distributeSpacing"] { + let axis = if id == "artboard.distributeSpacing" { json!({"horizontal": null, "axis": "horizontal"}) } else { json!({}) }; + for extra in &shared { + let mut p = with(axis.clone()); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + if id == "artboard.distributeSpacing" && extra.get("horizontal").is_some() { + p = json!({"indices": ALL, "axis": extra["horizontal"]}); + } + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + } + for (id, p) in [ + ("artboard.align", json!({"indices": ALL})), + ("artboard.align", json!({"indices": ALL, "vertical": "middle"})), + ("artboard.distribute", json!({"indices": ALL})), + ("artboard.distribute", with(json!({"spacing": "10"}))), + ("artboard.distribute", with(json!({"spacing": true}))), + ("artboard.distribute", json!({"indices": [0, 1], "horizontal": "left", "to": "artboard", "artboard": 2, "spacing": 10})), + ("artboard.distributeSpacing", json!({"indices": ALL, "spacing": [10]})), + ("artboard.distributeSpacing", json!({"indices": [0, 1], "to": "artboard", "artboard": 2, "spacing": 10})), + ] { + assert!(s.execute(id, &p).is_err(), "{id} {p}"); + } + // Spacings that would put an artboard past the canvas, or overflow to infinity. + for (id, p) in [ + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 0, "spacing": 1e9}))), + ("artboard.distribute", with(json!({"to": "artboard", "artboard": 1, "spacing": 1e308}))), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 0, "spacing": 1e9})), + ("artboard.distributeSpacing", json!({"indices": ALL, "to": "artboard", "artboard": 1, "spacing": 1e308})), + ] { + let e = s.execute(id, &p).unwrap_err().to_string(); + assert!(e.contains("exceed the canvas"), "{id} {p}: {e}"); + } + assert_eq!((undo_steps(&s), corners(&s)), (steps, before)); +} + +/// An artboard's own guides move with it. +#[test] +fn an_artboards_guides_move_with_it() { + let (mut s, _) = three_boards(); + s.execute("guide.add", &json!({"vertical": true, "pos": 160, "artboard": 1})).unwrap(); + s.execute("artboard.align", &json!({"indices": [0, 1], "horizontal": "left"})).unwrap(); + let d = &s.doc().unwrap().doc; + let positions: Vec = d.ruler_guides().iter().map(|g| g.pos).collect(); + assert_eq!(positions, [10.0], "the guide stays 10 pt inside artboard 1"); +} diff --git a/crates/engine/src/cmd/panelcmds.rs b/crates/engine/src/cmd/panelcmds.rs index 83a0655284..9f05168f63 100644 --- a/crates/engine/src/cmd/panelcmds.rs +++ b/crates/engine/src/cmd/panelcmds.rs @@ -122,7 +122,7 @@ pub(crate) fn boards_and_art_noted(s: &mut Session, p: &Value, cmd: &str) -> Res /// Add `selectedArtboards` to the running command's journal entry when `p` names no artboard, so a /// replay acts on the artboards the Artboard tool had selected. An action leaves it out /// (`REPLAY_ONLY`) and keeps an `index` or `indices` the call gave. -fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { +pub(crate) fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { if p.get("index").is_none() && p.get("indices").is_none() { s.note_journal("selectedArtboards", json!(indices)); } @@ -130,7 +130,7 @@ fn note_artboards(s: &mut Session, p: &Value, indices: &[usize]) { /// The artboards `cmd` acts on: `index` or `indices`, else `selectedArtboards` (a replay of the /// journal), else those the Artboard tool has selected, else its active one. -fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result> { +pub(crate) fn named_or_selected(s: &Session, p: &Value, cmd: &str) -> Result> { let t = s.tool_options_of("artboard"); let d = &s.doc()?.doc; if p.get("index").is_some() || p.get("indices").is_some() { diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4c9abdb357..c1fc4d6d0a 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -85,9 +85,12 @@ pub(super) const ALLOWED: &[&str] = &[ "appearance.showAllHidden", "appearance.targetContents", "appearance.transfer", + "artboard.align", "artboard.convertToArtboards", "artboard.delete", "artboard.deleteEmpty", + "artboard.distribute", + "artboard.distributeSpacing", "artboard.duplicate", "artboard.fitToArt", "artboard.fitToSelection", diff --git a/crates/engine/src/command_sets.rs b/crates/engine/src/command_sets.rs index 95b44776f0..3eff647cc2 100644 --- a/crates/engine/src/command_sets.rs +++ b/crates/engine/src/command_sets.rs @@ -28,7 +28,7 @@ pub const FIT_ACTIVE_ARTBOARD: [&str; 2] = ["artboard.fitToArt", "artboard.fitTo /// Artboard tool had selected for its commands and for Paste in Place, in Front and in Back; the artboards and art Cut and Copy took with that /// tool chosen; the view's center the app passes to Edit Symbol); an action leaves them out /// ([`Session::journal_for_action`]). -const REPLAY_ONLY: [(&str, &str); 29] = [ +const REPLAY_ONLY: [(&str, &str); 35] = [ ("file.new", "created"), ("edit.newDocumentFromState", "created"), ("document.save", "modified"), @@ -50,6 +50,12 @@ const REPLAY_ONLY: [(&str, &str); 29] = [ ("artboard.cut", "selectedArtboards"), ("artboard.rename", "selectedArtboards"), ("artboard.switchOrientation", "selectedArtboards"), + ("artboard.align", "selectedArtboards"), + ("artboard.align", "activeArtboard"), + ("artboard.distribute", "selectedArtboards"), + ("artboard.distribute", "activeArtboard"), + ("artboard.distributeSpacing", "selectedArtboards"), + ("artboard.distributeSpacing", "activeArtboard"), ("edit.copy", "selectedArtboards"), ("edit.copy", "art"), ("edit.cut", "selectedArtboards"), diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b07964b225..51a9addf70 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -261,91 +261,91 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.horizontalLeft", "Horizontal Align Left", "", - "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalCenter", "Horizontal Align Center", "", - "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalRight", "Horizontal Align Right", "", - "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalVerticalCenter", "Horizontal & Vertical Align Center", "", - "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalTop", "Vertical Align Top", "", - "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalCenter", "Vertical Align Center", "", - "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalBottom", "Vertical Align Bottom", "", - "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalTop", "Vertical Distribute Top", "", - "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalCenter", "Vertical Distribute Center", "", - "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalBottom", "Vertical Distribute Bottom", "", - "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalLeft", "Horizontal Distribute Left", "", - "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalCenter", "Horizontal Distribute Center", "", - "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalRight", "Horizontal Distribute Right", "", - "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalSpace", "Vertical Distribute Space", "", - "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalSpace", "Horizontal Distribute Space", "", - "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "type.bold", diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 53bfb98c1c..e7c4145397 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -282,6 +282,26 @@ fn groups_before_transform(app: &mut VectorcraftApp, ui: &mut Ui, objects: usize transform } +/// Draws the Control bar's Align group after the artboard controls, with the Artboard tool in use: +/// the Align buttons, the Align To menu and, for two or more selected artboards, the Distribute +/// buttons. They align and distribute the selected artboards +/// ([`crate::panels::align::run_button`]). Each shows only while the bar has room for it, and none +/// while the panel menu has the group off. +fn artboard_align_group(app: &mut VectorcraftApp, ui: &mut Ui) { + if !group_on(app, "alignDistribute") || app.session.active().is_none() || ui.available_width() < separator_width(ui) + buttons_width(ui, 7) { + return; + } + separator(ui); + crate::panels::align::align_buttons(app, ui, BUTTON); + if ui.available_width() >= crate::panels::align::align_to_menu_width(BUTTON) + ui.spacing().item_spacing.x { + crate::panels::align::align_to_menu(app, ui, BUTTON); + if crate::panels::align::artboards_selected(app) > 1 && ui.available_width() >= GROUP_GAP + buttons_width(ui, 6) { + ui.add_space(GROUP_GAP); + crate::panels::align::distribute_buttons(app, ui, BUTTON); + } + } +} + /// The edges of the window the Control bar docks to (`window.control.dock {edge}`): the top, then /// the bottom. pub const CONTROL_BAR_EDGES: [&str; 2] = ["top", "bottom"]; @@ -516,6 +536,7 @@ pub fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // of the object controls. let (artboard_options, transform) = (group_on(app, "artboardOptions"), group_on(app, "transform")); if crate::panels::artboards::control_bar(app, ui, artboard_options, transform) { + artboard_align_group(app, ui); return; } if anchors != AnchorControls::None && group_on(app, "anchors") { diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index d7620e8d03..9350180586 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -2669,6 +2669,49 @@ fn menus_stop_above_a_control_bar_docked_at_the_bottom() { assert!(f < bar_top - 1.0, "the status and hint bars show above the Control bar: menus stop above them, {f}"); } +/// With the Artboard tool in use, the Control bar shows the Align buttons after the artboard +/// controls while it has room, and the Distribute buttons for two or more selected artboards. A +/// click aligns the selected artboards as the Align panel's button does. The group is left out +/// while the panel menu has it off. +#[test] +fn the_control_bar_aligns_the_selected_artboards_with_the_artboard_tool() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("artboard.new", json!({"x": 150, "y": 40, "width": 60, "height": 80})).unwrap(); + app.select_tool("artboard"); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2400.0, 300.0)); + let frame = |app: &mut crate::VectorcraftApp, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| super::control_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + }; + let button = |app: &mut crate::VectorcraftApp, name: &str| { + frame(app, vec![]); + let nodes = frame(app, vec![]); + let n = nodes.iter().find(|(_, n)| n.label() == Some(name)).map(|(_, n)| n)?; + n.bounds().map(|b| egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32))) + }; + app.session.set_tool_option("selected", &json!([1])); + assert!(button(&mut app, "Vertical Align Top").is_some(), "one artboard: the Align buttons"); + assert!(button(&mut app, "Horizontal Distribute Left").is_none(), "one artboard: no Distribute buttons"); + app.session.set_tool_option("selected", &json!([1, 0])); + assert!(button(&mut app, "Horizontal Distribute Left").is_some(), "two artboards: the Distribute buttons"); + let r = button(&mut app, "Vertical Align Top").expect("Vertical Align Top"); + let press = + |pressed| egui::Event::PointerButton { pos: r.center(), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for events in [vec![egui::Event::PointerMoved(r.center()), press(true)], vec![press(false)]] { + frame(&mut app, events); + } + let tops: Vec = app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect.y0).collect(); + assert_eq!(tops, [0.0, 0.0], "{}", app.ui.status); + app.run("window.control.options", json!({"group": "alignDistribute", "visible": false})).unwrap(); + assert!(button(&mut app, "Vertical Align Top").is_none(), "the group is off"); +} + /// Two or more selected objects show all six Distribute Objects buttons in the Control bar; /// a single object keeps the bar as it was. A click distributes as the Align panel's button does. #[test] diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index d68608824b..e5c35f6c6e 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -225,7 +225,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { } id if crate::panels::paragraph::ALIGN_COMMANDS.iter().any(|c| c.0 == id) => crate::panels::character::text_style(app).is_some(), "type.applyBullets" | "type.applyNumbers" | "type.convertListToText" => crate::panels::character::text_style(app).is_some(), - id if let Some(b) = crate::panels::align::button(id) => enabled(app, b.command()), + id if let Some(b) = crate::panels::align::button(id) => enabled(app, b.command_now(app)), "file.reveal" => app.services.reveal.is_some() && app.session.active().is_some_and(|d| d.path.is_some()), "file.cancelExport" | "file.exportInBackground" => app.background.jobs.iter().any(|j| j.progress.is_some() && !j.cancelled()), "file.cancelOpen" => !app.opening.pending.is_empty(), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f435bfff22..3800d7e71c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -262,91 +262,91 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "align.horizontalLeft", "Horizontal Align Left", "", - "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Left button: object.align {horizontal: \"left\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalCenter", "Horizontal Align Center", "", - "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Center button: object.align {horizontal: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalRight", "Horizontal Align Right", "", - "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal Align Right button: object.align {horizontal: \"right\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.horizontalVerticalCenter", "Horizontal & Vertical Align Center", "", - "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Horizontal & Vertical Align Center button: object.align {horizontal: \"center\", vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalTop", "Vertical Align Top", "", - "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Top button: object.align {vertical: \"top\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalCenter", "Vertical Align Center", "", - "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Center button: object.align {vertical: \"center\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.verticalBottom", "Vertical Align Bottom", "", - "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice", + "{} the Align panel's Vertical Align Bottom button: object.align {vertical: \"bottom\"} with to: \"key\" while there is a key, else \"artboard\" for one selected object without selected anchor points, else the Align To choice; with the Artboard tool chosen, artboard.align with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalTop", "Vertical Distribute Top", "", - "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Top button: object.distribute {vertical: \"top\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalCenter", "Vertical Distribute Center", "", - "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Center button: object.distribute {vertical: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalBottom", "Vertical Distribute Bottom", "", - "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Bottom button: object.distribute {vertical: \"bottom\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalLeft", "Horizontal Distribute Left", "", - "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Left button: object.distribute {horizontal: \"left\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalCenter", "Horizontal Distribute Center", "", - "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Center button: object.distribute {horizontal: \"center\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalRight", "Horizontal Distribute Right", "", - "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Right button: object.distribute {horizontal: \"right\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeVerticalSpace", "Vertical Distribute Space", "", - "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Vertical Distribute Space button: object.distributeSpacing {axis: \"vertical\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "align.distributeHorizontalSpace", "Horizontal Distribute Space", "", - "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key", + "{} the Align panel's Horizontal Distribute Space button: object.distributeSpacing {axis: \"horizontal\"} with to: \"key\" while there is a key, else the Align To choice, and spacing: the Distribute Spacing value while there is a key; with the Artboard tool chosen, the artboard command of the same name (artboard.distribute, artboard.distributeSpacing) with the same direction on the artboards the tool has selected, to: \"artboard\" (the active artboard) and spacing: the Distribute Spacing value while Align to Artboard is chosen, else \"selection\"", ), ( "type.bold", diff --git a/crates/ui-egui/src/panels/align.rs b/crates/ui-egui/src/panels/align.rs index 82005595f0..1888ea177f 100644 --- a/crates/ui-egui/src/panels/align.rs +++ b/crates/ui-egui/src/panels/align.rs @@ -1,6 +1,7 @@ //! Align panel: Align Objects, Distribute Objects and Distribute Spacing (both with the spacing //! value when aligning to a key object or a key guide) and Align To (selection / key object / -//! artboard). +//! artboard). With the Artboard tool chosen, the buttons align and distribute the artboards the +//! tool has selected. use egui::Ui; use serde::Serialize; @@ -104,7 +105,7 @@ pub enum Button { } impl Button { - /// The engine command the button runs. + /// The engine command the button runs on the selected objects. pub(crate) fn command(self) -> &'static str { match self { Button::Align(..) | Button::AlignCenters => "object.align", @@ -112,6 +113,51 @@ impl Button { Button::Spacing(_) => "object.distributeSpacing", } } + + /// The engine command the button runs on the selected artboards ([`on_artboards`]). + fn artboard_command(self) -> &'static str { + match self { + Button::Align(..) | Button::AlignCenters => "artboard.align", + Button::Distribute(..) => "artboard.distribute", + Button::Spacing(_) => "artboard.distributeSpacing", + } + } + + /// The engine command a click on the button runs now: the artboard command with the Artboard + /// tool chosen, else the object command. + pub(crate) fn command_now(self, app: &VectorcraftApp) -> &'static str { + if on_artboards(app) { self.artboard_command() } else { self.command() } + } +} + +/// Whether the Align panel's buttons, and the Control bar's, align and distribute artboards: the +/// Artboard tool is chosen. They then act on the artboards the tool has selected. +pub(crate) fn on_artboards(app: &VectorcraftApp) -> bool { + app.session.tool_id() == "artboard" +} + +/// The number of artboards the Artboard tool has selected ([`super::artboards::picked`]). +pub(crate) fn artboards_selected(app: &VectorcraftApp) -> usize { + let n = app.session.active().map_or(0, |d| d.doc.artboards.len()); + if n == 0 { 0 } else { super::artboards::picked(app, n).len() } +} + +/// Runs what a click on button `b` runs with the Artboard tool chosen: the artboard command on +/// the artboards the tool has selected. With Align to Artboard chosen, it sends `to: "artboard"`, +/// which keeps the tool's active artboard in place, and the Distribute buttons send the +/// Distribute Spacing value. With Align to Selection chosen, it sends `to: "selection"`. +fn run_on_artboards(app: &mut VectorcraftApp, b: Button) -> Result { + let to_artboard = app.ui.align_to == AlignTo::Artboard; + let mut p = match b { + Button::Align(axis, v) | Button::Distribute(axis, v) => json!({axis: v}), + Button::AlignCenters => json!({"horizontal": "center", "vertical": "center"}), + Button::Spacing(axis) => json!({"axis": axis}), + }; + p["to"] = json!(if to_artboard { "artboard" } else { "selection" }); + if to_artboard && matches!(b, Button::Distribute(..) | Button::Spacing(_)) { + p["spacing"] = json!(app.ui.align_spacing); + } + app.run(b.artboard_command(), p) } /// The Align panel's buttons as UI commands ([`crate::menus::UI_COMMANDS`]), in the panel's order: @@ -143,8 +189,12 @@ pub(crate) fn button(id: &str) -> Option