mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Scripts: path creation and paint edits replay as run; mixed picks keep their anchors
Scripted shapes record the layer they were drawn on, so replay does not draw them behind other art or inside an isolated group. Paint edits on objects keep the new-art defaults on replay, and a solid new-art color copied to a path keeps its color model. An anchor picked next to a selected segment stays selected and is listed by selectedPathPoints. closed set on an empty path applies to its first points. Text fillColor and strokeColor reflect as Color. Saved file.new steps keep the old row rounding.
This commit is contained in:
@@ -441,6 +441,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'
|
||||
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
|
||||
/// ([`plugin::run_command`]), which needs the command's id.
|
||||
pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<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
|
||||
),
|
||||
|
||||
@@ -870,7 +870,14 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
|
||||
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let size = str_param(p, "preset").map(|_| sorted(&base));
|
||||
let mut settings = base.with_params(p, C)?;
|
||||
let mut params = p.clone();
|
||||
if s.replaying()
|
||||
&& let Some(rows) = params.pointer_mut("/artboardLayout/rows")
|
||||
&& let Some(value) = rows.as_f64().filter(|r| r.is_finite() && *r >= 1.0)
|
||||
{
|
||||
*rows = json!(value.round().min(MAX_ARTBOARDS as f64) as u32);
|
||||
}
|
||||
let mut settings = base.with_params(¶ms, C)?;
|
||||
if size != Some(sorted(&settings)) {
|
||||
settings.name = "Custom".into();
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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
|
||||
),
|
||||
|
||||
@@ -289,19 +289,11 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
|
||||
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active
|
||||
/// layer, then puts the drawing mode back.
|
||||
fn drawing_normally<T>(h: &super::Host, parent: Option<NodeId>, f: impl FnOnce() -> T) -> T {
|
||||
let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal);
|
||||
let isolation = h.session.borrow_mut().active_mut().map(|st| (st.uid, std::mem::replace(&mut st.isolation, parent)));
|
||||
let r = f();
|
||||
if let Some((uid, isolation)) = isolation
|
||||
&& let Some(st) = h.session.borrow_mut().document_mut(uid)
|
||||
{
|
||||
st.isolation = isolation;
|
||||
}
|
||||
h.session.borrow_mut().draw_mode = kept;
|
||||
r
|
||||
/// Runs a path creation command with its layer placement recorded.
|
||||
fn drawing_normally(h: &super::Host, parent: Option<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
|
||||
@@ -315,6 +307,9 @@ fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::r
|
||||
}
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
o.entry("ids").or_insert_with(|| json!([item.id.0]));
|
||||
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
|
||||
o.insert("objectOnly".into(), json!(true));
|
||||
}
|
||||
}
|
||||
let result = keeping_paint(h, || edit_item(h, item, id, ¶ms))?;
|
||||
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
|
||||
@@ -453,7 +448,7 @@ fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
let made = on_doc(h, doc.uid, true, |h| {
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let id = made_id(&drawing_normally(h, parent, || super::command_value(h, id, params))?)?;
|
||||
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
@@ -613,9 +608,9 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
|
||||
let id = made_id(&drawing_normally(h, parent, || super::command_value(h, "path.create", &json!({"d": ""})))?)?;
|
||||
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
|
||||
if unpainted {
|
||||
keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?;
|
||||
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
|
||||
}
|
||||
Ok(id)
|
||||
})?;
|
||||
@@ -640,7 +635,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let closed = boolean(arg(a, 1), "closed")?;
|
||||
let item = this_path(h, a)?;
|
||||
edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
edit_points(h, item, |subs| {
|
||||
if subs.is_empty() && closed {
|
||||
subs.push(SubPath::new(Vec::new(), closed));
|
||||
} else {
|
||||
subs.iter_mut().for_each(|sp| sp.closed = closed);
|
||||
}
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -836,10 +837,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul
|
||||
Ok(match linked {
|
||||
true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}),
|
||||
true => json!({"swatch": name}),
|
||||
false => json!({"color": colors::param(color)}),
|
||||
false => json!({"color": colors::param(color), "keepModel": true}),
|
||||
})
|
||||
}
|
||||
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})),
|
||||
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})),
|
||||
Paint::Gradient(g) => {
|
||||
let mut g = g.clone();
|
||||
if g.geom.is_some() || g.freeform.is_some() {
|
||||
@@ -1502,12 +1503,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[
|
||||
if held {
|
||||
return true;
|
||||
}
|
||||
if !sel.contains(id) || sel.segments.contains_key(&id) {
|
||||
if !sel.contains(id) {
|
||||
return false;
|
||||
}
|
||||
match sel.partial(id) {
|
||||
None => true,
|
||||
Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)),
|
||||
Some(picked) => locate(subs, i).is_some_and(|(s, j)| {
|
||||
picked.contains(&(s, j))
|
||||
&& !sel
|
||||
.segments
|
||||
.get(&id)
|
||||
.is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j)))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1592,17 +1599,11 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let picked: Vec<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;
|
||||
for (s, sp) in pd.subpaths.iter().enumerate() {
|
||||
let n = sp.anchors.len();
|
||||
out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j));
|
||||
first += n;
|
||||
}
|
||||
out
|
||||
let total: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum();
|
||||
(0..total).filter(|&i| anchor_selected(sel, item.id, held, &pd.subpaths, i)).collect()
|
||||
})?;
|
||||
h.charge_call(picked.len() as u64)?;
|
||||
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
|
||||
|
||||
@@ -1617,6 +1617,7 @@ fn attr_type(attr: Attr) -> &'static str {
|
||||
match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
Attr::FillColor | Attr::StrokeColor => "Color",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1024,6 +1024,22 @@ fn file_new_takes_the_rows_of_a_grid_by_column() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_new_replays_legacy_fractional_and_large_rows() {
|
||||
for (rows, rounded) in [(3.6, 4), (1001.2, 1000)] {
|
||||
let params = json!({"width": 100, "height": 100, "artboards": 5, "artboardLayout": {"layout": "gridByColumn", "rows": rows}});
|
||||
let mut s = Session::new();
|
||||
assert!(s.execute("file.new", ¶ms).unwrap_err().to_string().contains("rows must be a whole number"));
|
||||
s.replay("file.new", ¶ms).unwrap();
|
||||
let mut expected = Session::new();
|
||||
let mut params = params;
|
||||
params["artboardLayout"]["rows"] = json!(rounded);
|
||||
expected.execute("file.new", ¶ms).unwrap();
|
||||
let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|b| b.rect).collect::<Vec<_>>();
|
||||
assert_eq!(boards(&s), boards(&expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_listed_preset_keeps_more_rows_than_artboards() {
|
||||
use crate::cmd::newdoc::{ArtboardLayout, DocSettings};
|
||||
|
||||
@@ -49,6 +49,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node {
|
||||
s.active().unwrap().doc.node(id).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_creation_replays_on_top_of_the_active_layer() {
|
||||
for mode in ["behind", "inside", "isolation"] {
|
||||
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
|
||||
let setup = || {
|
||||
let (mut s, a, b) = doc();
|
||||
if mode == "isolation" {
|
||||
let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone();
|
||||
s.execute("object.isolate", &json!({"id": group})).unwrap();
|
||||
} else {
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut s = setup();
|
||||
let start = s.journal.len();
|
||||
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
|
||||
let mut replay = setup();
|
||||
for (id, params) in s.journal.since(start) {
|
||||
replay.replay(id, params).unwrap();
|
||||
}
|
||||
assert_eq!(art(&replay), art(&s), "{mode}: {create}");
|
||||
assert_eq!(replay.draw_mode, s.draw_mode);
|
||||
assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_paint_edits_replay_without_changing_new_art() {
|
||||
let (mut s, a, _) = doc();
|
||||
let start = s.journal.len();
|
||||
log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\
|
||||
p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\
|
||||
app.activeDocument.pathItems.rectangle(100, 200, 20, 30);",
|
||||
);
|
||||
let (mut replay, _, _) = doc();
|
||||
for (id, params) in s.journal.since(start) {
|
||||
replay.replay(id, params).unwrap();
|
||||
}
|
||||
assert_eq!(node(&replay, a).appearance, node(&s, a).appearance);
|
||||
assert_eq!(art(&replay), art(&s));
|
||||
assert_eq!(replay.paint, s.paint);
|
||||
assert_eq!(replay.fill_active, s.fill_active);
|
||||
assert_eq!(replay.recent_colors, s.recent_colors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_anchor_and_segment_picks_keep_independent_anchors() {
|
||||
for selected in ["ANCHORPOINT", "NOSELECTION"] {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap();
|
||||
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\
|
||||
vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\
|
||||
p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);",
|
||||
if selected == "ANCHORPOINT" { 1 } else { 3 }
|
||||
),
|
||||
);
|
||||
assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]);
|
||||
assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 }));
|
||||
assert!(!s.active().unwrap().selection.segments.contains_key(&a));
|
||||
assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] }));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_path_keeps_closed_before_points_are_added() {
|
||||
for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);"] {
|
||||
let (mut s, _, _) = doc();
|
||||
let start = s.journal.len();
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"),
|
||||
);
|
||||
assert_eq!(out, [json!(true), json!(true)]);
|
||||
let (mut replay, _, _) = doc();
|
||||
for (id, params) in s.journal.since(start) {
|
||||
replay.replay(id, params).unwrap();
|
||||
}
|
||||
assert_eq!(art(&replay), art(&s));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabling_path_paint_preserves_the_new_art_color_model() {
|
||||
for fill in [true, false] {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
|
||||
s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap();
|
||||
let new_art = s.new_art();
|
||||
let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() };
|
||||
log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" });
|
||||
let n = node(&s, a);
|
||||
assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each number of `v` rounded to 3 decimals, in place.
|
||||
fn rounded(v: &Value) -> Value {
|
||||
match v {
|
||||
|
||||
@@ -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();
|
||||
|
||||
+17
-7
@@ -3124,7 +3124,8 @@ through `$`:
|
||||
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`,
|
||||
`fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and
|
||||
`strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with
|
||||
`text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are
|
||||
`text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports
|
||||
`fillColor` and `strokeColor` as `Color`. Paragraph attributes are
|
||||
`justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`,
|
||||
or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`,
|
||||
`spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts`
|
||||
@@ -3175,7 +3176,9 @@ through `$`:
|
||||
radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`,
|
||||
`shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new
|
||||
art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing
|
||||
mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
|
||||
mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and
|
||||
record this placement for replay. A null `onLayer` draws normally on the active layer.
|
||||
A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
|
||||
members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`,
|
||||
`guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`,
|
||||
`stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to
|
||||
@@ -3183,8 +3186,11 @@ through `$`:
|
||||
(counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The
|
||||
geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the
|
||||
stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through
|
||||
`object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the
|
||||
points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
|
||||
`object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`.
|
||||
Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy
|
||||
and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept
|
||||
this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`.
|
||||
Changes to the points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
|
||||
`path.setAnchors` before the script uses any other member or command, or the points of another path, and when the
|
||||
script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points
|
||||
read as the grid snaps them.
|
||||
@@ -3204,7 +3210,8 @@ through `$`:
|
||||
the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues`
|
||||
and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`.
|
||||
VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is
|
||||
closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner
|
||||
closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first
|
||||
subpath. `setEntirePath` takes at most 100,000 points and gives corner
|
||||
points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and
|
||||
`pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point
|
||||
whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed
|
||||
@@ -3212,7 +3219,8 @@ through `$`:
|
||||
than the object model changed the path's points (a command run with `vc.run`, such as `path.setAnchors`,
|
||||
`object.move` or `edit.undo`); points stay valid through the object model's other changes to the path or to an
|
||||
object that holds it, such as `translate()`. Every point of a path selected as a whole is a selected anchor point,
|
||||
and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole.
|
||||
and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment
|
||||
picks. A path in a selected group or compound path is selected as a whole.
|
||||
Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT`
|
||||
to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a
|
||||
path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's
|
||||
@@ -3228,7 +3236,7 @@ through `$`:
|
||||
was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a
|
||||
global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
|
||||
art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the
|
||||
stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
|
||||
stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
|
||||
it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error.
|
||||
`fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and
|
||||
radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000,
|
||||
@@ -10492,6 +10500,8 @@ the rows give the current number of artboards, and New Document drops the rows w
|
||||
`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
|
||||
value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see
|
||||
[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)).
|
||||
Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still
|
||||
require whole row counts from 1 to 1000.
|
||||
`file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets,
|
||||
kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be
|
||||
passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets
|
||||
|
||||
Reference in New Issue
Block a user