diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 8a4e6ebe6f..4f8a211d51 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -441,6 +441,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&' /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in /// ([`plugin::run_command`]), which needs the command's id. pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result { + if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") { + return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p)); + } + if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p)); + } if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) } } diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 16ceda7d38..31b9950296 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -12,6 +12,25 @@ use super::{ }; use crate::EngineError; +pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if p.get("onLayer").is_none() { + return run(s); + } + let parent = object_param(p, "onLayer", cmd)?; + let d = &s.doc()?.doc; + if let Some(id) = parent + && !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id)) + { + return Err(bad(cmd, "onLayer must name an editable layer")); + } + let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal); + let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent); + let result = run(s); + s.doc_mut()?.isolation = isolation; + s.draw_mode = mode; + result +} + pub fn specs() -> Vec { vec![ cmd!( @@ -19,7 +38,7 @@ pub fn specs() -> Vec { "Rectangle", [], None, - "{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}", has_doc, rectangle ), @@ -28,7 +47,7 @@ pub fn specs() -> Vec { "Ellipse", [], None, - "{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", + "{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}", has_doc, ellipse ), @@ -37,7 +56,7 @@ pub fn specs() -> Vec { "Polygon", [], None, - "{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", + "{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}", has_doc, polygon ), @@ -46,7 +65,7 @@ pub fn specs() -> Vec { "Star", [], None, - "{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", + "{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}", has_doc, star ), @@ -137,7 +156,7 @@ pub fn specs() -> Vec { "Create Path", [], None, - "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}", + "{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}", has_doc, path_create ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index db0495ac97..0416c5b406 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -870,7 +870,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result { // A preset keeps its name in Recent unless its size changed (turning it doesn't count). let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); let size = str_param(p, "preset").map(|_| sorted(&base)); - let mut settings = base.with_params(p, C)?; + let mut params = p.clone(); + if s.replaying() + && let Some(rows) = params.pointer_mut("/artboardLayout/rows") + && let Some(value) = rows.as_f64().filter(|r| r.is_finite() && *r >= 1.0) + { + *rows = json!(value.round().min(MAX_ARTBOARDS as f64) as u32); + } + let mut settings = base.with_params(¶ms, C)?; if size != Some(sorted(&settings)) { settings.name = "Custom".into(); } diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index c722e2a58b..726aada285 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -42,7 +42,7 @@ pub fn specs() -> Vec { "Fill", [], None, - "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", + "{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row or changed it, and its opacity when `opacity` wrote that row (exceptions: docs/mcp.md); on a graph label, the graph stores the paint for every label of its kind, as a character fill when the characters took it and with the label's rows when a row did; on a graph's axis line, tick mark or radar ring, its rows for every line of its kind. While the Live Paint Bucket or the Shape Builder is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given, only the default changes (the color the bucket paints with, and the fill the Shape Builder's merges take with Pick Color From Color Swatches) and the selection keeps its paint; `defaultsOnly` with ids, id or item is refused, and the journal records a change either tool made this way with `defaultsOnly: true`, so a replay with another tool active changes the default too → {objects: how many objects took the paint (the objects inside a group, unless an appearance item of the group's own is targeted; 0 when only the default changed), or with an opacity alone how many took the opacity}", has_doc, |s, p| set_paint(s, p, true) ), @@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) apply_paint_opacity(s, p, Some(paint), None, fill) } +pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result) -> Result { + if !switch_or(p, "objectOnly", false, cmd)? { + return run(s); + } + if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) { + return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly")); + } + let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone()); + let result = run(s); + (s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept; + if result.is_ok() { + s.note_defaults_only(); + } + result +} + /// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or /// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points' /// own opacity for a fill (with no paint or a solid color), nothing on a target without that item. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 931504dedb..0e937376bd 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } let mut members = Members::of(sel); for (id, refs) in items { - // A segment pick's endpoints aren't selected anchors: start from none of them. - let segment_pick = sel.segments.remove(&id).is_some(); + let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok()); let all: BTreeSet = d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default(); // Anything but a path is selected, toggled or deselected as a whole. @@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT } // From the anchors selected now (all of them for a path selected as a whole). let now = match sel.partial(id) { - _ if segment_pick => BTreeSet::new(), - Some(a) => a.clone(), + Some(a) => match &endpoints { + Some(endpoints) => a.difference(endpoints).copied().collect(), + None => a.clone(), + }, None if members.contains(id) => all.clone(), None => BTreeSet::new(), }; diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e1d64b2112..4ee4f01c10 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -23,7 +23,7 @@ pub fn specs() -> Vec { "Stroke Options", ["Window", "Stroke"], None, - "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", + "{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}", has_doc, stroke_set ), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 0a5aeacf31..8c8e758c7b 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -289,19 +289,11 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'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, parent: Option, f: impl FnOnce() -> T) -> T { - let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal); - let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent))); - let r = f(); - if let Some((uid, isolation)) = isolation - && let Some(st) = h.session.borrow_mut().document_mut(uid) - { - st.isolation = isolation; - } - h.session.borrow_mut().draw_mode = kept; - r +/// Runs a path creation command with its layer placement recorded. +fn drawing_normally(h: &super::Host, parent: Option, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> { + let mut params = params.clone(); + params["onLayer"] = json!(parent.map(|p| p.0)); + super::command_value(h, id, ¶ms) } /// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which @@ -315,6 +307,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r } if let Some(o) = params.as_object_mut() { o.entry("ids").or_insert_with(|| json!([item.id.0])); + if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") { + o.insert("objectOnly".into(), json!(true)); + } } let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?; let count = if id == "object.setOverprint" { "changed" } else { "objects" }; @@ -453,7 +448,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result { fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { let made = on_doc(h, doc.uid, true, |h| { let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?; + let id = made_id(&drawing_normally(h, parent, id, params)?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -613,9 +608,9 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer())); - let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?; if unpainted { - keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; + command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?; } Ok(id) })?; @@ -640,7 +635,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points(h, item, |subs| { + if subs.is_empty() && closed { + subs.push(SubPath::new(Vec::new(), closed)); + } else { + subs.iter_mut().for_each(|sp| sp.closed = closed); + } + })?; Ok(Data::Undefined) } @@ -836,10 +837,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul Ok(match linked { true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}), true => json!({"swatch": name}), - false => json!({"color": colors::param(color)}), + false => json!({"color": colors::param(color), "keepModel": true}), }) } - Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})), + Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})), Paint::Gradient(g) => { let mut g = g.clone(); if g.geom.is_some() || g.freeform.is_some() { @@ -1502,12 +1503,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[ if held { return true; } - if !sel.contains(id) || sel.segments.contains_key(&id) { + if !sel.contains(id) { return false; } match sel.partial(id) { None => true, - Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)), + Some(picked) => locate(subs, i).is_some_and(|(s, j)| { + picked.contains(&(s, j)) + && !sel + .segments + .get(&id) + .is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j))) + }), } } @@ -1592,17 +1599,11 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer { let picked: Vec = read_path(h, item, |st, _, pd| { let sel = &st.selection; let held = held_selected(&st.doc, sel, item.id); - if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) { + if !held && !sel.contains(item.id) { return Vec::new(); } - let mut out = Vec::new(); - let mut first = 0; - for (s, sp) in pd.subpaths.iter().enumerate() { - let n = sp.anchors.len(); - out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j)); - first += n; - } - out + let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); + (0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect() })?; h.charge_call(picked.len() as u64)?; let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect(); diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index e96645da43..f5a8c840fe 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1617,6 +1617,7 @@ fn attr_type(attr: Attr) -> &'static str { match attr { Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", Attr::TextFont => "TextFont", + Attr::FillColor | Attr::StrokeColor => "Color", _ => "number", } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4bebfb6ab9..7b44a3eb04 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1024,6 +1024,22 @@ fn file_new_takes_the_rows_of_a_grid_by_column() { } } +#[test] +fn file_new_replays_legacy_fractional_and_large_rows() { + for (rows, rounded) in [(3.6, 4), (1001.2, 1000)] { + let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}}); + let mut s = Session::new(); + assert!(s.execute("file.new", ¶ms).unwrap_err().to_string().contains("rows must be a whole number")); + s.replay("file.new", ¶ms).unwrap(); + let mut expected = Session::new(); + let mut params = params; + params["artboardLayout"]["rows"] = json!(rounded); + expected.execute("file.new", ¶ms).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::>(); + assert_eq!(boards(&s), boards(&expected)); + } +} + #[test] fn a_listed_preset_keeps_more_rows_than_artboards() { use crate::cmd::newdoc::{ArtboardLayout, DocSettings}; diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index b08ed50e9a..c1ec77f4e1 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -49,6 +49,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node { s.active().unwrap().doc.node(id).unwrap().clone() } +#[test] +fn path_creation_replays_on_top_of_the_active_layer() { + for mode in ["behind", "inside", "isolation"] { + for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] { + let setup = || { + let (mut s, a, b) = doc(); + if mode == "isolation" { + let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone(); + s.execute("object.isolate", &json!({"id": group})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.drawMode", &json!({"mode": mode})).unwrap(); + } + s + }; + let mut s = setup(); + let start = s.journal.len(); + log(&mut s, &format!("app.activeDocument.pathItems.{create};")); + let mut replay = setup(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s), "{mode}: {create}"); + assert_eq!(replay.draw_mode, s.draw_mode); + assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation); + } + } +} + +#[test] +fn path_paint_edits_replay_without_changing_new_art() { + let (mut s, a, _) = doc(); + let start = s.journal.len(); + log( + &mut s, + "var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\ + p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\ + app.activeDocument.pathItems.rectangle(100, 200, 20, 30);", + ); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(node(&replay, a).appearance, node(&s, a).appearance); + assert_eq!(art(&replay), art(&s)); + assert_eq!(replay.paint, s.paint); + assert_eq!(replay.fill_active, s.fill_active); + assert_eq!(replay.recent_colors, s.recent_colors); +} + +#[test] +fn mixed_anchor_and_segment_picks_keep_independent_anchors() { + for selected in ["ANCHORPOINT", "NOSELECTION"] { + let (mut s, a, _) = doc(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap(); + s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap(); + let out = log( + &mut s, + &format!( + "var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\ + vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\ + p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);", + if selected == "ANCHORPOINT" { 1 } else { 3 } + ), + ); + assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]); + assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 })); + assert!(!s.active().unwrap().selection.segments.contains_key(&a)); + assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] })); + } +} + +#[test] +fn an_empty_path_keeps_closed_before_points_are_added() { + for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] { + let (mut s, _, _) = doc(); + let start = s.journal.len(); + let out = log( + &mut s, + &format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"), + ); + assert_eq!(out, [json!(true), json!(true)]); + let (mut replay, _, _) = doc(); + for (id, params) in s.journal.since(start) { + replay.replay(id, params).unwrap(); + } + assert_eq!(art(&replay), art(&s)); + } +} + +#[test] +fn enabling_path_paint_preserves_the_new_art_color_model() { + for fill in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let cmd = if fill { "paint.setFill" } else { "paint.setStroke" }; + s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap(); + let new_art = s.new_art(); + let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() }; + log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" }); + let n = node(&s, a); + assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want); + } +} + /// Each number of `v` rounded to 3 decimals, in place. fn rounded(v: &Value) -> Value { match v { diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 29b676a377..a18184d7ce 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> { } } +#[test] +fn character_color_attributes_reflect_as_color() { + let (mut s, _) = doc_with("color"); + let out = log( + &mut s, + "var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\ + vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);", + ); + assert_eq!(out, [json!("Color"), json!("Color")]); +} + #[test] fn text_frames_add_point_area_and_path_type() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 6070ae384a..1ff018d34e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3124,7 +3124,8 @@ through `$`: `verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`, `fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and `strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with - `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are + `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports + `fillColor` and `strokeColor` as `Color`. Paragraph attributes are `justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`, or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`, `spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts` @@ -3175,7 +3176,9 @@ through `$`: 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. `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 + mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and + record this placement for replay. A null `onLayer` draws normally on the active layer. + 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`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to @@ -3183,8 +3186,11 @@ through `$`: (counterclockwise for a 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`. Changes to the - points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one + `object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. + Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy + and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept + this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`. + 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. @@ -3204,7 +3210,8 @@ through `$`: the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues` and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`. VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is - closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner + closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first + subpath. `setEntirePath` takes at most 100,000 points and gives corner points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and `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`, and so does a point read before the script removed @@ -3212,7 +3219,8 @@ through `$`: than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`, `object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point, - and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole. + and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment + picks. A path in a selected group or compound path is selected as a whole. Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT` to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's @@ -3228,7 +3236,7 @@ through `$`: 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 gradient goes on the bounds of the path, or of the compound path or compound shape whose paint + stroke. A copied solid new-art color keeps its color model. 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, @@ -10492,6 +10500,8 @@ the rows give the current number of artboards, and New Document drops the rows w `bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)). +Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still +require whole row counts from 1 to 1000. `file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets, kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets