Scripts: swatches, spots, color groups, symbols, graphic styles and brushes

Each document gains the swatches, spots, swatchGroups, symbols,
symbolItems, graphicStyles and brushes collections that the scripting
reference lists (https://ai-scripting.docsforadobe.dev/jsobjref/Document/).
Each change runs the existing Swatches, Symbols, Graphic Styles or
Brushes command inside the run's transaction.

- Resource objects follow renames made through them and throw
  Stale <Class> once the resource is removed, or renamed or deleted
  with vc.run, so a new resource with the old name is not theirs.
- Swatches, spots and color groups share their names: a name one of
  them already has throws instead of taking a numbered name.
- None, Registration and the Default Graphic Style cannot be renamed
  or removed, and removeAll() keeps them.
- spots.add() converts the current fill to the document's color space
  unless it is Lab; a spot's color stays in that space or Lab.
- A tint of a spot reads as a SpotColor of that spot at its tint.
- Brush.applyTo throws for a guide, a clipping path and a path in a
  compound path, which brush.apply does not brush.
- Objects of another document throw before any command runs.
- Document.gradients, Document.patterns and assigning a SpotColor to
  art are not available yet.

The host name check lists the new classes, members and enumerations.
Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
dotCooCoo committed 2026-11-21 13:44:28 -08:00
1 parent 43813db855
commit 4ac416d7d0
8 files changed
+1675 -17

No files matched your search

+21 -6
View File
@@ -40,6 +40,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session};
mod colors;
mod paths;
mod resources;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
@@ -96,6 +97,8 @@ pub(super) struct State {
items: RefCell<Option<ItemList>>,
/// The last list of a document's paths ([`paths`]), kept while that document is unchanged.
paths: RefCell<Option<ItemList>>,
/// The swatches, symbols, styles and brushes the run's objects name ([`resources`]).
resources: RefCell<resources::Table>,
saving: Cell<bool>,
}
@@ -126,6 +129,12 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
r
}
/// Makes the run's swatch, symbol, style and brush objects whose resource a `vc.run` command
/// removed or renamed stale, so a new resource that takes the name later is not theirs.
pub(super) fn forget_removed(h: &Host) {
resources::forget_removed(h);
}
/// A document's uid, the document as it was, and the ids of its page items then.
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
@@ -1750,10 +1759,9 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("selection", property(l, doc_selection, doc_set_selection)),
("pathItems", get(l, paths::doc_path_items)),
]);
document.extend(resources::document_members(l));
document.extend(
["layers", "artboards", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
.into_iter()
.map(|m| later(l, "Document", m)),
["layers", "artboards", "groupItems", "textFrames", "views", "activeLayer", "saveAs", "close"].into_iter().map(|m| later(l, "Document", m)),
);
classes.push(class("Document", None, document, None));
classes.push(class(
@@ -1818,12 +1826,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
.map(|m| later(l, "PageItem", m)),
);
classes.push(class("PageItem", None, page_item, None));
classes.extend(
ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), if *c == "PathItem" { paths::path_item_members(l) } else { Vec::new() }, None)),
);
classes.extend(ITEM_CLASSES.iter().map(|c| {
let members = match *c {
"PathItem" => paths::path_item_members(l),
"SymbolItem" => resources::symbol_item_members(l),
_ => Vec::new(),
};
class(c, Some("PageItem"), members, None)
}));
classes.extend(paths::classes(l));
classes.extend(colors::classes(l));
classes.extend(resources::classes(l));
paths::install_enums(realm)?;
resources::install_enums(realm)?;
classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])
}
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -1297,7 +1297,9 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
let bytes = args.iter().map(data_size).sum();
host.charge_call(bytes)?;
bump(&host.counts.vc_run);
command(host, &id, &params)
let r = command(host, &id, &params);
dom::forget_removed(host);
r
}
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
+1
View File
@@ -174,6 +174,7 @@ mod script_dialogs;
mod script_dollar;
mod script_dom;
mod script_dom_paths;
mod script_dom_resources;
mod script_engines;
mod script_folder;
mod script_include;
@@ -0,0 +1,433 @@
//! The script object model's swatches, color groups, spots, symbols, graphic styles and brushes.
use serde_json::{Value, json};
use crate::*;
fn run(s: &mut Session, source: &str) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
}
/// What the run logged.
fn log(s: &mut Session, source: &str) -> Vec<Value> {
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
r["log"].as_array().cloned().unwrap_or_default()
}
/// The message of the run's failure.
fn failure(s: &mut Session, source: &str) -> String {
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
}
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
}
/// A 400 × 300 pt RGB document with one rectangle.
fn doc() -> (Session, NodeId) {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
s.execute("select.none", &json!({})).unwrap();
(s, a)
}
fn undo_steps(s: &Session) -> usize {
s.active().unwrap().history.undo.len()
}
fn swatch_names(s: &mut Session) -> Vec<String> {
let l = s.execute("swatch.list", &json!({})).unwrap();
l["swatches"].as_array().unwrap().iter().map(|w| w["name"].as_str().unwrap().to_string()).collect()
}
/// The document's resources, to show that a failed call changed nothing.
fn resources(s: &Session) -> String {
let d = &s.active().unwrap().doc;
format!("{:?}{:?}{:?}{:?}{:?}", *d.swatches, *d.swatch_groups, *d.graphic_styles, d.symbols, d.layers)
}
#[test]
fn swatches_are_live_and_keep_reserved_entries() {
let (mut s, _) = doc();
let names = swatch_names(&mut s);
let out = log(
&mut s,
"var w = app.activeDocument.swatches; vc.log(w.length); vc.log(w.typename); vc.log(w.parent.typename);\
vc.log(w[0].name); vc.log(w[1].name); vc.log(w[1].typename); vc.log(w[w.length] === undefined);\
vc.log(w.getByName('Black').color.typename); vc.log(w.getSelected().length);",
);
assert_eq!(
out,
vec![
json!(names.len()),
json!("Swatches"),
json!("Document"),
json!(names[0]),
json!("[Registration]"),
json!("Swatch"),
json!(true),
json!("RGBColor"),
json!(0)
]
);
let out = log(
&mut s,
"var w = app.activeDocument.swatches, n = w.add(); n.name = 'Script Ink';\
var c = new RGBColor(); c.red = 10; c.green = 20; c.blue = 30; n.color = c;\
vc.log(w.getByName('Script Ink').color.green); vc.log(n.name);",
);
assert_eq!(out, vec![json!(20), json!("Script Ink")]);
assert!(swatch_names(&mut s).contains(&"Script Ink".to_string()));
let steps = undo_steps(&s);
log(&mut s, "app.activeDocument.swatches.removeAll();");
assert_eq!(undo_steps(&s), steps + 1);
let left = swatch_names(&mut s);
assert_eq!(left, vec![names[0].clone(), "[Registration]".to_string()]);
for script in ["app.activeDocument.swatches[1].name = 'R';", "app.activeDocument.swatches[0].remove();"] {
assert!(failure(&mut s, script).contains("is built in"), "{script}");
}
let steps = undo_steps(&s);
log(&mut s, "app.activeDocument.swatches.removeAll();");
assert_eq!(undo_steps(&s), steps, "a removeAll with nothing to remove records no step");
}
#[test]
fn swatches_add_saves_a_gradient_fill_as_a_gradient() {
let (mut s, _) = doc();
let ramp = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]});
s.execute("paint.setFill", &json!({"gradient": ramp})).unwrap();
let out = log(&mut s, "vc.log(app.activeDocument.swatches.add().color.typename);");
assert_eq!(out, vec![json!("GradientColor")]);
}
#[test]
fn resource_objects_go_stale_after_remove_and_follow_renames() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var w = app.activeDocument.swatches.getByName('Black'); w.name = 'Ink'; vc.log(w.name);\
var again = app.activeDocument.swatches.getByName('Ink'); vc.log(again.name);",
);
assert_eq!(out, vec![json!("Ink"), json!("Ink")]);
let cases = [
("var w = app.activeDocument.swatches.getByName('Ink'); w.remove(); w.name;", "Stale Swatch"),
("var w = app.activeDocument.swatches.getByName('White'); w.remove(); w.typename;", "Stale Swatch"),
("var w = app.activeDocument.swatches.getByName('White'); vc.run('swatch.delete', {name: 'White'}); w.color;", "Stale Swatch"),
(
"var g = app.activeDocument.graphicStyles.getByName('Default Graphic Style'); vc.run('graphicStyle.rename', {name: g.name, to: 'X'}); g.name;",
"Stale GraphicStyle",
),
("var w = app.activeDocument.swatches.getByName('Red'); w.remove(); app.activeDocument.swatches.add().name = 'Red'; w.name;", "Stale Swatch"),
(
"var w = app.activeDocument.swatches.getByName('Lime'); vc.run('swatch.delete', {name: 'Lime'}); vc.run('swatch.new', {name: 'Lime', color: '#00ff00'}); w.name;",
"Stale Swatch",
),
];
for (script, message) in cases {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
}
#[test]
fn hostile_names_and_values_are_refused_without_change() {
let (mut s, _) = doc();
let before = resources(&s);
let steps = undo_steps(&s);
let long = "x".repeat(1025);
let cases = [
("app.activeDocument.swatches.getByName('Black').name = 'a\\u0007b';".to_string(), "control characters"),
("app.activeDocument.swatches.getByName('Black').name = ' ';".to_string(), "cannot be empty"),
(format!("app.activeDocument.swatches.getByName('Black').name = '{long}';"), "longer than 1024 bytes"),
("app.activeDocument.swatches.getByName('Black').name = 7;".to_string(), "must be a string"),
("app.activeDocument.swatches.getByName('Black').name = 'White';".to_string(), "already exists"),
("var d = app.activeDocument, p = d.spots.add(); p.name = 'Black';".to_string(), "a swatch or color group named Black already exists"),
(
"var d = app.activeDocument; d.swatchGroups.add().name = 'Mine'; d.swatches.getByName('White').name = 'Mine';".to_string(),
"a swatch or color group named Mine already exists",
),
("app.activeDocument.swatches.getByName('Black').color = new NoColor();".to_string(), "cannot be NoColor"),
("app.activeDocument.swatches.getByName('Black').color = {typename: 'RGBColor', red: 300};".to_string(), "from 0 to 255"),
("app.activeDocument.swatches.getByName('nope');".to_string(), "Not found"),
("app.activeDocument.swatches.index({});".to_string(), "name or an index"),
("app.activeDocument.symbols.add(app.activeDocument);".to_string(), "not a page item"),
("app.activeDocument.symbols.add(app.activeDocument.pageItems[0], 'SymbolRegistrationPoint.NOPE');".to_string(), "SymbolRegistrationPoint"),
("app.activeDocument.symbolItems.add(app.activeDocument.swatches[2]);".to_string(), "not a Symbol"),
("app.activeDocument.graphicStyles[0].applyTo([app.activeDocument.pageItems[0]]);".to_string(), "one page item"),
];
for (script, message) in &cases {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn spots_keep_their_kind_and_their_document_color_space() {
let (mut s, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, p = d.spots.add(); p.name = 'Pea'; p.colorType = ColorModel.SPOT;\
var c = new RGBColor(); c.red = 90; c.green = 200; c.blue = 30; p.color = c;\
vc.log(d.spots.length); vc.log(p.typename); vc.log(p.colorType); vc.log(p.spotKind); vc.log(p.getInternalColor());\
var w = d.swatches.getByName('Pea').color; vc.log(w.typename); vc.log(w.spot.name); vc.log(w.tint);",
);
assert_eq!(
out,
vec![
json!(1),
json!("Spot"),
json!("ColorModel.SPOT"),
json!("SpotColorKind.SPOTRGB"),
json!([90, 200, 30]),
json!("SpotColor"),
json!("Pea"),
json!(100)
]
);
let before = resources(&s);
for (script, message) in [
("var p = app.activeDocument.spots[0]; p.color = new CMYKColor();", "must be an RGBColor"),
("app.activeDocument.spots[0].colorType = ColorModel.PROCESS;", "stays a spot color"),
("app.activeDocument.spots[0].colorType = 3;", "ColorModel value"),
] {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
log(&mut s, "var p = app.activeDocument.spots[0]; var l = new LabColor(); l.l = 50; p.color = l;");
assert_eq!(log(&mut s, "vc.log(app.activeDocument.spots[0].spotKind);"), vec![json!("SpotColorKind.SPOTLAB")]);
log(&mut s, "app.activeDocument.spots.removeAll();");
assert!(!swatch_names(&mut s).contains(&"Pea".to_string()));
}
#[test]
fn a_tint_of_a_spot_reads_as_that_spot_at_the_tint() {
let (mut s, _) = doc();
s.execute("swatch.new", &json!({"name": "Ink", "color": "#204080", "spot": true})).unwrap();
s.execute("paint.setFill", &json!({"swatch": "Ink"})).unwrap();
let tint = s.execute("swatch.new", &json!({"tint": 40})).unwrap()["name"].as_str().unwrap().to_string();
let out = log(
&mut s,
&format!("var c = app.activeDocument.swatches.getByName('{tint}').color; vc.log(c.typename); vc.log(c.spot.name); vc.log(c.tint);"),
);
assert_eq!(out, vec![json!("SpotColor"), json!("Ink"), json!(40)]);
}
#[test]
fn spots_add_converts_the_fill_to_the_document_color_space() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000", "keepModel": true})).unwrap();
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
assert!(rgb, "the current fill is RGB in a CMYK document");
let out = log(&mut s, "var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename);");
assert_eq!(out, vec![json!("SpotColorKind.SPOTCMYK"), json!("CMYKColor")]);
}
#[test]
fn spots_add_converts_a_cmyk_or_gray_fill_in_an_rgb_document() {
for fill in [json!({"c": 0, "m": 100, "y": 100, "k": 0}), json!({"gray": 40})] {
let (mut s, _) = doc();
s.execute("paint.setFill", &json!({"color": fill})).unwrap();
let rgb = matches!(s.new_art().fill_paint(), vectorcraft_color::Paint::Solid { color: vectorcraft_color::Color::Rgb { .. }, .. });
assert!(!rgb, "the current fill {fill} is not RGB in an RGB document");
let out = log(
&mut s,
"var p = app.activeDocument.spots.add(); vc.log(p.spotKind); vc.log(p.color.typename); p.color = p.color; vc.log(p.name == '');",
);
assert_eq!(out, vec![json!("SpotColorKind.SPOTRGB"), json!("RGBColor"), json!(false)], "{fill}");
}
}
#[test]
fn color_groups_hold_solid_swatches_only() {
let (mut s, _) = doc();
s.execute(
"swatch.new",
&json!({"name": "Ramp", "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}),
)
.unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, g = d.swatchGroups.add(); g.name = 'Script Group';\
g.addSwatch(d.swatches.getByName('Black')); g.addSwatch(d.swatches.getByName('Black'));\
var all = g.getAllSwatches(); vc.log(all.length); vc.log(all[0].name); vc.log(d.swatchGroups.getByName('Script Group').typename);",
);
assert_eq!(out, vec![json!(1), json!("Black"), json!("SwatchGroup")]);
let before = resources(&s);
for (script, message) in [
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches.getByName('Ramp'));", "solid colors only"),
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSwatch(d.swatches[0]);", "is built in"),
("var d = app.activeDocument; d.swatchGroups.getByName('Script Group').addSpot(d.swatches.getByName('Black'));", "not a Spot"),
] {
let e = failure(&mut s, script);
assert!(e.contains(message), "{script}: {e}");
}
assert_eq!(resources(&s), before);
let out = log(
&mut s,
"var d = app.activeDocument, g = d.swatchGroups.getByName('Script Group'), b = g.getAllSwatches()[0];\
g.removeAll(); vc.log(g.getAllSwatches().length); try { b.name; } catch (e) { vc.log(String(e.message)); }\
g.remove(); try { g.name; } catch (e) { vc.log(String(e.message)); }",
);
assert_eq!(out, vec![json!(0), json!("Stale Swatch"), json!("Stale SwatchGroup")]);
}
#[test]
fn symbols_add_keeps_the_source_and_instances_follow_their_symbol() {
let (mut s, a) = doc();
let out = log(
&mut s,
"var d = app.activeDocument, n = d.pageItems.length, sym = d.symbols.add(d.pageItems[0], SymbolRegistrationPoint.SYMBOLTOPLEFTPOINT);\
vc.log(d.pageItems.length === n); vc.log(sym.typename); vc.log(d.symbols.length);\
sym.name = 'Mark'; var copy = sym.duplicate(); vc.log(copy.name);\
var inst = d.symbolItems.add(sym); vc.log(inst.typename); vc.log(inst.symbol.name); vc.log(d.symbolItems.length);\
inst.symbol = copy; vc.log(inst.symbol.name); vc.log(d.selection === null);",
);
assert_eq!(
out,
vec![
json!(true),
json!("Symbol"),
json!(1),
json!("Mark copy"),
json!("SymbolItem"),
json!("Mark"),
json!(1),
json!("Mark copy"),
json!(true)
]
);
assert!(s.active().unwrap().doc.node(a).is_some(), "the source art stays");
let l = s.execute("symbol.list", &json!({})).unwrap();
assert_eq!(l["symbols"][0]["registration"], json!(0));
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.symbolItems.removeAll(); vc.log(d.symbols.length);");
assert_eq!(undo_steps(&s), steps + 1);
let out = log(
&mut s,
"var d = app.activeDocument, sym = d.symbols[0]; d.symbols.removeAll(); vc.log(d.symbols.length); try { sym.name; } catch (e) { vc.log(String(e.message)); }",
);
assert_eq!(out, vec![json!(0), json!("Stale Symbol")]);
}
#[test]
fn resources_refuse_objects_of_another_document() {
let (mut s, _) = doc();
log(&mut s, "var d = app.activeDocument; d.symbols.add(d.pageItems[0]);");
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
rect(&mut s, 0.0, 0.0, 10.0, 10.0);
let before = resources(&s);
for script in [
"var a = app.documents[0], b = app.documents[1]; b.symbolItems.add(a.symbols[0]);",
"var a = app.documents[0], b = app.documents[1]; a.graphicStyles[0].applyTo(b.pageItems[0]);",
"var a = app.documents[0], b = app.documents[1]; b.swatchGroups.add().addSwatch(a.swatches.getByName('Black'));",
"var a = app.documents[0], b = app.documents[1]; a.symbols.add(b.pageItems[0]);",
] {
let e = failure(&mut s, script);
assert!(e.contains("Cross-document"), "{script}: {e}");
}
assert_eq!(resources(&s), before);
}
#[test]
fn graphic_styles_apply_replaces_and_merge_adds() {
let (mut s, a) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("graphicStyle.new", &json!({"name": "Red"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let b = rect(&mut s, 100.0, 100.0, 20.0, 20.0);
s.execute("select.none", &json!({})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, g = d.graphicStyles.getByName('Red'); vc.log(g.typename); vc.log(d.graphicStyles.typename);\
g.applyTo(d.pageItems[1]);",
);
assert_eq!(out, vec![json!("GraphicStyle"), json!("GraphicStyles")]);
let id = s.active().unwrap().doc.graphic_style("Red").unwrap().id;
let n = s.active().unwrap().doc.node(b).unwrap().clone();
assert_eq!(n.extras().graphic_style, Some(id));
let fills = n.appearance.items.len();
log(&mut s, "var d = app.activeDocument; d.graphicStyles.getByName('Red').mergeTo(d.pageItems[1]);");
let n = s.active().unwrap().doc.node(b).unwrap().clone();
assert!(n.appearance.items.len() > fills, "merge adds the style's rows");
assert_eq!(n.extras().graphic_style, None);
let before = resources(&s);
for script in [
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').name = 'Plain';",
"app.activeDocument.graphicStyles.getByName('Default Graphic Style').remove();",
] {
let e = failure(&mut s, script);
assert!(e.contains("is built in"), "{script}: {e}");
}
assert_eq!(resources(&s), before);
log(&mut s, "app.activeDocument.graphicStyles.removeAll();");
let left: Vec<String> = s.active().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect();
assert_eq!(left, vec![crate::doc::DEFAULT_GRAPHIC_STYLE.to_string()]);
}
#[test]
fn brushes_apply_to_paths_only_and_once() {
let (mut s, a) = doc();
s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let first = s.execute("brush.list", &json!({})).unwrap()["brushes"][0]["name"].as_str().unwrap().to_string();
let out = log(
&mut s,
"var b = app.activeDocument.brushes; vc.log(b.typename); vc.log(b[0].typename); vc.log(b[0].name); vc.log(b.removeAll === undefined);",
);
assert_eq!(out, vec![json!("Brushes"), json!("Brush"), json!(first), json!(true)]);
let before = resources(&s);
let e = failure(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pageItems[1]);");
assert!(e.contains("PathItem only"), "{e}");
assert_eq!(resources(&s), before);
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
let st = s.active().unwrap().doc.node(a).unwrap().appearance.stroke().cloned().unwrap();
assert_eq!(st.brush.as_deref(), Some(first.as_str()));
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.brushes[0].applyTo(d.pathItems[0]);");
assert_eq!(undo_steps(&s), steps, "applying the brush a path already draws runs no command");
}
#[test]
fn brushes_refuse_guides_clipping_paths_and_compound_members() {
let (mut s, a) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("view.guides.make", &json!({})).unwrap();
let (m1, m2) = (rect(&mut s, 100.0, 20.0, 30.0, 40.0), rect(&mut s, 150.0, 20.0, 30.0, 40.0));
s.execute("select.set", &json!({"ids": [m1.0, m2.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let (c1, c2) = (rect(&mut s, 200.0, 20.0, 30.0, 40.0), rect(&mut s, 210.0, 30.0, 10.0, 10.0));
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
s.execute("object.clippingMask.make", &json!({})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let pick = |test: &str| {
format!(
"var d = app.activeDocument, p = null; for (var i = 0; i < d.pathItems.length; i++) {{ var q = d.pathItems[i]; if ({test}) p = q; }}\
d.brushes[0].applyTo(p);"
)
};
for test in ["q.guides", "q.clipping", "q.parent.typename == 'CompoundPathItem'"] {
let before = resources(&s);
let steps = undo_steps(&s);
let e = failure(&mut s, &pick(test));
assert!(e.contains("does not apply to a guide"), "{test}: {e}");
assert_eq!((resources(&s), undo_steps(&s)), (before, steps), "{test}");
}
}
#[test]
fn several_resource_edits_are_one_undo_step_and_a_failure_puts_them_back() {
let (mut s, _) = doc();
let steps = undo_steps(&s);
log(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'One'; d.spots.add().name = 'Two'; d.swatchGroups.add().name = 'Three';");
assert_eq!(undo_steps(&s), steps + 1);
let before = resources(&s);
let e = failure(&mut s, "var d = app.activeDocument; d.swatches.add().name = 'Four'; d.swatches.removeAll(); throw new Error('stop');");
assert!(e.contains("stop"), "{e}");
assert_eq!(resources(&s), before);
}
@@ -73,10 +73,11 @@ const INSIDE: &[(&str, &str)] = &[
),
(
"",
"app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \
PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PointType PolarityValues RulerUnits StrokeCap \
StrokeJoin Transformation ZOrderMethod",
"app Application Brush Brushes ColorModel CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement \
GraphicStyle GraphicStyles Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
PointType PolarityValues RulerUnits Spot SpotColorKind Spots StrokeCap StrokeJoin Swatch SwatchGroup SwatchGroups \
Swatches Symbol SymbolItem SymbolItems SymbolRegistrationPoint Symbols Transformation ZOrderMethod",
),
("Application.", "prototype"),
(
@@ -89,10 +90,10 @@ const INSIDE: &[(&str, &str)] = &[
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
groupItems groupItems= height layers layers= name pageItems parent pathItems rulerOrigin rulerOrigin= \
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames textFrames= typename \
views views= width",
"activeLayer activeLayer= artboards artboards= brushes close close= constructor convertCoordinate \
documentColorSpace gradients gradients= graphicStyles groupItems groupItems= height layers layers= name pageItems \
parent pathItems patterns patterns= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= spots \
swatchGroups swatches symbolItems symbols textFrames textFrames= typename views views= width",
),
("Layer.", "prototype"),
("Layer.prototype.", "constructor name typename"),
@@ -127,6 +128,35 @@ const INSIDE: &[(&str, &str)] = &[
"anchor anchor= constructor leftDirection leftDirection= parent pointType pointType= remove rightDirection \
rightDirection= selected selected= typename",
),
("Swatches.", "prototype"),
("Swatches.prototype.", "add constructor getByName getSelected index length parent removeAll typename"),
("Swatch.", "prototype"),
("Swatch.prototype.", "color color= constructor name name= parent remove typename"),
("Spots.", "prototype"),
("Spots.prototype.", "add constructor getByName index length parent removeAll typename"),
("Spot.", "prototype"),
("Spot.prototype.", "color color= colorType colorType= constructor getInternalColor name name= parent remove spotKind typename"),
("SwatchGroups.", "prototype"),
("SwatchGroups.prototype.", "add constructor getByName index length parent removeAll typename"),
("SwatchGroup.", "prototype"),
("SwatchGroup.prototype.", "addSpot addSwatch constructor getAllSwatches name name= parent remove removeAll typename"),
("Symbols.", "prototype"),
("Symbols.prototype.", "add constructor getByName index length parent removeAll typename"),
("Symbol.", "prototype"),
("Symbol.prototype.", "constructor duplicate name name= parent remove typename"),
("SymbolItems.", "prototype"),
("SymbolItems.prototype.", "add constructor getByName index length parent removeAll typename"),
("SymbolItem.", "prototype"),
("SymbolItem.prototype.", "constructor symbol symbol="),
("GraphicStyles.", "prototype"),
("GraphicStyles.prototype.", "constructor getByName index length parent removeAll typename"),
("GraphicStyle.", "prototype"),
("GraphicStyle.prototype.", "applyTo constructor mergeTo name name= parent remove typename"),
("Brushes.", "prototype"),
("Brushes.prototype.", "constructor getByName index length parent typename"),
("Brush.", "prototype"),
("Brush.prototype.", "applyTo constructor name parent typename"),
("ColorModel.", "PROCESS REGISTRATION SPOT"),
("CoordinateSystem.", "ARTBOARDCOORDINATESYSTEM DOCUMENTCOORDINATESYSTEM"),
("DocumentArtboardLayout.", "Column GridByCol GridByRow RLGridByCol RLGridByRow RLRow Row"),
("DocumentColorSpace.", "CMYK RGB"),
@@ -143,17 +173,23 @@ const INSIDE: &[(&str, &str)] = &[
("PointType.", "CORNER SMOOTH"),
("PolarityValues.", "NEGATIVE POSITIVE"),
("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"),
("SpotColorKind.", "SPOTCMYK SPOTLAB SPOTRGB"),
("StrokeCap.", "BUTTENDCAP PROJECTINGENDCAP ROUNDENDCAP"),
("StrokeJoin.", "BEVELENDJOIN MITERENDJOIN ROUNDENDJOIN"),
(
"SymbolRegistrationPoint.",
"SYMBOLBOTTOMLEFTPOINT SYMBOLBOTTOMMIDDLEPOINT SYMBOLBOTTOMRIGHTPOINT SYMBOLCENTERPOINT SYMBOLMIDDLELEFTPOINT \
SYMBOLMIDDLERIGHTPOINT SYMBOLTOPLEFTPOINT SYMBOLTOPMIDDLEPOINT SYMBOLTOPRIGHTPOINT",
),
("Transformation.", "BOTTOM BOTTOMLEFT BOTTOMRIGHT CENTER DOCUMENTORIGIN LEFT RIGHT TOP TOPLEFT TOPRIGHT"),
("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"),
];
/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset`,
/// the page item types other than `PathItem`, and the color classes.
/// the page item types other than `PathItem` and `SymbolItem`, and the color classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem DocumentPreset EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem PlacedItem RGBColor RasterItem RepeatItem SpotColor \
SymbolItem TextFrame cmykColor";
TextFrame cmykColor";
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
+40
View File
@@ -2724,6 +2724,46 @@ app through the global object `vc`, and writes to the Script Console and runs ot
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. `selectedPathPoints`, `PathPoint.selected`,
`transform`, `polarity`, the gradient stops and the document's default paint are not available yet.
- A `Document` also has `swatches`, `spots`, `swatchGroups`, `symbols`, `symbolItems`, `graphicStyles` and `brushes`
(https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/,
https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroups/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/,
https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItems/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyles/
and https://ai-scripting.docsforadobe.dev/jsobjref/Brushes/). Each has `length`, `parent`, `[i]`, `index(key)` and
`getByName(name)`; all but `brushes` have `removeAll()`. `swatches.add()` and `spots.add()` run `swatch.new`,
`swatchGroups.add()` runs `swatch.newGroup`, `symbols.add(sourceArt, registrationPoint?)` runs `symbol.new` with
`keepArt: true` (the default point is `SymbolRegistrationPoint.SYMBOLCENTERPOINT`), and `symbolItems.add(symbol)`
runs `symbol.place`. `swatches.getSelected()` gives `[]`. A `Swatch` (https://ai-scripting.docsforadobe.dev/jsobjref/Swatch/)
has `name` and `color` (`swatch.edit`) and `remove()` (`swatch.delete`); a spot swatch's `color` reads as a
`SpotColor` with its `spot` and a `tint` of 100, and a tint of a spot as that `spot` at its `tint`. A `Spot` (https://ai-scripting.docsforadobe.dev/jsobjref/Spot/) has
`name`, `color`, `colorType`, `spotKind`, `getInternalColor()` and `remove()`. A `SwatchGroup`
(https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/) has `name` (`swatch.renameGroup`), `addSwatch(swatch)`
and `addSpot(spot)` (`swatch.move`), `getAllSwatches()`, `remove()` and `removeAll()`. A `Symbol`
(https://ai-scripting.docsforadobe.dev/jsobjref/Symbol/) has `name` (`symbol.options`), `duplicate()`
(`symbol.duplicate`) and `remove()` (`symbol.delete`), and a `SymbolItem`
(https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/) adds `symbol` to the page item members, which
`symbol.replace` changes. A `GraphicStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/) has `name`
(`graphicStyle.rename`), `applyTo(item)` and `mergeTo(item)` (`graphicStyle.apply`, with `add: true` for `mergeTo`)
and `remove()` (`graphicStyle.delete`). A `Brush` (https://ai-scripting.docsforadobe.dev/jsobjref/Brush/) has a
read-only `name` and `applyTo(item)` (`brush.apply`). The enumerations `SymbolRegistrationPoint`, `ColorModel` and
`SpotColorKind` hold strings such as `"ColorModel.SPOT"`.
VectorCraft's own rules: `swatches` lists None, Registration, the other ungrouped swatches and then each color
group's, and `swatchGroups` lists the color groups. `swatches.add()` saves the current fill (a color, gradient or
pattern) or black when the fill is None, and `spots.add()` the current fill, converted to the document's color
space unless it is Lab, or black when it is not a solid color. None and Registration cannot change or be removed,
and `removeAll()` keeps them; the Default Graphic Style cannot be renamed or removed, and
`graphicStyles.removeAll()` keeps it. A color group takes solid
colors only; `SwatchGroup.remove()` deletes the group with its swatches, and its `removeAll()` deletes the swatches
and keeps the group. A spot's color is in the document's color space or Lab, its `colorType` takes only
`ColorModel.SPOT`, a gray spot's `spotKind` is `SpotColorKind.SPOTCMYK`, and `getInternalColor()` gives the
components on the color classes' scales. `symbols.add` leaves the source art as it is, and removing a symbol turns
its instances into plain art. `applyTo` and `mergeTo` take one page item of the same document that can be edited,
and `Brush.applyTo` a path that is not a guide, a clipping path or a path in a compound path; applying the brush a
path already draws runs no command. A name is 1 to 1,024 bytes, not blank, with no control characters, and a name a
swatch, spot or color group already has throws for any of the three. Renaming a resource through these objects keeps the object; after it is
removed, or renamed or deleted with `vc.run`, every member throws `Stale Swatch` (`Stale Spot`, `Stale SwatchGroup`,
`Stale Symbol`, `Stale GraphicStyle`, `Stale Brush`). A run holds at most 100,000 of these objects. An object of
another document throws `Cross-document placement is not available`. `Document.gradients`, `Document.patterns` and
assigning a `SpotColor` to art are not available yet.
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
+1
View File
@@ -1026,6 +1026,7 @@ 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: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: each document's swatches, spots, color groups, symbols and their instances, graphic styles and brushes are live collections; scripts add, rename, recolor, group, duplicate, apply and remove them through the Swatches, Symbols, Graphic Styles and Brushes commands, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Swatches/, https://ai-scripting.docsforadobe.dev/jsobjref/Spots/, https://ai-scripting.docsforadobe.dev/jsobjref/SwatchGroup/, https://ai-scripting.docsforadobe.dev/jsobjref/Symbols/, https://ai-scripting.docsforadobe.dev/jsobjref/SymbolItem/, https://ai-scripting.docsforadobe.dev/jsobjref/GraphicStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/Brush/ describe them (`docs/mcp.md`). Gradients and patterns are not there yet. `crates/engine/src/tests/script_dom_resources.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.