mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into fix/format-write-and-unpack-budget-tests
This commit is contained in:
commit
b6d0ba34b1
20 files changed
+1254
-206
No files matched your search
@@ -448,6 +448,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<Value> {
|
||||
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) }
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Value>) -> Result<Value> {
|
||||
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<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -19,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -395,7 +395,7 @@ impl DocSettings {
|
||||
}
|
||||
"rows" => {
|
||||
self.rows = if replaying {
|
||||
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
|
||||
v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32)
|
||||
} else {
|
||||
count(v)
|
||||
}
|
||||
@@ -605,10 +605,10 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
|
||||
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
|
||||
/// place) stays 0.
|
||||
/// A saved or Recent preset's grid rows, rounded and kept to 0 (columns in their place) to
|
||||
/// [`MAX_ARTBOARDS`], the counts `file.new` takes.
|
||||
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
|
||||
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
|
||||
Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32)
|
||||
}
|
||||
|
||||
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
|
||||
|
||||
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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 o
Line truncated
|
||||
"{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
Line truncated
|
||||
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<Value>) -> Result<Value> {
|
||||
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(), s.pending_paint.clone());
|
||||
let result = run(s);
|
||||
(s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = 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.
|
||||
|
||||
@@ -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<AnchorRef> =
|
||||
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(),
|
||||
};
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"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
|
||||
),
|
||||
|
||||
@@ -99,9 +99,12 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod clipboard;
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
mod paths;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
mod save_open;
|
||||
@@ -111,6 +114,9 @@ mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
@@ -124,13 +130,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
mod colors;
|
||||
mod defaults;
|
||||
mod paths;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::POINT_LOOKS;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
/// The error for an object that was deleted, or that came from an earlier run.
|
||||
@@ -218,9 +217,6 @@ pub(super) struct State {
|
||||
/// Each path whose points the run read, as the run last saw it, by document uid and then path
|
||||
/// id ([`paths`]).
|
||||
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
|
||||
/// The path whose points the object model is writing with `path.setAnchors`, the only path
|
||||
/// that command changes ([`paths`]).
|
||||
one_path: Cell<Option<Item>>,
|
||||
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
|
||||
/// points it read ([`paths`]).
|
||||
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
|
||||
@@ -292,11 +288,13 @@ impl State {
|
||||
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
|
||||
/// document, the selection and the undo histories are as they were before it, with no undo step
|
||||
/// and no change to the document's saved state, and the growth its commands were charged is not
|
||||
/// counted.
|
||||
/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not
|
||||
/// put them back.
|
||||
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
if h.dom.saving.get() {
|
||||
return f(h);
|
||||
}
|
||||
flush(h)?;
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let styles = text::styles::mark(h);
|
||||
let mark = h.growth_mark();
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
//! - 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, or that is on a locked artboard, throws `Cannot edit` with nothing
|
||||
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
|
||||
//! artboard.
|
||||
//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a
|
||||
//! range error when it is assigned.
|
||||
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
|
||||
//! 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
|
||||
@@ -52,9 +53,7 @@
|
||||
//! throws an error that says it is not available yet on a path inside a compound path, throws
|
||||
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
|
||||
//! are locked; assigning the value the path has runs no command.
|
||||
//! - 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.
|
||||
//! - The transforms are `PageItem`'s, with their rules in [`super::transform`].
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
@@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
|
||||
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
|
||||
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
|
||||
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError {
|
||||
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
|
||||
}
|
||||
|
||||
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
|
||||
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
|
||||
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
|
||||
/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is
|
||||
/// hidden or locked, or it is on a locked artboard.
|
||||
fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option<HostError> {
|
||||
if !editable(&st.doc, id) {
|
||||
return Err(cannot_edit(id));
|
||||
Some(cannot_edit(id))
|
||||
} else if super::on_locked_artboard(h, st, id) {
|
||||
Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)))
|
||||
} else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) {
|
||||
Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
if super::on_locked_artboard(h, st, id) {
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
|
||||
}
|
||||
|
||||
/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin.
|
||||
fn in_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
|
||||
if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(HostError::Range(format!("{what} is outside the canvas")))
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The path `d` names, which must still be in its document.
|
||||
@@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError
|
||||
path_of(h, arg(a, 0))
|
||||
}
|
||||
|
||||
/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them.
|
||||
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
|
||||
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
|
||||
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
}
|
||||
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
path_of(h, &path_ref(h, Item { doc, id }))
|
||||
}
|
||||
@@ -149,12 +162,10 @@ fn read_path<T>(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d
|
||||
})
|
||||
}
|
||||
|
||||
/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count).
|
||||
fn path_ref(h: &super::Host, item: Item) -> Data {
|
||||
let s = h.session.borrow();
|
||||
match s.documents().iter().find(|d| d.uid == item.doc.uid) {
|
||||
Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)),
|
||||
None => Data::Null,
|
||||
}
|
||||
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
|
||||
host_ref("PathItem", &handle)
|
||||
}
|
||||
|
||||
/// The index of the first point of each subpath of `subs`, followed by the number of points.
|
||||
@@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
|
||||
/// 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() {
|
||||
#[cfg(test)]
|
||||
tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1));
|
||||
if i < sp.anchors.len() {
|
||||
return Some((s, i));
|
||||
}
|
||||
@@ -248,7 +261,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// 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 or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
|
||||
/// locked or is on a locked artboard ([`protected`]), 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<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
@@ -264,10 +277,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
|
||||
let (same, refused, 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, refuse_path_edit(h, st, item.id), aligned)
|
||||
let same = pd.subpaths == subs;
|
||||
(same, if same { None } else { protected(h, st, item.id) }, aligned)
|
||||
})?;
|
||||
if !same {
|
||||
refused?;
|
||||
if let Some(e) = refused {
|
||||
return Err(e);
|
||||
}
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
if aligned {
|
||||
flush(h)?;
|
||||
@@ -325,12 +341,29 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
let subpaths: Vec<Value> =
|
||||
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
|
||||
// Changes made before this one are looked at in full first.
|
||||
see_all_points(h);
|
||||
let kept = h.dom.one_path.replace(Some(item));
|
||||
let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}));
|
||||
h.dom.one_path.set(kept);
|
||||
r?;
|
||||
super::atomically(h, |h| {
|
||||
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
|
||||
let selection = &mut st.selection;
|
||||
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
|
||||
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
|
||||
}
|
||||
if let Some(segments) = selection.segments.get_mut(&item.id) {
|
||||
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
|
||||
if segments.is_empty() {
|
||||
selection.segments.remove(&item.id);
|
||||
}
|
||||
}
|
||||
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
|
||||
selection.key_anchor = None;
|
||||
}
|
||||
if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id))
|
||||
&& (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()))
|
||||
{
|
||||
selection.remove(item.id);
|
||||
}
|
||||
}
|
||||
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -340,26 +373,36 @@ 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<T>(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 a path creation command with its layer placement recorded.
|
||||
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, 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
|
||||
/// must be one the user could edit ([`refuse_path_edit`]).
|
||||
/// must be one the user could edit ([`protected`]).
|
||||
/// 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.
|
||||
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
|
||||
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
|
||||
if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) {
|
||||
return Err(e);
|
||||
}
|
||||
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));
|
||||
}
|
||||
}
|
||||
keeping_paint(h, || edit_item(h, item, id, ¶ms))
|
||||
let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?;
|
||||
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
|
||||
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
|
||||
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
|
||||
{
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
|
||||
@@ -503,6 +546,11 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
if h.session.borrow().menu.guides_locked
|
||||
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
|
||||
{
|
||||
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
|
||||
}
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
@@ -522,10 +570,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The id in the result of a command that made an object, read from the command's own result so
|
||||
/// that an id above 2^53 stays exact.
|
||||
fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
|
||||
r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
|
||||
/// read it.
|
||||
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
}
|
||||
|
||||
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
|
||||
@@ -535,7 +583,8 @@ fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = keeping_paint(h, || {
|
||||
on_doc(h, doc.uid, true, |h| {
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
@@ -700,9 +749,10 @@ 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(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?;
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
|
||||
if unpainted {
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?;
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})
|
||||
@@ -716,8 +766,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let item = this_path(h, a)?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low]))
|
||||
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
|
||||
Ok(host_ref("PathPoints", &handle))
|
||||
}
|
||||
|
||||
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -728,7 +778,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)
|
||||
}
|
||||
|
||||
@@ -835,8 +891,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
|
||||
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<Anchor> =
|
||||
script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
|
||||
let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
|
||||
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
|
||||
let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
|
||||
write_path(h, item, subs)?;
|
||||
cut_points(h, item);
|
||||
Ok(Data::Undefined)
|
||||
@@ -924,10 +980,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() {
|
||||
@@ -1200,8 +1256,8 @@ pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std
|
||||
|
||||
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
|
||||
let item = path_at(h, *run, *uid, *high, *low)?;
|
||||
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
|
||||
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
|
||||
flush_other(h, item)?;
|
||||
Ok(item)
|
||||
}
|
||||
@@ -1240,8 +1296,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
|
||||
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
|
||||
handle.extend([float(i as u64), float(point_cuts(h, item))]);
|
||||
host_ref("PathPoint", &handle)
|
||||
}
|
||||
|
||||
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
|
||||
@@ -1293,7 +1350,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
|
||||
POINT_LOOKS.with(|n| n.set(n.get() + 1));
|
||||
let node = {
|
||||
let s = h.session.borrow();
|
||||
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned())
|
||||
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| {
|
||||
h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone());
|
||||
node_arc(&st.doc, NodeId(key.1)).cloned()
|
||||
})
|
||||
};
|
||||
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
|
||||
// stale.
|
||||
@@ -1316,53 +1376,47 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
|
||||
/// change that a later command reverses still makes the points stale. Paths under the object that
|
||||
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
|
||||
/// object model's own, and their points stay valid. A document that is the one the run last looked
|
||||
/// at is skipped, as are its paths. While the object model writes one path's points
|
||||
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
|
||||
/// Objects on Path group are looked at in its document.
|
||||
/// at is skipped, as are its paths.
|
||||
pub(super) fn see_all_points(h: &super::Host) {
|
||||
let keys: Vec<(u64, u64)> = {
|
||||
let seen = h.dom.point_nodes.borrow();
|
||||
if seen.values().all(|paths| paths.is_empty()) {
|
||||
return;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut docs = h.dom.point_docs.borrow_mut();
|
||||
let one = h.dom.one_path.get();
|
||||
let seen = h.dom.point_nodes.borrow();
|
||||
let mut keys = Vec::new();
|
||||
// The documents that changed since the last look, kept as they are now.
|
||||
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
|
||||
// Editing a path in an Objects on Path group can move other paths in the group.
|
||||
let mut moved = Vec::new();
|
||||
match s.documents().iter().find(|d| d.uid == *uid) {
|
||||
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
|
||||
Some(st) => {
|
||||
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
|
||||
let d = &st.doc;
|
||||
let group = d.ancestry(item.id).and_then(|a| {
|
||||
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
|
||||
});
|
||||
if let Some(g) = group {
|
||||
g.walk(&mut |n: &crate::doc::Node| {
|
||||
if n.id != item.id && paths.contains_key(&n.id.0) {
|
||||
moved.push((*uid, n.id.0));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
docs.insert(*uid, st.doc.clone());
|
||||
docs.retain(|uid, before| {
|
||||
let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc);
|
||||
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
|
||||
return true;
|
||||
}
|
||||
// Editing a path in an Objects on Path group can move the other paths in the group, so
|
||||
// the outermost such group is looked at in place of the path.
|
||||
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
|
||||
Some(item) => {
|
||||
let group = before
|
||||
.ancestry(item.id)
|
||||
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)));
|
||||
node_arc(before, group.unwrap_or(item.id)).into_iter().collect()
|
||||
}
|
||||
None => {
|
||||
docs.remove(uid);
|
||||
None => before.layers.iter().collect(),
|
||||
};
|
||||
while let Some(node) = todo.pop() {
|
||||
if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) {
|
||||
continue;
|
||||
}
|
||||
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
|
||||
keys.push((*uid, node.id.0));
|
||||
}
|
||||
if let Some(children) = node.children() {
|
||||
todo.extend(children);
|
||||
}
|
||||
}
|
||||
match one {
|
||||
Some(item) if item.doc.uid == *uid => {
|
||||
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
|
||||
keys.append(&mut moved);
|
||||
}
|
||||
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
|
||||
if let Some(after) = after {
|
||||
*before = after.clone();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
keys
|
||||
};
|
||||
let editing = h.dom.editing.get();
|
||||
@@ -1444,8 +1498,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// point of the path removed or replaced since `this` was read.
|
||||
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
|
||||
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
|
||||
let item = path_at(h, *run, *uid, *high, *low)?;
|
||||
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
|
||||
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
|
||||
flush_other(h, item)?;
|
||||
if whole(*cuts) != Some(point_cuts(h, item)) {
|
||||
return Err(HostError::Error(STALE_POINT.into()));
|
||||
@@ -1482,17 +1536,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul
|
||||
let p = point(arg(a, 1), what)?;
|
||||
let (item, _) = this_point(h, a)?;
|
||||
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
|
||||
on_canvas(fr.to_document(h.dom.coords.get(), p), what)
|
||||
}
|
||||
|
||||
/// `p`, a point a script gave in document coordinates, when it is on the canvas (within
|
||||
/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise.
|
||||
fn on_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
|
||||
if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
|
||||
Ok(p)
|
||||
} else {
|
||||
Err(HostError::Range(format!("{what} is outside the canvas")))
|
||||
}
|
||||
in_canvas(fr.to_document(h.dom.coords.get(), p), what)
|
||||
}
|
||||
|
||||
fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer {
|
||||
@@ -1560,12 +1604,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)))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1577,12 +1627,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
|
||||
|
||||
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
|
||||
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
|
||||
/// [`super::State`] are written first only when they add or remove points of this path, since
|
||||
/// the selection names anchors by their place in the document's path.
|
||||
/// [`super::State`] are written first when they add or remove points of this path or invalidate
|
||||
/// selected segments.
|
||||
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let (item, i) = this_point(h, a)?;
|
||||
let moved = match &*h.dom.pending.borrow() {
|
||||
Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?,
|
||||
Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| {
|
||||
!same_layout(subs, &pd.subpaths)
|
||||
|| st
|
||||
.selection
|
||||
.segments
|
||||
.get(&item.id)
|
||||
.is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count())))
|
||||
})?,
|
||||
_ => false,
|
||||
};
|
||||
if moved {
|
||||
@@ -1650,22 +1707,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let picked: Vec<usize> = 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;
|
||||
let segments = sel.segments.get(&item.id);
|
||||
let ends: std::collections::BTreeSet<_> = segments
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
|
||||
.flatten()
|
||||
.collect();
|
||||
let partial = sel.partial(item.id).filter(|_| !held);
|
||||
let mut picked = Vec::new();
|
||||
let mut offset = 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;
|
||||
for j in 0..sp.anchors.len() {
|
||||
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
|
||||
picked.push(offset + j);
|
||||
}
|
||||
}
|
||||
offset += sp.anchors.len();
|
||||
}
|
||||
out
|
||||
picked
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let [high, low] = id_parts(item.id);
|
||||
let cuts = float(point_cuts(h, item));
|
||||
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
Ok(Data::Array(points))
|
||||
}
|
||||
|
||||
@@ -1723,10 +1789,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::d
|
||||
if !wait {
|
||||
// The points are written first, and the selection is then set with selection
|
||||
// commands, which the journal records with the edit.
|
||||
// The current layer and the highlighted Layers rows are put back after the selection is set.
|
||||
let (layer, rows) = with_doc(h, item.doc, |_, st| (st.active_layer, st.highlighted_rows()));
|
||||
flush(h)?;
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
super::restore_selection(h, &doc, &sel)
|
||||
super::restore_selection(h, &doc, &sel)?;
|
||||
super::restore_layer(h, item.doc.uid, layer, &rows)
|
||||
})?;
|
||||
}
|
||||
}
|
||||
@@ -1815,7 +1884,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
|
||||
),
|
||||
("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")),
|
||||
("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")),
|
||||
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
|
||||
("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }),
|
||||
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
|
||||
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
|
||||
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
|
||||
@@ -1897,13 +1966,38 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
|
||||
thread_local! {
|
||||
pub(super) static LOCATE_STEPS: Cell<usize> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_points_do_not_rescan_subpaths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128];
|
||||
s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap();
|
||||
s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap();
|
||||
LOCATE_STEPS.with(|steps| steps.set(0));
|
||||
let out = s
|
||||
.execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"}))
|
||||
.unwrap();
|
||||
assert_eq!(out["log"], json!([2]));
|
||||
LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_made_id_above_two_to_the_53_stays_exact() {
|
||||
assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
|
||||
assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7)));
|
||||
assert!(made_id(&json!({"id": 1.5})).is_err());
|
||||
assert!(made_id(&json!({})).is_err());
|
||||
let made = |v: Value| made_id(&(Data::Undefined, v));
|
||||
assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
|
||||
assert_eq!(made(json!({"id": 7})), Ok(NodeId(7)));
|
||||
assert!(made(json!({"id": 1.5})).is_err());
|
||||
assert!(made(json!({})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! `paragraphAttributes`, and `app.textFonts`, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
@@ -33,6 +34,8 @@
|
||||
//! value; set on an empty range it changes nothing. A paragraph attribute reads the first
|
||||
//! paragraph the range touches and sets every one of them. A text range has the members of
|
||||
//! both its `characterAttributes` and its `paragraphAttributes`.
|
||||
//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes
|
||||
//! the paint away. `strokeWeight` is 0 to 1000 points.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -40,13 +43,14 @@ use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item,
|
||||
editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property,
|
||||
returns, text, typed, typename_of, whole, with_doc,
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of,
|
||||
doc_ref, edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc,
|
||||
page_items, point, property, returns, text, typed, typename_of, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
@@ -303,6 +307,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc<Index>, usize, usize, u
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing
|
||||
/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a
|
||||
/// locked artboard.
|
||||
fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
refuse_protected(h, item, "TextFrame")?;
|
||||
edit_item(h, item, id, params)
|
||||
}
|
||||
|
||||
/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is
|
||||
/// hidden or locked, or it is on a locked artboard.
|
||||
fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> {
|
||||
let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id)));
|
||||
if !ok {
|
||||
return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0)));
|
||||
}
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`.
|
||||
/// When the text is not what that edit gives, every earlier range goes stale.
|
||||
fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
|
||||
@@ -453,7 +478,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
|
||||
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
|
||||
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
|
||||
record(h, r.item, &index, s, e - s, &insert)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -547,6 +572,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option<NodeId>) -> Answer {
|
||||
/// `null` when the type has nothing to outline and the command removed it.
|
||||
fn frame_outline(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
refuse_protected(h, item, "TextFrame")?;
|
||||
let (_, r) = on_doc(h, item.doc.uid, true, |h| {
|
||||
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
|
||||
super::command_value(h, "type.createOutlines", &json!({}))
|
||||
@@ -568,6 +594,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer {
|
||||
Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))),
|
||||
Some(true) => {}
|
||||
}
|
||||
refuse_protected(h, item, "TextFrame")?;
|
||||
let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" };
|
||||
let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?;
|
||||
new_ref(h, item.doc, result_id(&r).or(Some(item.id)))
|
||||
@@ -730,35 +757,40 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let contents = contents_of(arg(a, 1))?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let at = if before || matches!(arg(a, 2), Data::Undefined) {
|
||||
// The place, and whether it is the end of a range, which rounds up to a character boundary.
|
||||
let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) {
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let span = |k: usize| match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
if before {
|
||||
items.clone().next().and_then(span).map_or(s, |(x, _)| x)
|
||||
(items.clone().next().and_then(span).map_or(s, |(x, _)| x), false)
|
||||
} else {
|
||||
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
|
||||
(items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true)
|
||||
}
|
||||
} else {
|
||||
let rel = arg(a, 2);
|
||||
let target = if handle_of(rel, "TextFrame").is_some() {
|
||||
whole_span(h, item_of(h, rel)?)?.1
|
||||
} else if handle_of(rel, "TextRange").is_some() {
|
||||
span_of(h, rel, &["TextRange"])?
|
||||
} else {
|
||||
span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))?
|
||||
return Err(HostError::Type("relativeObject must be a TextRange or a TextFrame".into()));
|
||||
};
|
||||
if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id {
|
||||
return Err(HostError::Error("relativeObject must be text of the same text frame".into()));
|
||||
}
|
||||
let (_, ts, te, _) = resolve(h, target)?;
|
||||
if text_placement(arg(a, 3))? { te } else { ts }
|
||||
if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) }
|
||||
};
|
||||
// A place inside a character (between the two halves of a surrogate pair) moves to its edge.
|
||||
let b = index.byte(at, after);
|
||||
let at = index.text[..b].encode_utf16().count();
|
||||
if contents.is_empty() {
|
||||
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
|
||||
return Ok(range_ref(h, r.item, at, at, stamp, "TextRange"));
|
||||
}
|
||||
let b = index.byte(at, false);
|
||||
let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next());
|
||||
let (lead, trail) = match part {
|
||||
Part::Characters => ("", ""),
|
||||
@@ -774,7 +806,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
|
||||
),
|
||||
};
|
||||
let insert = format!("{lead}{contents}{trail}");
|
||||
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
|
||||
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
|
||||
record(h, r.item, &index, at, 0, &insert)?;
|
||||
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
|
||||
let start = at + lead.encode_utf16().count();
|
||||
@@ -804,9 +836,12 @@ enum Attr {
|
||||
Underline,
|
||||
StrikeThrough,
|
||||
TextFont,
|
||||
FillColor,
|
||||
StrokeColor,
|
||||
StrokeWeight,
|
||||
}
|
||||
|
||||
const ATTRS: [(&str, Attr); 11] = [
|
||||
const ATTRS: [(&str, Attr); 14] = [
|
||||
("size", Attr::Size),
|
||||
("leading", Attr::Leading),
|
||||
("autoLeading", Attr::AutoLeading),
|
||||
@@ -818,6 +853,9 @@ const ATTRS: [(&str, Attr); 11] = [
|
||||
("underline", Attr::Underline),
|
||||
("strikeThrough", Attr::StrikeThrough),
|
||||
("textFont", Attr::TextFont),
|
||||
("fillColor", Attr::FillColor),
|
||||
("strokeColor", Attr::StrokeColor),
|
||||
("strokeWeight", Attr::StrokeWeight),
|
||||
];
|
||||
|
||||
/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with
|
||||
@@ -920,9 +958,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize)
|
||||
Attr::Underline => Data::Bool(s.underline),
|
||||
Attr::StrikeThrough => Data::Bool(s.strikethrough),
|
||||
Attr::TextFont => font_ref(h, &s.font_family, &s.font_style),
|
||||
Attr::FillColor => colors::of_paint(&s.fill),
|
||||
Attr::StrokeColor => colors::of_paint(&s.stroke),
|
||||
Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a
|
||||
/// `strokeWidth` it is given.
|
||||
fn stroke_scale(t: &TextObject) -> f64 {
|
||||
vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0)
|
||||
}
|
||||
|
||||
/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after.
|
||||
fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> {
|
||||
let finite = || number(v, name);
|
||||
@@ -991,6 +1038,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &
|
||||
let (family, style) = font_of(h, v)?;
|
||||
(json!({"font": family, "style": style}), font_ref(h, &family, &style))
|
||||
}
|
||||
Attr::FillColor | Attr::StrokeColor => {
|
||||
let color = colors::assigned(v, name)?;
|
||||
let paint = color.map_or(Paint::None, Paint::solid);
|
||||
let given = color.map_or_else(|| json!("none"), |c| colors::param(&c));
|
||||
let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" };
|
||||
(json!({ key: given }), colors::of_paint(&paint))
|
||||
}
|
||||
Attr::StrokeWeight => {
|
||||
let n = finite()?;
|
||||
if !(0.0..=1000.0).contains(&n) {
|
||||
return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into()));
|
||||
}
|
||||
(json!({"strokeWidth": n}), num(n))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1024,7 +1085,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?;
|
||||
// A leading set on characters with auto leading fixes it even where auto gives that value.
|
||||
let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants);
|
||||
let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p));
|
||||
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
|
||||
let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p));
|
||||
let fixed = match (attr, &wants) {
|
||||
(Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?),
|
||||
_ => None,
|
||||
@@ -1042,7 +1104,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
super::atomically(h, |h| {
|
||||
for (start, end, leading) in &spans {
|
||||
let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading});
|
||||
edit_item(h, r.item, "text.setRangeStyle", &p)?;
|
||||
edit_text(h, r.item, "text.setRangeStyle", &p)?;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -1054,7 +1116,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
|
||||
o.insert("start".into(), json!(ba));
|
||||
o.insert("end".into(), json!(bb));
|
||||
}
|
||||
let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?;
|
||||
let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?;
|
||||
if let Attr::TextFont = attr {
|
||||
let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
|
||||
font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?;
|
||||
@@ -1216,7 +1278,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
|
||||
o.insert("start".into(), json!(ba));
|
||||
o.insert("end".into(), json!(bb));
|
||||
}
|
||||
edit_item(h, r.item, id, &p)?;
|
||||
edit_text(h, r.item, id, &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1336,6 +1398,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
|
||||
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
|
||||
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
|
||||
}
|
||||
refuse_protected(h, path, "PathItem")?;
|
||||
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
|
||||
let vertical = vertical_of(arg(a, orientation))?;
|
||||
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
|
||||
@@ -1380,7 +1443,7 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
@@ -1557,6 +1620,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",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the
|
||||
/// text frame is protected as for any other text edit.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
@@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
super::refuse_protected(h, target.item, "TextFrame")?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
@@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
// A style's colors and stroke weight are not available yet (`char_members`).
|
||||
Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec<Described> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| {
|
||||
if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) {
|
||||
return super::super::later(link, "CharacterAttributes", name);
|
||||
}
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
//! other value, and a scale of strokes and effects with positions left as they are, throws an
|
||||
//! error that says so.
|
||||
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
|
||||
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
|
||||
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
|
||||
//! with nothing changed, and so are
|
||||
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
|
||||
//! past the canvas.
|
||||
|
||||
@@ -41,6 +42,9 @@ const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"
|
||||
/// The error for a locked object.
|
||||
const LOCKED: &str = "cannot transform locked objects";
|
||||
|
||||
/// The error for a guide while guides are locked.
|
||||
const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked";
|
||||
|
||||
/// The error for a hidden object.
|
||||
const HIDDEN: &str = "cannot transform hidden objects";
|
||||
|
||||
@@ -215,6 +219,9 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) {
|
||||
return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0)));
|
||||
}
|
||||
// The identity acts the same about every point, so an object without bounds (an empty path)
|
||||
// takes it too.
|
||||
let o = match (about, bounds) {
|
||||
|
||||
@@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() {
|
||||
assert_eq!(fill_of(&s, a).to_hex(), "#808080");
|
||||
}
|
||||
|
||||
/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would
|
||||
/// leave waiting for the commit is not added to Recent Colors when the interaction commits.
|
||||
#[test]
|
||||
fn object_only_paint_in_an_interaction_keeps_recent_colors() {
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, json!("#808080"));
|
||||
s.recent_colors.clear();
|
||||
let recent = (s.recent_colors.clone(), s.last_solid);
|
||||
s.begin_interaction("Adjust Colors").unwrap();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap();
|
||||
assert_eq!(fill_of(&s, a).to_hex(), "#ff0000");
|
||||
s.commit_interaction().unwrap();
|
||||
assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were");
|
||||
}
|
||||
|
||||
/// Saturate needs its intensity: a call without one, or with one that is not a number, is an error
|
||||
/// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end.
|
||||
#[test]
|
||||
|
||||
@@ -219,6 +219,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() {
|
||||
("rows", 2.4, 2),
|
||||
("rows", 0.6, 1),
|
||||
("rows", 1000.4, 1000),
|
||||
("rows", 1000.6, 1000),
|
||||
("rows", 5000.0, 1000),
|
||||
] {
|
||||
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
|
||||
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
|
||||
@@ -236,8 +238,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() {
|
||||
p["artboardLayout"][key] = json!(expected);
|
||||
}
|
||||
assert_eq!(boards(&s), boards(&new_doc(p)));
|
||||
if key == "rows" {
|
||||
assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}");
|
||||
}
|
||||
}
|
||||
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
|
||||
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] {
|
||||
let mut p = json!({"artboardLayout": layout});
|
||||
p["artboardLayout"]["layout"] = json!("gridByColumn");
|
||||
let mut s = Session::new();
|
||||
@@ -345,6 +350,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() {
|
||||
assert_eq!(boards(&s).iter().map(|r| r.x0).collect::<Vec<_>>(), [0.0, 100.0, 200.0], "side by side, not overlapping");
|
||||
}
|
||||
|
||||
/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that
|
||||
/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows.
|
||||
#[test]
|
||||
fn a_saved_preset_with_too_many_rows_reads_in_range() {
|
||||
let mut s = Session::new();
|
||||
let prefs = json!({
|
||||
"newDocPresets": [
|
||||
{"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001},
|
||||
{"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0},
|
||||
],
|
||||
});
|
||||
s.apply_prefs(serde_json::from_value(prefs).unwrap());
|
||||
let saved = presets(&mut s, "Saved");
|
||||
assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]);
|
||||
assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]);
|
||||
s.execute("file.new", &saved[0]).unwrap();
|
||||
assert_eq!(boards(&s).len(), 4);
|
||||
}
|
||||
|
||||
/// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest
|
||||
/// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names
|
||||
/// the limit in points and, when the document's units aren't points, in those units too.
|
||||
|
||||
@@ -1321,6 +1321,24 @@ 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), (1000.4, 1000), (1000.5, 1000), (5000.0, 1000)] {
|
||||
let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}});
|
||||
let mut s = Session::new();
|
||||
// A direct call refuses a fraction or a count over 1000; a replay rounds it and keeps it to at most 1000.
|
||||
let direct = Session::new().execute("file.new", ¶ms);
|
||||
assert!(direct.is_err(), "{rows}: {direct:?}");
|
||||
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::<Vec<_>>();
|
||||
assert_eq!(boards(&s), boards(&expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
|
||||
|
||||
@@ -50,6 +50,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]]);", "p.setEntirePath([]);"] {
|
||||
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 {
|
||||
@@ -114,6 +222,23 @@ fn path_items_read_with_a_name_give_the_named_path() {
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_items_read_non_index_numbers_as_names() {
|
||||
for name in ["-1", "1.5", "4294967295"] {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\
|
||||
vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\
|
||||
vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `pathItems` read with a name that is the text of a number but not an array index, such as `-1`
|
||||
/// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes
|
||||
/// a number as a position, as in `pageItems`.
|
||||
@@ -332,6 +457,354 @@ fn path_point_wrapper_goes_stale_after_remove() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_point_remaps_selection_and_clears_deleted_geometry() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\
|
||||
var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\
|
||||
vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\
|
||||
vc.log(p.pathPoints[0].selected);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]);
|
||||
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)]));
|
||||
assert!(s.active().unwrap().selection.contains(b));
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
assert!(!s.active().unwrap().selection.contains(a));
|
||||
assert!(s.active().unwrap().selection.contains(b));
|
||||
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
assert!(!s.active().unwrap().selection.contains(a));
|
||||
assert!(!s.active().unwrap().selection.segments.contains_key(&a));
|
||||
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::<Vec<_>>(), vec![(0, 1)]);
|
||||
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_point_replays_selection_before_moving_anchors() {
|
||||
for segments in [false, true] {
|
||||
let setup = || {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap();
|
||||
if segments {
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap();
|
||||
} else {
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap();
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut s = setup();
|
||||
let start = s.journal.len();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
let a = s.active().unwrap().selection.objects[0];
|
||||
// The removed anchor's segments take their other ends with them unless a selected segment
|
||||
// still ends there, so with segments the anchor after the removed one leaves the selection.
|
||||
assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] }));
|
||||
s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap();
|
||||
let mut replay = setup();
|
||||
for (id, params) in s.journal.since(start) {
|
||||
replay.replay(id, params).unwrap();
|
||||
}
|
||||
assert_eq!(art(&replay), art(&s), "segments: {segments}");
|
||||
assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() {
|
||||
let (mut s, _, b) = doc();
|
||||
s.execute("layer.new", &json!({"name": "Top"})).unwrap();
|
||||
let c = rect(&mut s, 200.0, 50.0, 40.0, 40.0);
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
|
||||
let (layer, rows) = {
|
||||
let st = s.active().unwrap();
|
||||
(st.active_layer, st.highlighted_rows())
|
||||
};
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();");
|
||||
let st = s.active().unwrap();
|
||||
assert!(!st.selection.contains(c) && st.selection.contains(b));
|
||||
assert_eq!(st.active_layer, layer);
|
||||
assert_eq!(st.highlighted_rows(), rows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emptying_an_unselected_path_keeps_the_targeted_layer() {
|
||||
let (mut s, a, _) = doc();
|
||||
let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
|
||||
assert!(!s.active().unwrap().selection.contains(a));
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();");
|
||||
assert_eq!(s.active().unwrap().selection.target, Some(layer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_selection_reads_flush_removed_closing_segments() {
|
||||
for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\
|
||||
p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\
|
||||
vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);",
|
||||
);
|
||||
assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]);
|
||||
assert_eq!(out[4], json!("PathPointSelection.NOSELECTION"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() {
|
||||
for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] {
|
||||
for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap();
|
||||
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
|
||||
let anchors = selected_anchors(&s, a);
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}"));
|
||||
assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] });
|
||||
assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed);
|
||||
let selection = &s.active().unwrap().selection;
|
||||
assert!(selection.contains(b));
|
||||
assert_eq!(selected_anchors(&s, a), anchors);
|
||||
let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect();
|
||||
assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] });
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(node(&s, a).path_data().unwrap().subpaths[0].closed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert");
|
||||
let path = folder.join("saved.vectorcraft");
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let before = node(&s, a);
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\
|
||||
p.name = 'changed'; vc.run('file.revert');\
|
||||
try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\
|
||||
var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\
|
||||
fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}");
|
||||
assert_ne!(node(&s, a).path_data(), before.path_data());
|
||||
s.execute("file.revert", &json!({})).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute(
|
||||
"path.setAnchors",
|
||||
&json!({"id": a.0, "subpaths": [
|
||||
{"anchors": [{"x": 0, "y": 0}]},
|
||||
{"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]}
|
||||
]}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap();
|
||||
s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
|
||||
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)]));
|
||||
assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_guides_refuse_path_edits_and_bulk_removal() {
|
||||
let (mut s, a, _) = doc();
|
||||
log(&mut s, "app.activeDocument.pathItems[0].guides = true;");
|
||||
s.set_guides_locked(true);
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
for edit in [
|
||||
"p.pathPoints[0].anchor = [0, 0]",
|
||||
"p.pathPoints[0].remove()",
|
||||
"p.pathPoints.removeAll()",
|
||||
"p.setEntirePath([[0, 0], [1, 1]])",
|
||||
"p.closed = false",
|
||||
"p.translate(1, 0)",
|
||||
"p.filled = false",
|
||||
"p.strokeWidth = 12",
|
||||
"app.activeDocument.pathItems.removeAll()",
|
||||
] {
|
||||
let out =
|
||||
log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"));
|
||||
assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}");
|
||||
assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}");
|
||||
}
|
||||
assert!(is_guide(&s, a));
|
||||
s.set_guides_locked(false);
|
||||
log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);");
|
||||
assert_ne!(art(&s), before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_path_creators_use_the_active_layer_during_isolation() {
|
||||
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
|
||||
let (mut s, a, b) = doc();
|
||||
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("object.isolate", &json!({"id": group.0})).unwrap();
|
||||
let layer = s.active().unwrap().active_layer.unwrap();
|
||||
let before = node(&s, group);
|
||||
let selection = s.active().unwrap().selection.clone();
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
|
||||
let st = s.active().unwrap();
|
||||
let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap();
|
||||
assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}");
|
||||
assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}");
|
||||
assert_eq!(node(&s, group), before, "{create}");
|
||||
assert_eq!(st.isolation, Some(group), "{create}");
|
||||
assert_eq!(st.selection, selection, "{create}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "{create}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_writes_refuse_generated_graph_design_paths() {
|
||||
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
|
||||
for unpainted in [false, true] {
|
||||
let (mut s, a, _) = doc();
|
||||
if unpainted {
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap();
|
||||
}
|
||||
s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute(
|
||||
"graph.create",
|
||||
&json!({
|
||||
"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"
|
||||
}),
|
||||
)
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
|
||||
let graph_node = node(&s, graph);
|
||||
let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap();
|
||||
let mut paths = Vec::new();
|
||||
design.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) {
|
||||
paths.push(n.id);
|
||||
}
|
||||
});
|
||||
let path = paths[0];
|
||||
s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
for edit in [
|
||||
"p.fillColor = c",
|
||||
"p.strokeColor = c",
|
||||
"p.filled = !p.filled",
|
||||
"p.stroked = !p.stroked",
|
||||
"p.strokeWidth = 12",
|
||||
"p.strokeCap = StrokeCap.ROUNDENDCAP",
|
||||
"p.strokeJoin = StrokeJoin.BEVELENDJOIN",
|
||||
"p.strokeMiterLimit = 22",
|
||||
"p.strokeDashes = [3, 4]",
|
||||
] {
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\
|
||||
try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"
|
||||
),
|
||||
);
|
||||
assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}");
|
||||
assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overprint_writes_refuse_generated_graph_design_paths() {
|
||||
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap();
|
||||
s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap();
|
||||
let graph = NodeId(
|
||||
s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
|
||||
let graph_node = node(&s, graph);
|
||||
let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
|
||||
let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap();
|
||||
let mut paths = Vec::new();
|
||||
design.walk(&mut |n| {
|
||||
if matches!(n.kind, NodeKind::Path { .. }) {
|
||||
paths.push(n.id);
|
||||
}
|
||||
});
|
||||
s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap();
|
||||
let before = (art(&s), undo_steps(&s));
|
||||
for property in ["fillOverprint", "strokeOverprint"] {
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\
|
||||
try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);"
|
||||
),
|
||||
);
|
||||
assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}");
|
||||
assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() {
|
||||
let (mut s, a, b) = doc();
|
||||
for i in 0..100 {
|
||||
rect(&mut s, f64::from(i), 10.0, 2.0, 2.0);
|
||||
}
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\
|
||||
for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\
|
||||
for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\
|
||||
var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\
|
||||
vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\
|
||||
try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\
|
||||
paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\
|
||||
vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\
|
||||
try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}",
|
||||
a = a.0,
|
||||
b = b.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn points_read_before_a_removal_or_replacement_go_stale() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1250,6 +1723,78 @@ fn locked_paths_and_wrong_objects_are_refused() {
|
||||
assert!(e.contains("not a PathPoint"), "{e}");
|
||||
}
|
||||
|
||||
/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing.
|
||||
#[test]
|
||||
fn point_edits_of_a_path_on_a_locked_artboard_are_refused() {
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let before = art(&s);
|
||||
let steps = undo_steps(&s);
|
||||
for source in [
|
||||
"app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];",
|
||||
"app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];",
|
||||
"app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);",
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}");
|
||||
}
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a
|
||||
/// later member call does not lose an assignment that returned.
|
||||
#[test]
|
||||
fn a_point_beyond_the_canvas_throws_when_it_is_assigned() {
|
||||
let (mut s, a, _) = doc();
|
||||
let before = node(&s, a).path_data().unwrap().subpaths.clone();
|
||||
let far = crate::MAX_COORD * 1.5;
|
||||
for source in [
|
||||
format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"),
|
||||
format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"),
|
||||
format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"),
|
||||
] {
|
||||
let e = failure(&mut s, &source);
|
||||
assert!(e.contains("outside the canvas"), "{source}: {e}");
|
||||
}
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\
|
||||
q.anchor = [45, 285];\
|
||||
try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\
|
||||
vc.log(q.anchor); vc.log(p.closed);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]);
|
||||
let after = node(&s, a).path_data().unwrap().subpaths.clone();
|
||||
assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays");
|
||||
assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_refuse_moving_gradients_without_the_path() {
|
||||
for transform in
|
||||
["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"]
|
||||
{
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute(
|
||||
"paint.setFill",
|
||||
&json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
|
||||
)
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
|
||||
let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s));
|
||||
let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"));
|
||||
assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}");
|
||||
assert!(
|
||||
out[1].as_str().unwrap().contains("Gradients different from") && out[1].as_str().unwrap().contains("not available yet"),
|
||||
"{transform}: {out:?}"
|
||||
);
|
||||
assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() {
|
||||
let mut s = Session::new();
|
||||
@@ -1676,3 +2221,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
|
||||
log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;");
|
||||
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
|
||||
}
|
||||
|
||||
/// A point change made before a call that fails and is put back, here a new document whose
|
||||
/// profile cannot be read, is kept.
|
||||
#[test]
|
||||
fn a_point_change_before_a_failed_new_document_is_kept() {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap();
|
||||
let (mut s, a, _) = doc();
|
||||
s.attach_new_doc_profiles(dir.clone());
|
||||
let before = node(&s, a).path_data().unwrap().subpaths.clone();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\
|
||||
try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }",
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
assert_eq!(out, vec![json!("refused")]);
|
||||
assert_eq!(s.documents().len(), 1);
|
||||
assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept");
|
||||
}
|
||||
@@ -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();
|
||||
@@ -252,6 +263,131 @@ fn setting_the_value_a_range_has_records_no_undo_step() {
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_attributes_paint_only_their_own_characters() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\
|
||||
var red = new RGBColor(); red.red = 255; b.fillColor = red;\
|
||||
var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\
|
||||
vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\
|
||||
vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);",
|
||||
);
|
||||
let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN);
|
||||
assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}");
|
||||
assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given");
|
||||
assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill");
|
||||
assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke");
|
||||
let runs = paints(&s, id);
|
||||
let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own");
|
||||
assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
|
||||
assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
|
||||
assert!(b.3 > 1.0);
|
||||
assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}");
|
||||
assert!(undo_steps(&s) > before);
|
||||
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;");
|
||||
assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step");
|
||||
log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();");
|
||||
assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_weight_reads_back_in_document_points_on_scaled_type() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
|
||||
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);");
|
||||
assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}");
|
||||
let stored = paints(&s, id)[0].3;
|
||||
assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}");
|
||||
let steps = undo_steps(&s);
|
||||
log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;");
|
||||
assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_text_paint_is_refused_without_a_change() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let before = undo_steps(&s);
|
||||
let runs = paints(&s, id);
|
||||
for (src, want) in [
|
||||
("r.fillColor = 'red';", "fillColor must be a color object"),
|
||||
("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"),
|
||||
("r.fillColor = new GradientColor();", "not available yet"),
|
||||
("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"),
|
||||
("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}"));
|
||||
assert!(e.contains(want), "{src}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(paints(&s, id), runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_or_locked_type_is_not_edited() {
|
||||
let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
for hide in ["t.locked = true;", "t.hidden = true;"] {
|
||||
for edit in [
|
||||
"r.characters[1].fillColor = red;",
|
||||
"r.size = 30;",
|
||||
"r.contents = 'xyz';",
|
||||
"r.characters.add('!');",
|
||||
"r.justification = Justification.CENTER;",
|
||||
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);",
|
||||
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);",
|
||||
"var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);",
|
||||
] {
|
||||
// Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden.
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let before = state(&s, id);
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"),
|
||||
);
|
||||
assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}");
|
||||
assert_eq!(state(&s, id), before, "{hide} {edit}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\
|
||||
var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);",
|
||||
);
|
||||
assert_eq!(plain(&s, id), "\u{1F600}!X");
|
||||
// Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's
|
||||
// end joins the range.
|
||||
assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]);
|
||||
// An empty range there sits after the character too, and styling it changes nothing.
|
||||
let runs = paints(&s, id);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\
|
||||
var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(0)]);
|
||||
assert_eq!(paints(&s, id), runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
@@ -465,7 +601,7 @@ fn text_fonts_list_and_assign_fonts_by_name() {
|
||||
&format!(
|
||||
"var f = app.textFonts, m = '';\
|
||||
try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
|
||||
vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\
|
||||
vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\
|
||||
vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);"
|
||||
@@ -547,7 +683,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
}
|
||||
// Empty contents add nothing; bad arguments throw before anything changes.
|
||||
let (mut s, id) = doc_with("ab");
|
||||
s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap();
|
||||
let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap());
|
||||
let before = undo_steps(&s);
|
||||
// `textFrames` lists the topmost first, so the newer "other" is [0].
|
||||
let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);");
|
||||
@@ -563,7 +699,62 @@ fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
assert!(e.contains(want), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(plain(&s, other), "other");
|
||||
assert_eq!(plain(&s, id), "ab");
|
||||
// A range of a frame that was removed is stale, not of the wrong class.
|
||||
let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);");
|
||||
assert!(e.contains("Stale text range"), "{e}");
|
||||
assert_eq!(plain(&s, id), "ab");
|
||||
}
|
||||
|
||||
/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are
|
||||
/// not changed.
|
||||
#[test]
|
||||
fn protected_type_and_paths_are_not_converted_or_edited() {
|
||||
let (mut s, id) = doc_with("abc");
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] {
|
||||
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}"));
|
||||
assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}");
|
||||
}
|
||||
assert_eq!(plain(&s, id), "abc");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap();
|
||||
for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] {
|
||||
let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};"));
|
||||
assert!(e.contains("Cannot edit PathItem"), "{call}: {e}");
|
||||
assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as
|
||||
/// `pathItems.removeAll()` does.
|
||||
#[test]
|
||||
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
|
||||
let (mut s, id) = doc_with("ab");
|
||||
let lock = |s: &mut Session, locked: bool| {
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = locked;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
lock(&mut s, true);
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}");
|
||||
assert_eq!(plain(&s, id), "ab");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
lock(&mut s, false);
|
||||
log(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -450,12 +450,14 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"TextRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
|
||||
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
|
||||
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
|
||||
duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \
|
||||
getLocalCharOverridesJSON= \
|
||||
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
|
||||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
|
||||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= strokeColor strokeColor= \
|
||||
strokeWeight strokeWeight= textFont textFont= textRanges \
|
||||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||||
verticalScale= words",
|
||||
),
|
||||
@@ -468,9 +470,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("CharacterAttributes.", "prototype"),
|
||||
(
|
||||
"CharacterAttributes.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||||
underline= verticalScale verticalScale=",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \
|
||||
leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \
|
||||
strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=",
|
||||
),
|
||||
("ParagraphAttributes.", "prototype"),
|
||||
(
|
||||
@@ -485,9 +487,9 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("CharacterStyleAttributes.", "prototype"),
|
||||
(
|
||||
"CharacterStyleAttributes.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
|
||||
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
|
||||
underline= verticalScale verticalScale=",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \
|
||||
leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \
|
||||
strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=",
|
||||
),
|
||||
("ParagraphStyles.", "prototype"),
|
||||
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
|
||||
@@ -523,12 +525,12 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"StoryRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
|
||||
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
|
||||
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
|
||||
contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \
|
||||
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
|
||||
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
|
||||
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
|
||||
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||||
strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||||
underline underline= verticalScale verticalScale= words",
|
||||
),
|
||||
("StoryCharacters.", "prototype"),
|
||||
|
||||
+32
-13
@@ -636,7 +636,7 @@ left out or null; `appearance.setActiveItem` reads a null `index` as clearing th
|
||||
whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the
|
||||
default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or
|
||||
played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of
|
||||
1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000.
|
||||
1 or more is rounded and kept to at most 1000, and a `rows` is rounded, must then be 1 or more, and is kept to at most 1000.
|
||||
A command that leaves out an object selected inside a
|
||||
selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes
|
||||
`ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value
|
||||
@@ -3642,14 +3642,19 @@ 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
|
||||
500), `strokeDashes` and `strokeDashOffset`, and takes the page item transforms above. 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`. Changes to the
|
||||
`object.setOverprint`.
|
||||
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, edits the points of another path, or reads
|
||||
the points of another path in the same Objects on Path group, and when the script ends;
|
||||
@@ -3671,7 +3676,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
|
||||
@@ -3682,7 +3688,8 @@ through `$`:
|
||||
Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`.
|
||||
Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of
|
||||
another path in the same Objects on Path group. 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
|
||||
@@ -3698,7 +3705,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,
|
||||
@@ -3706,13 +3713,15 @@ through `$`:
|
||||
64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to
|
||||
`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
|
||||
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` different from
|
||||
`changePositions` 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, that is in a hidden or locked layer or group, or that is on a locked artboard throws
|
||||
`Cannot edit` with nothing changed. `pathItems.removeAll()` deletes nothing and throws an error when any path is
|
||||
hidden or locked or is inside a hidden or locked layer, group, compound path or other object (`cannot delete hidden or locked paths`), and otherwise
|
||||
when any path is on a locked artboard (`cannot delete objects on a locked artboard`), each followed by a colon and
|
||||
the ids of up to 20 of those paths. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
the ids of up to 20 of those paths. A point given to `setEntirePath` or assigned to
|
||||
`anchor`, `leftDirection` or `rightDirection` whose x or y is more than 4,000,000 pt from the origin throws a range
|
||||
error when it is given, and the path keeps its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new
|
||||
art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops
|
||||
are not available yet.
|
||||
@@ -3737,7 +3746,11 @@ through `$`:
|
||||
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
|
||||
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`
|
||||
value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and
|
||||
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame`
|
||||
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. `removeAll()` throws
|
||||
and deletes nothing when any type object is hidden or locked, is in a hidden or locked layer or group, or is on a
|
||||
locked artboard (`cannot delete objects on a locked artboard`). A text edit, `createOutline()` or a conversion of
|
||||
such a type object, and `areaText` or `pathText` given such a path, throw `Cannot edit` with nothing changed. A
|
||||
`TextFrame`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
|
||||
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
|
||||
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
|
||||
@@ -3752,8 +3765,11 @@ through `$`:
|
||||
`add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its
|
||||
range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to
|
||||
5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and
|
||||
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`,
|
||||
set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are
|
||||
`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. 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`
|
||||
@@ -3812,7 +3828,8 @@ through `$`:
|
||||
style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the
|
||||
style's document; a character style on an empty range inside text changes nothing, on empty text it styles the
|
||||
text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left
|
||||
out is false. A range lists each style once, in the order
|
||||
out is false. `applyTo` on a frame that is hidden or locked, in a hidden or locked layer or group, or on a locked
|
||||
artboard throws `Cannot edit` with nothing changed. A range lists each style once, in the order
|
||||
its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove
|
||||
styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made
|
||||
through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws
|
||||
@@ -11109,6 +11126,8 @@ with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays
|
||||
`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
|
||||
|
||||
+1
-1
@@ -209,7 +209,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 `<pattern>`/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) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 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, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines 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, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, 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, text lines, gradient stops and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; 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); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 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 <name>, 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), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), 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 |
|
||||
|
||||
@@ -1116,12 +1116,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- 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: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.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, guide state, selected points, 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`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `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, guide state, selected points, 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`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
|
||||
Reference in new issue
Block a user