mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 14:51:20 -05:00
Merge pull request #9041 from dotCooCoo/feat/scripts-api-d2-paths-colors
Scripts: documents give scripts their paths, path points and colors
This commit is contained in:
@@ -69,9 +69,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, 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, item_rect, 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, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method,
|
||||
named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -248,8 +248,9 @@ 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 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.
|
||||
/// locked or is on a locked artboard ([`refuse_path_edit`]), 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> {
|
||||
forget_waiting_starts(h);
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
@@ -415,20 +416,44 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match super::position(*n) {
|
||||
Some(i) => item_at(h, doc, i),
|
||||
None => match items_named(h, doc, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path at position `i` of `pathItems`, or `undefined` past the end.
|
||||
fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
with_doc(h, doc, |_, st| Ok(path_items(h, st)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
}
|
||||
|
||||
/// The first path of `pathItems` named `name`, or `Not found`.
|
||||
fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -436,10 +461,13 @@ fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(_) => match items_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
Some(d) => Ok(d),
|
||||
}
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
@@ -462,7 +490,7 @@ fn items_remove_all(h: &super::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<_>>()})))?;
|
||||
|
||||
@@ -98,6 +98,64 @@ fn path_items_remove_all_refuses_locked_paths_and_changes_nothing() {
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
/// `pathItems` read with a name gives what `getByName` gives, and throws as it does for no match,
|
||||
/// as `pageItems` does.
|
||||
#[test]
|
||||
fn path_items_read_with_a_name_give_the_named_path() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "n"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems, m = [];\
|
||||
vc.log([p['n'] === p.getByName('n'), p['n'].name, 'n' in p, 'nosuch' in p, p['length'] === p.length]);\
|
||||
try { p['nosuch']; } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]);
|
||||
}
|
||||
|
||||
/// `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`.
|
||||
#[test]
|
||||
fn path_items_read_with_a_number_name_that_is_not_an_index_give_the_named_path() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("object.setProps", &json!({"ids": [a.0], "name": "-1"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems, m = [];\
|
||||
vc.log([p['-1'] === p.getByName('-1'), '-1' in p, p[-1] === p.getByName('-1'), p['1.5'] === undefined, '1.5' in p]);\
|
||||
try { p.index(-1); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, true, true, true, false]), json!(["Not found"])]);
|
||||
}
|
||||
|
||||
/// Paths on a locked artboard stay, a path in a group included: `removeAll()` throws and deletes
|
||||
/// nothing, as `pageItems.removeAll()` and `remove()` do.
|
||||
#[test]
|
||||
fn path_items_remove_all_refuses_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("object.group", &json!({"ids": [b.0]})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let lock = |s: &mut Session, locked: bool| {
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = locked;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
lock(&mut s, true);
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()) && e.contains(&b.0.to_string()), "{e}");
|
||||
assert_eq!(art(&s), before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
lock(&mut s, false);
|
||||
log(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.pathItems.length);"), vec![json!(0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_creators_use_documented_defaults_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
|
||||
+9
-4
@@ -3370,8 +3370,11 @@ through `$`:
|
||||
the Script Console as a line that starts with `Document.print: `. `vc.run` still cannot run `file.print` or
|
||||
`print.*`.
|
||||
- `Document.pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/) lists the document's paths in the
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `index(key)`,
|
||||
`getByName(name)`, `removeAll()`, `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
order of `pageItems`, paths inside groups and compound paths included, with `length`, `[i]`, `[name]` (read as
|
||||
`pageItems["name"]` is read), `index(key)`,
|
||||
`getByName(name)`, `removeAll()` (it deletes nothing and throws `cannot delete hidden or locked paths` when any path is
|
||||
hidden or locked or is inside a hidden or locked object, and otherwise `cannot delete objects on a locked artboard`
|
||||
when any path is on a locked artboard; each message is followed by a colon and the ids of up to 20 of those paths), `add()` (a path with no points, from `path.create`, painted as new art; when new
|
||||
art has no fill and no stroke, the path has neither), and the shape creators
|
||||
`rectangle(top, left, width, height, reversed?)`, `roundedRectangle(top, left, width, height, horizontalRadius = 15,
|
||||
verticalRadius = 20, reversed?)`, `ellipse(top = 100, left = 100, width = 50, height = 100, reversed?, inscribed?)`,
|
||||
@@ -3447,8 +3450,10 @@ through `$`:
|
||||
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with
|
||||
`inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
|
||||
that is hidden or locked, 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()` when any path is on a locked artboard throws
|
||||
`cannot delete objects on a locked artboard` and deletes nothing. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
|
||||
`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
|
||||
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.
|
||||
|
||||
@@ -1114,7 +1114,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `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`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops 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 on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops 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: 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`.
|
||||
|
||||
Reference in New Issue
Block a user