From 55f615d0c92ae33ecd0ab754806a4efc5889e5d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:32:25 -0800 Subject: [PATCH] Scripts: write path point edits with one command, keep colors exact - Changes to a path's points (closed, setEntirePath, pathPoints and each PathPoint) wait in the object model and are written by one path.setAnchors before any other member or command, before another path's points change, and when the script ends. A loop over 2,000 points now runs one command and makes one undo step. A path aligned to the pixel grid is written at each change so its points read snapped. - A color component reads with the fewest decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path unchanged (RGB, CMYK, Gray and Lab, fill and stroke). - add() and the shape creators put the new path on top of the active layer whatever the drawing mode, and leave the mode as it was. - fillOverprint and strokeOverprint change the top fill or stroke only. - filled = true on a compound path member places the new-art gradient on the compound path's bounds. - An identity rotate or resize checks its arguments and runs no command, on an empty path too. - Tests for each of these, and for setAnchors reading smooth false as a corner. Docs: docs/mcp.md, docs/gaps.md, docs/roadmap.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 39 ++- crates/engine/src/script/dom/colors.rs | 21 +- crates/engine/src/script/dom/paths.rs | 288 +++++++++++++------- crates/engine/src/script/mod.rs | 24 +- crates/engine/src/tests/script_dom_paths.rs | 220 ++++++++++++++- docs/gaps.md | 7 +- docs/mcp.md | 21 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 9 files changed, 504 insertions(+), 120 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 03b236c0e1..c33b3cd47f 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -88,14 +88,17 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, the point changes of a path not written yet, +/// and whether a call's own savepoint ([`atomically`]) is open. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. paths: RefCell>, + /// A path and its subpaths with the point changes the run has made to it and not written yet + /// ([`flush`]). + pending: RefCell)>>, saving: Cell, } @@ -134,15 +137,34 @@ type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. type Member = fn(&Host, &[Data]) -> Answer; +/// A member function that first writes the point changes waiting in [`State`] ([`flush`]). fn function(link: &Link, f: Member) -> HostFunction { + call(link, f, true) +} + +/// A member function of the points of a path, which reads and adds to the point changes waiting in +/// [`State`] instead of writing them first. +fn point_function(link: &Link, f: Member) -> HostFunction { + call(link, f, false) +} + +fn call(link: &Link, f: Member, flushing: bool) -> HostFunction { let l = link.clone(); Rc::new(move |a: Vec| { let h = current(&l)?; h.charge_call(16 + a.iter().map(data_size).sum::())?; + if flushing { + flush(&h)?; + } f(&h, &a) }) } +/// Writes the point changes of a path that wait in [`State`] with one command ([`paths::flush`]). +pub(super) fn flush(h: &Host) -> std::result::Result<(), HostError> { + paths::flush(h) +} + fn get(link: &Link, f: Member) -> HostMember { HostMember::Get(function(link, f)) } @@ -155,6 +177,19 @@ fn method(link: &Link, f: Member) -> HostMember { HostMember::Method(function(link, f)) } +/// [`get`], [`property`] and [`method`] for a member of the points of a path ([`point_function`]). +fn point_get(link: &Link, f: Member) -> HostMember { + HostMember::Get(point_function(link, f)) +} + +fn point_property(link: &Link, g: Member, s: Member) -> HostMember { + HostMember::Property { get: point_function(link, g), set: point_function(link, s) } +} + +fn point_method(link: &Link, f: Member) -> HostMember { + HostMember::Method(point_function(link, f)) +} + /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document, page item or path point `this` is still there. fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 40421c5d38..34c1496054 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -45,9 +45,24 @@ fn color_object(class: &str, values: &[(&str, f64)]) -> Data { Data::Object(items) } -/// A component as the script sees it: `v` times `scale`, rounded to 4 decimals. +/// A component as the script sees it: `exact` rounded to the fewest decimals, from 4 to 9, that +/// `back` turns into the stored `v` again, else `exact` itself, so that assigning a color read +/// from an object gives that object the same color. +fn shown_as(exact: f64, v: f32, back: impl Fn(f64) -> f32) -> f64 { + let mut scale = 1e4; + for _ in 4..=9 { + let r = (exact * scale).round() / scale; + if back(r) == v { + return r; + } + scale *= 10.0; + } + exact +} + +/// A component stored as `v`, from 0 to 1, that the script sees times `scale`. fn shown(v: f32, scale: f64) -> f64 { - (f64::from(v) * scale * 1e4).round() / 1e4 + shown_as(f64::from(v) * scale, v, |r| unit(r, scale)) } /// The color object for a solid color. @@ -58,7 +73,7 @@ fn of_color(c: &Color) -> Data { "CMYKColor", &[("cyan", shown(c, 100.0)), ("magenta", shown(m, 100.0)), ("yellow", shown(y, 100.0)), ("black", shown(k, 100.0))], ), - Color::Gray { k } => color_object("GrayColor", &[("gray", shown(1.0 - k, 100.0))]), + Color::Gray { k } => color_object("GrayColor", &[("gray", shown_as((1.0 - f64::from(k)) * 100.0, k, |g| unit(100.0 - g, 100.0)))]), Color::Lab { l, a, b } => color_object("LabColor", &[("l", shown(l, 1.0)), ("a", shown(a, 1.0)), ("b", shown(b, 1.0))]), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index ac643ce370..29b0c909be 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -6,8 +6,10 @@ //! //! A `PathPoints` object holds its path's handle, and a `PathPoint` the path's handle and the //! point's index, counted across the path's subpaths in order. Each read looks the path up again. -//! Every change runs one command (`path.setAnchors` for the geometry), inside the run's one undo -//! step, and a change that changes nothing runs no command. +//! Every change runs one command inside the run's one undo step, and a change that changes nothing +//! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are +//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or +//! path's points are read or changed, and when the script ends. //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside @@ -15,12 +17,14 @@ //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint -//! commands change in its place. A paint or stroke change leaves the paint for new art, the -//! active proxy and the recent colors as they were. +//! commands change in its place, and a gradient that `filled = true` gives it is placed on that +//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and +//! the recent colors as they were. `fillOverprint` and `strokeOverprint` read and change the top +//! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` makes a path with no points on top of the active layer, painted as new art -//! is. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever +//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -28,7 +32,8 @@ //! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole //! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that //! says it is not available yet. `rotateAbout` and `scaleAbout` default to -//! `Transformation.CENTER`. +//! `Transformation.CENTER`. A transform that leaves the path where it is (`rotate(360)`, +//! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too. //! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and //! `changeStrokePattern` given as different values throw an error; gradients move with the art, //! so `changeFillGradients` false throws an error that says it is not available yet. @@ -46,8 +51,8 @@ use vectorcraft_tools::params::gradient_params; use super::{ Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, property, - this_doc, typename_of, whole, with_doc, + float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -117,14 +122,14 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path has, across its subpaths. -fn point_count(pd: &PathData) -> usize { - pd.subpaths.iter().map(|sp| sp.anchors.len()).sum() +/// How many points a path with the subpaths `subs` has. +fn point_count(subs: &[SubPath]) -> usize { + subs.iter().map(|sp| sp.anchors.len()).sum() } -/// The subpath and the place in it of point `i`. -fn locate(pd: &PathData, mut i: usize) -> Option<(usize, usize)> { - for (s, sp) in pd.subpaths.iter().enumerate() { +/// The subpath and the place in it of point `i`, among the subpaths `subs`. +fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { + for (s, sp) in subs.iter().enumerate() { if i < sp.anchors.len() { return Some((s, i)); } @@ -137,14 +142,69 @@ fn anchor_json(a: &Anchor) -> Value { json!({"x": a.p.x, "y": a.p.y, "in": [a.h_in.x, a.h_in.y], "out": [a.h_out.x, a.h_out.y], "smooth": a.kind == AnchorKind::Smooth}) } -/// Gives the path of `item` the subpaths `subs` with `path.setAnchors`, unless it has them. -fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { - let (same, ok) = read_path(h, item, |st, _, pd| (pd.subpaths == subs, editable(&st.doc, item.id)))?; - if same { - return Ok(()); +fn same_path(a: Item, b: Item) -> bool { + a.doc.uid == b.doc.uid && a.id == b.id +} + +/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included. +fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result { + if let Some((waiting, subs)) = &*h.dom.pending.borrow() + && same_path(*waiting, item) + { + return Ok(f(subs)); } - if !ok { - return Err(cannot_edit(item.id)); + read_path(h, item, |_, _, pd| f(&pd.subpaths)) +} + +/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with +/// the path's other point changes until [`flush`] writes them. The first change of a path writes +/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or +/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object +/// that is, is written at once, so that its points read as the grid snaps them. +fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { + if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() + && same_path(*waiting, item) + { + return Ok(f(subs)); + } + flush(h)?; + let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; + let r = f(&mut subs); + let (same, ok, aligned) = read_path(h, item, |st, _, pd| { + let d = &st.doc; + let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned))); + (pd.subpaths == subs, editable(d, item.id), aligned) + })?; + if !same { + if !ok { + return Err(cannot_edit(item.id)); + } + *h.dom.pending.borrow_mut() = Some((item, subs)); + if aligned { + flush(h)?; + } + } + Ok(r) +} + +/// Gives the path of `item` the subpaths `subs` ([`edit_points`]). +fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::Result<(), HostError> { + edit_points(h, item, |s| *s = subs) +} + +/// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless +/// the path has those points already. +pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { + let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + let same = { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); + node.and_then(|n| n.path_data()).map(|pd| pd.subpaths == subs) + }; + match same { + Some(true) => return Ok(()), + Some(false) => {} + None => return Err(HostError::Error(STALE_ITEM.into())), } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); @@ -152,7 +212,23 @@ fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::R Ok(()) } -/// Runs `id` with `params` and `ids: [item]` on the item, which must be one the user could edit. +/// The object whose paint the path `n` with id `id` shows: its compound path or compound shape +/// when it is a member of one, since the paint commands paint that owner in its place. +fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node { + d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n) +} + +/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active +/// layer, then puts the drawing mode back. +fn drawing_normally(h: &super::Host, f: impl FnOnce() -> T) -> T { + let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); + let r = f(); + h.session.borrow_mut().draw_mode = kept; + r +} + +/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which +/// must be one the user could edit. /// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the /// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put /// back afterwards, so the edit changes only the path. @@ -162,7 +238,7 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r return Err(cannot_edit(item.id)); } if let Some(o) = params.as_object_mut() { - o.insert("ids".into(), json!([item.id.0])); + o.entry("ids").or_insert_with(|| json!([item.id.0])); } keeping_paint(h, || edit_item(h, item, id, ¶ms)) } @@ -273,11 +349,11 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc`, the selection kept, and reverses the new -/// path's direction when `reversed`. → the new path. +/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, +/// and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { - let id = made_id(&command(h, id, params)?)?; + let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -426,8 +502,8 @@ fn items_star(h: &super::Host, a: &[Data]) -> Answer { make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points, from `path.create` with empty path data, painted as -/// new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open +/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with +/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open /// path is set back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; @@ -436,7 +512,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&command(h, "path.create", &json!({"d": ""}))?)?; + let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -457,14 +533,13 @@ fn path_points(h: &super::Host, a: &[Data]) -> Answer { fn path_closed(h: &super::Host, a: &[Data]) -> Answer { let item = this_path(h, a)?; - read_path(h, item, |_, _, pd| Data::Bool(!pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed))) + read_points(h, item, |subs| Data::Bool(!subs.is_empty() && subs.iter().all(|sp| sp.closed))) } fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - let subs = read_path(h, item, |_, _, pd| pd.subpaths.iter().map(|sp| SubPath { anchors: sp.anchors.clone(), closed }).collect())?; - write_path(h, item, subs)?; + edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -517,8 +592,9 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range(format!("setEntirePath takes at most {MAX_POINTS} points"))); } let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::>()?; - let (f, closed) = read_path(h, item, |st, _, pd| (frame(st), !pd.subpaths.is_empty() && pd.subpaths.iter().all(|sp| sp.closed)))?; - let (f, c) = (f?, h.dom.coords.get()); + let f = with_doc(h, item.doc, |_, st| frame(st))?; + let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?; + let c = h.dom.coords.get(); let anchors: Vec = script.iter().map(|p| Anchor::corner(f.to_document(c, *p))).collect(); let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] }; write_path(h, item, subs)?; @@ -546,13 +622,7 @@ struct Look { /// since the paint commands paint that owner in its place. fn look(h: &super::Host, item: Item) -> std::result::Result { read_path(h, item, |st, n, _| { - let d = &st.doc; - let owner = d - .parent_of(item.id) - .and_then(|p| d.node(p)) - .filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()) - .unwrap_or(n); - let ap = &owner.appearance; + let ap = &paint_owner(&st.doc, item.id, n).appearance; let fill = ap.fill(); let stroke = ap.stroke(); Look { @@ -597,7 +667,8 @@ fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option) -> s /// The paint new art gets for its fill or stroke, as `paint.setFill` or `paint.setStroke` params for /// the path `item`: a solid color, linked to its global or spot swatch while the document has that -/// swatch; a gradient, a placed one moved onto the path's bounds as new art takes it; or a pattern. +/// swatch; a gradient, a placed one moved onto the bounds of the path or of the compound path or +/// compound shape whose paint it shows, as new art takes it; or a pattern. /// A fill or stroke of none gives black. A pattern that its swatch does not give as new art has it /// (its own placement, or a pattern the document does not have) throws an error. fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Result { @@ -619,7 +690,7 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { - match read_path(h, item, |_, n, _| n.geometric_bounds())? { + match read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).geometric_bounds())? { Some(b) => { ap.rebase_gradients(GraphicStyle::UNIT_BOX, b); if let Paint::Gradient(placed) = top(&ap) { @@ -827,10 +898,15 @@ fn set_overprint(h: &super::Host, a: &[Data], fill: bool) -> Answer { let (item, look) = this_look(h, a)?; let (now, paint) = if fill { (look.fill_overprint, &look.fill) } else { (look.stroke_overprint, &look.stroke) }; if now != on { - if paint.is_none() { + // The top fill or stroke of the object `look` reads, as `item` names it to the command. + let top = read_path(h, item, |st, n, _| { + let owner = paint_owner(&st.doc, item.id, n); + owner.appearance.items.iter().rposition(|i| i.is_fill() == fill).map(|index| (owner.id, index)) + })?; + let (Some((owner, index)), false) = (top, paint.is_none()) else { return Err(HostError::Error(format!("the path has no {key} to overprint"))); - } - edit_path(h, item, "object.setOverprint", json!({key: on}))?; + }; + edit_path(h, item, "object.setOverprint", json!({key: on, "item": index, "ids": [owner.0]}))?; } Ok(Data::Undefined) } @@ -845,16 +921,23 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer { // ---- PathItem transforms ---- -/// The point of the path's geometric bounds `r`, in document coordinates, that a `Transformation` -/// value names (left out: the center). -fn about(h: &super::Host, item: Item, d: &Data, r: Rect) -> std::result::Result { +/// The member of `Transformation` that `d` names (left out: `CENTER`). +fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> { let name = match d { Data::Undefined => "Transformation.CENTER", Data::String(s) => s.as_str(), _ => return Err(HostError::Type("give a Transformation value".into())), }; + let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m); + let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m)); + member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into())) +} + +/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation` +/// member `name` ([`about_name`]) names. +fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result { let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0); - Ok(match name.strip_prefix("Transformation.").unwrap_or("") { + Ok(match name { "CENTER" => Point::new(cx, cy), "TOP" => Point::new(cx, r.y0), "BOTTOM" => Point::new(cx, r.y1), @@ -914,11 +997,13 @@ fn path_translate(h: &super::Host, a: &[Data]) -> Answer { fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { let angle = number(arg(a, 1), "angle")?; let item = this_path(h, a)?; - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, arg(a, 6), r)?; - let mut params = json!({"angle": angle, "origin": [origin.x, origin.y]}); + let place = about_name(arg(a, 6))?; + let mut params = json!({"angle": angle}); transform_options(a, 2, &mut params)?; if angle.rem_euclid(360.0) != 0.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.rotate", params)?; } Ok(Data::Undefined) @@ -937,9 +1022,8 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into())); } let item = this_path(h, a)?; - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, arg(a, 8), r)?; - let mut params = json!({"sx": sx, "sy": sy, "origin": [origin.x, origin.y], "basis": "page", "strokes": false}); + let place = about_name(arg(a, 8))?; + let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false}); transform_options(a, 3, &mut params)?; let width = look(h, item)?.width; let new_width = widths.map(|w| width * w / 100.0); @@ -947,6 +1031,9 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } if sx != 100.0 || sy != 100.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.scale", params)?; } if let Some(w) = new_width @@ -967,7 +1054,7 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_path(h, item, |_, _, pd| num(float(point_count(pd) as u64))) + read_points(h, item, |subs| num(float(point_count(subs) as u64))) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -984,7 +1071,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - let n = read_path(h, item, |_, _, pd| point_count(pd))?; + let n = read_points(h, item, point_count)?; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1001,22 +1088,19 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; - let (mut subs, n, origin) = read_path(h, item, |st, _, pd| { - let origin = frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])); - (pd.subpaths.clone(), point_count(pd), origin) - })?; + let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); + let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } - let p = match subs.iter().rev().find_map(|sp| sp.anchors.last()) { - Some(last) => last.p, + let p = match last { + Some(p) => p, None => origin?, }; - match subs.last_mut() { + edit_points(h, item, |subs| match subs.last_mut() { Some(sp) => sp.anchors.push(Anchor::corner(p)), None => subs.push(SubPath::new(vec![Anchor::corner(p)], false)), - } - write_path(h, item, subs)?; + })?; Ok(point_ref(h, item, n)) } @@ -1034,7 +1118,7 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It let [run, uid, high, low, i] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) }; let item = path_at(h, *run, *uid, *high, *low)?; let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_path(h, item, |_, _, pd| point_count(pd))?; + let n = read_points(h, item, point_count)?; if i >= n { return Err(HostError::Error(STALE_POINT.into())); } @@ -1045,9 +1129,9 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { let (item, i) = this_point(h, a)?; let c = h.dom.coords.get(); - read_path(h, item, |st, _, pd| { - let fr = frame(st)?; - let anchor = locate(pd, i).and_then(|(s, j)| pd.subpaths.get(s).and_then(|sp| sp.anchors.get(j))); + let fr = with_doc(h, item.doc, |_, st| frame(st))?; + read_points(h, item, |subs| { + let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1056,12 +1140,13 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, i) = this_point(h, a)?; - let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; - let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { - f(an); - } - write_path(h, item, subs)?; + edit_points(h, item, |subs| { + if let Some((s, j)) = locate(subs, i) + && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) + { + f(an); + } + })?; Ok(Data::Undefined) } @@ -1121,15 +1206,16 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { let (item, i) = this_point(h, a)?; - let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; - let (s, j) = read_path(h, item, |_, _, pd| locate(pd, i))?.ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - if let Some(sp) = subs.get_mut(s) { - sp.anchors.remove(j); - if sp.anchors.is_empty() { - subs.remove(s); + edit_points(h, item, |subs| { + if let Some((s, j)) = locate(subs, i) + && let Some(sp) = subs.get_mut(s) + { + sp.anchors.remove(j); + if sp.anchors.is_empty() { + subs.remove(s); + } } - } - write_path(h, item, subs)?; + })?; Ok(Data::Undefined) } @@ -1138,14 +1224,14 @@ fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { /// The members `PathItem` adds to `PageItem`'s. pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> { let mut m = named(vec![ - ("pathPoints", get(l, path_points)), - ("closed", property(l, path_closed, path_set_closed)), + ("pathPoints", point_get(l, path_points)), + ("closed", point_property(l, path_closed, path_set_closed)), ("evenodd", property(l, path_evenodd, path_set_evenodd)), ("area", get(l, path_area)), ("length", get(l, path_length)), ("guides", get(l, path_guides)), ("clipping", get(l, path_clipping)), - ("setEntirePath", method(l, path_set_entire)), + ("setEntirePath", point_method(l, path_set_entire)), ("filled", property(l, path_filled, path_set_filled)), ("fillColor", property(l, path_fill_color, path_set_fill_color)), ("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint)), @@ -1193,13 +1279,13 @@ pub(super) fn classes(l: &Link) -> Vec { None, named(vec![ ("typename", typename_of("PathPoints")), - ("length", get(l, points_length)), - ("parent", get(l, points_parent)), - ("index", method(l, points_index)), - ("add", method(l, points_add)), - ("removeAll", method(l, points_remove_all)), + ("length", point_get(l, points_length)), + ("parent", point_get(l, points_parent)), + ("index", point_method(l, points_index)), + ("add", point_method(l, points_add)), + ("removeAll", point_method(l, points_remove_all)), ]), - Some(super::function(l, points_at)), + Some(super::point_function(l, points_at)), ), class( "PathPoint", @@ -1207,12 +1293,12 @@ pub(super) fn classes(l: &Link) -> Vec { { let mut m = named(vec![ ("typename", typename_of("PathPoint")), - ("parent", get(l, pt_parent)), - ("anchor", property(l, pt_anchor, pt_set_anchor)), - ("leftDirection", property(l, pt_left, pt_set_left)), - ("rightDirection", property(l, pt_right, pt_set_right)), - ("pointType", property(l, pt_type, pt_set_type)), - ("remove", method(l, pt_remove)), + ("parent", point_get(l, pt_parent)), + ("anchor", point_property(l, pt_anchor, pt_set_anchor)), + ("leftDirection", point_property(l, pt_left, pt_set_left)), + ("rightDirection", point_property(l, pt_right, pt_set_right)), + ("pointType", point_property(l, pt_type, pt_set_type)), + ("remove", point_method(l, pt_remove)), ]); m.push(later(l, "PathPoint", "selected")); m diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..37c4b8711d 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1309,6 +1309,8 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result std::result::Result<(Data, Value), HostError> { + // Point changes that wait in the object model are written before any command runs. + dom::flush(host)?; let id = id.to_string(); let params = params.clone(); let session = host.session.clone(); @@ -1352,6 +1354,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { + dom::flush(host)?; let s = host.session.borrow(); let Some(st) = s.active() else { return Ok(Data::Null) }; let ids: Vec = st.selection.objects.iter().take(1_000).map(|i| i.0).collect(); @@ -2472,6 +2475,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result std::result::Result RunError { + let message = match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) | HostError::Abort(m) => m, + HostError::Marked { error, .. } => return end_flush_error(*error), + HostError::Wait => "a host function waited for its result where the run cannot pause".into(), + }; + RunError { kind: RunErrorKind::Limit(LimitKind::Host), message, line: 0, column: 0, authored: false } +} + /// Tests: removes the session's running job while the session keeps its hold on it. → whether a /// job was removed. #[cfg(test)] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 9d9c0c5f7a..004c02f4fc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -344,13 +344,229 @@ fn a_spot_color_reads_as_a_spot_color_and_keeps_its_link() { fn filled_true_on_a_filled_path_runs_no_command() { let (mut s, _, _) = doc(); let steps = undo_steps(&s); - log( + let r = run( &mut s, "var p = app.activeDocument.pathItems[0]; p.filled = true; p.stroked = true; p.fillColor = p.fillColor;\ p.strokeWidth = p.strokeWidth; p.strokeCap = p.strokeCap; p.closed = true; p.evenodd = false; p.strokeDashes = [];\ p.pathPoints[0].anchor = p.pathPoints[0].anchor; p.translate(0, 0); p.rotate(360); p.resize(100, 100);", - ); + ) + .unwrap(); assert_eq!(undo_steps(&s), steps, "values that change nothing add no step"); + assert_eq!(r["slowestCommands"], json!([]), "and run no command"); +} + +#[test] +fn identity_transforms_of_an_empty_path_do_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log( + &mut s, + "var n = app.activeDocument.pathItems.add(); n.rotate(360); n.rotate(0, true, true, true, true, Transformation.TOPLEFT);\ + n.resize(100, 100); n.resize(100, 100, true, true, true, true, 100, Transformation.BOTTOM); n.translate(0, 0);", + ); + for source in [ + "app.activeDocument.pathItems[0].rotate(360, true, true, true, true, 'CENTER');", + "app.activeDocument.pathItems[0].resize(100, 100, true, true, true, true, 100, 'x');", + ] { + assert!(failure(&mut s, source).contains("Transformation"), "{source}"); + } +} + +/// The paint of the fill (`fill`) or stroke of `id`. +fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { + let n = node(s, id); + if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() } +} + +#[test] +fn a_color_read_from_a_path_assigns_back_unchanged() { + let colors = [ + "var c = new RGBColor(); c.red = 0.00001; c.green = 200.123456789; c.blue = 1 / 3;", + "var c = new CMYKColor(); c.cyan = 100 / 3; c.magenta = 0.00001; c.yellow = 99.99999; c.black = 12.3456789;", + "var c = new GrayColor(); c.gray = 100 / 3;", + "var c = new GrayColor(); c.gray = 99.99999;", + "var c = new LabColor(); c.l = 12.3456789; c.a = -0.00001; c.b = 127.99999;", + ]; + for color in colors { + for prop in ["fillColor", "strokeColor"] { + let (mut s, a, _) = doc(); + log(&mut s, &format!("{color} app.activeDocument.pathItems[0].{prop} = c;")); + let (before, steps) = (paint_of(&s, a, prop == "fillColor"), undo_steps(&s)); + let r = run(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.{prop} = p.{prop};")).unwrap(); + assert_eq!(paint_of(&s, a, prop == "fillColor"), before, "{color} {prop}"); + assert_eq!((undo_steps(&s), &r["slowestCommands"]), (steps, &json!([])), "{color} {prop}"); + } + } + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 0.5; p.fillColor = c;\ + var g = new GrayColor(); g.gray = 25; p.strokeColor = g; vc.log([p.fillColor.red, p.fillColor.green, p.strokeColor.gray]);", + ); + assert_eq!(out, vec![json!([200, 0.5, 25])], "whole and short values read as they were given"); +} + +#[test] +fn many_point_edits_run_one_command() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let anchors: Vec = (0..2000).map(|i| json!({"x": f64::from(i) * 0.1, "y": 100})).collect(); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": false})).unwrap()["id"].as_u64().unwrap()); + let steps = undo_steps(&s); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0], pp = p.pathPoints;\ + for (var i = 0; i < pp.length; i++) { var a = pp[i].anchor; pp[i].rightDirection = [a[0] + 1, a[1]]; pp[i].anchor = [a[0], a[1] + 5]; }\ + vc.log(pp[1999].anchor); vc.log(pp[1999].rightDirection); pp[0].remove(); vc.log(pp.length); vc.log(p.pathPoints[0].anchor);", + ) + .unwrap(); + let out: Vec = r["log"].as_array().unwrap().iter().map(rounded).collect(); + assert_eq!(out, vec![json!([199.9, 205]), json!([200.9, 200]), json!(1999), json!([0.1, 205])]); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every point" + ); + let pd = node(&s, id).path_data().unwrap().clone(); + assert_eq!(pd.subpaths[0].anchors.len(), 1999); + assert!(pd.subpaths[0].anchors.iter().all(|a| (a.h_out.x - a.p.x - 1.0).abs() < 1e-9 && (a.h_out.y - a.p.y - 5.0).abs() < 1e-9)); + assert_eq!(undo_steps(&s), steps + 1); +} + +#[test] +fn point_edits_are_written_before_the_next_other_member_reads() { + let (mut s, a, _) = doc(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0], q = app.activeDocument.pathItems[1];\ + p.pathPoints[0].anchor = [0, 300]; vc.log(p.geometricBounds); q.pathPoints[0].anchor = [90, 210];\ + p.pathPoints[1].anchor = [50, 300]; vc.log(q.geometricBounds); vc.log(p.geometricBounds);", + ); + let out: Vec = out.iter().map(rounded).collect(); + assert_eq!(out, vec![json!([0, 300, 40, 240]), json!([90, 210, 150, 150]), json!([0, 300, 50, 240])]); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[1].p, vectorcraft_geom::Point::new(50.0, 0.0)); +} + +#[test] +fn closed_and_set_entire_path_join_the_point_edits_in_one_command() { + let (mut s, a, _) = doc(); + let r = run( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 300], [40, 300], [40, 240]]); p.closed = false;\ + p.pathPoints[1].anchor = [50, 300]; vc.log(p.closed); p.closed = true; p.setEntirePath([[0, 300], [60, 300], [60, 240]]); vc.log(p.closed);", + ) + .unwrap(); + assert_eq!(r["log"], json!([false, true])); + assert_eq!( + r["slowestCommands"].as_array().map(|c| c.iter().map(|c| (c["id"].clone(), c["calls"].clone())).collect::>()), + Some(vec![(json!("path.setAnchors"), json!(1))]), + "one command writes every change" + ); + let pd = node(&s, a).path_data().unwrap().clone(); + assert!(pd.subpaths[0].closed); + assert_eq!(pd.subpaths[0].anchors.iter().map(|a| (a.p.x, a.p.y)).collect::>(), vec![(0.0, 0.0), (60.0, 0.0), (60.0, 60.0)]); +} + +#[test] +fn point_edits_of_a_pixel_aligned_path_read_as_the_grid_snaps_them() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.setPixelAligned", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[10.3, 280.3], [40.3, 280.3], [40.3, 240.3], [10.3, 240.3]]);\ + vc.log(p.pathPoints[0].anchor); p.pathPoints[1].anchor = [40.4, 280.3]; vc.log(p.pathPoints[1].anchor);", + ); + let anchors = node(&s, a).path_data().unwrap().subpaths[0].anchors.to_vec(); + let stored = |i: usize| rounded(&json!([anchors[i].p.x, 300.0 - anchors[i].p.y])); + assert_ne!(rounded(&out[0]), json!([10.3, 280.3]), "the grid moves the point"); + assert_eq!((rounded(&out[0]), rounded(&out[1])), (stored(0), stored(1)), "points read as the path has them"); +} + +#[test] +fn added_paths_go_on_top_of_the_layer_whatever_the_drawing_mode() { + for mode in ["behind", "inside"] { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + let drawing = s.draw_mode; + log( + &mut s, + "var d = app.activeDocument; d.pathItems.add().name = 'n'; d.pathItems.rectangle(10, 10, 5, 5).name = 'r';\ + d.pathItems.roundedRectangle(10, 10, 5, 5).name = 'q';", + ); + let st = s.active().unwrap(); + let children = st.doc.layers[0].children().unwrap(); + let names: Vec> = children.iter().rev().take(3).map(|c| c.name.as_deref()).collect(); + assert_eq!(names, [Some("q"), Some("r"), Some("n")], "{mode}: the new paths are on top of the layer"); + assert_eq!(s.draw_mode, drawing, "{mode}: the drawing mode stays"); + } +} + +#[test] +fn overprint_changes_the_top_fill_or_stroke_only() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.addStroke", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pathItems[0]; p.fillOverprint = true; p.strokeOverprint = true; vc.log([p.fillOverprint, p.strokeOverprint]);", + ); + assert_eq!(out, vec![json!([true, true])]); + let items = node(&s, a).appearance.items.clone(); + for fill in [true, false] { + let flags: Vec = items.iter().filter(|i| i.is_fill() == fill).map(|i| i.overprint()).collect(); + assert!(flags.len() >= 2, "{flags:?}"); + let (top, lower) = flags.split_last().unwrap(); + assert!(*top && lower.iter().all(|f| !f), "fill {fill}: only the top row overprints: {flags:?}"); + } +} + +#[test] +fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() { + for member in 0..2 { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let compound = NodeId(s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [compound.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let stops = json!([{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]); + s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "stops": stops}})).unwrap(); + if let Paint::Gradient(g) = &mut s.paint.fill { + g.geom = Some(vectorcraft_color::GradientGeom { + start: vectorcraft_geom::Point::new(0.0, 0.5), + end: vectorcraft_geom::Point::new(1.0, 0.5), + aspect: 1.0, + focal: None, + }); + } + log(&mut s, &format!("app.activeDocument.pathItems[{member}].filled = true;")); + let b = node(&s, compound).geometric_bounds().unwrap(); + let Paint::Gradient(g) = node(&s, compound).appearance.fill_paint() else { panic!("member {member}: the compound has a gradient") }; + let geom = g.geom.unwrap(); + assert!((geom.start.x - b.x0).abs() < 1e-6 && (geom.end.x - b.x1).abs() < 1e-6, "member {member}: {geom:?} spans {b:?}"); + } +} + +#[test] +fn set_anchors_reads_smooth_false_as_a_corner() { + let (mut s, a, _) = doc(); + let anchor = |smooth: Value| { + let mut v = json!({"x": 20, "y": 20, "in": [10, 20], "out": [30, 20]}); + if !smooth.is_null() { + v["smooth"] = smooth; + } + v + }; + for (smooth, kind, read) in [(json!(false), AnchorKind::Corner, "PointType.CORNER"), (Value::Null, AnchorKind::Smooth, "PointType.SMOOTH")] { + let subpaths = json!([{"anchors": [anchor(smooth.clone()), {"x": 60, "y": 20}], "closed": false}]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subpaths})).unwrap(); + assert_eq!(node(&s, a).path_data().unwrap().subpaths[0].anchors[0].kind, kind, "smooth {smooth}"); + assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].pointType);"), vec![json!(read)], "smooth {smooth}"); + } } #[test] diff --git a/docs/gaps.md b/docs/gaps.md index cd23b3096c..d8184b1a9b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,9 +807,10 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G6 Automation and scripting -- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the - other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new - documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` +- **Missing:** the rest of the document object model for scripts (layers, artboards, type, the selected path + points, gradient stops and the other classes) and the `#engine` script directive (#1183 is open). Scripts have + `app`, the open documents, new documents, each document's selection and its page items, and `Document.pathItems` + makes paths and reads and changes their points, colors, stroke options and transforms. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 44d375ae2c..6c5e64789d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2685,7 +2685,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed?)` and `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new - art is painted. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing + mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, @@ -2693,7 +2694,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through `object.setOverprint` and the transforms - through `object.move`, `object.rotate` and `object.scale`. `pathPoints` + through `object.move`, `object.rotate` and `object.scale`. Changes to the points of a path (`closed`, + `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the + script uses any other member or command, or the points of another path, and when the script ends; a path aligned + to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, `leftDirection` (the handle into the point), `rightDirection` (the handle out of it), `pointType`, `parent` and @@ -2708,15 +2713,19 @@ app through the global object `vc`, and writes to the Script Console and runs ot `pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point whose index is past the end of its path throws `Stale path point`. Color components left out count as 0, `new cmykColor()` makes a `CMYKColor`, `LabColor.l` is 0 to 100 and `a` and `b` are -128 to 128, and a component out of - range throws a `RangeError` when the color is assigned, with nothing changed. Reading `fillColor` or `strokeColor` - gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a + range throws a `RangeError` when the color is assigned, with nothing changed. A component reads with the fewest + decimals, at least 4, that give the stored value back, so assigning a color read from a path leaves the path as it + was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the - stroke; a new-art pattern with a placement of its own, or one missing from the document, throws an error. Sizes and + stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error. + `fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000, `strokeWidth` 0 to 1000 points (a `changeLineWidths` that would scale it past 1000 throws), `strokeDashes` at most 64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to - `Transformation.CENTER`. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and + `Transformation.CENTER`. A transform that leaves the path where it is, such as `rotate(360)` or + `resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and `changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden or locked layer or group, throws `Cannot edit` with nothing diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..28192e13b9 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; the rest of the script document model (layers, artboards, type, the selected path points, gradient stops and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 81abb83e94..72ed713051 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.