Merge main into feat/scripts-layer-text-frames

This commit is contained in:
dotCooCoo committed 2026-12-02 17:49:12 -08:00
commit e4e6dd517d
25 files changed
+1292 -358

No files matched your search

+17 -1
View File
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -1312,6 +1312,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator<Item = NodeId>) -> BTreeSet<NodeId> {
ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect()
}
pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet<NodeId>) {
for id in ids {
if let Some(n) = d.node_mut(id)
&& n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide()))
{
n.set_clips(false);
}
}
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?;
@@ -1348,6 +1362,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Clear", |d, sel| {
let clipped = clipped_ancestors(d, ids.iter().copied());
let parents: Vec<_> = if keep_empty {
Vec::new()
} else {
@@ -1363,6 +1378,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let gone = sel.guides.clone();
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
release_empty_clips(d, clipped);
if is_explicit {
sel.remove_all(ids.iter().copied());
sel.prune(d);
+6 -1
View File
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
has_doc,
move_node
),
@@ -1006,6 +1006,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(n.kind, NodeKind::Path { guide: false, .. }) {
return Err(bad(C, "a compound path holds only paths"));
}
// A clip group's or clipping layer's clipping path stays where it is: without it, the
// next object up would become the clipping path.
if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) {
return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first"));
}
if !d.is_editable(c.id) {
return Err(bad(C, "the compound path is hidden or locked"));
}
+4 -3
View File
@@ -110,17 +110,18 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
/// selection stays as it is.
pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.newGroup";
// Only an omitted key takes its default; `null` is refused like any other bad value.
let compound = match p.get("compound") {
None | Some(Value::Null) => false,
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?,
};
let st = s.doc()?;
let parent = match p.get("parent") {
None | Some(Value::Null) => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?),
};
let index = match p.get("index") {
None | Some(Value::Null) => usize::MAX,
None => usize::MAX,
Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?,
};
let d = &st.doc;
+1 -1
View File
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Group",
[],
None,
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; the selection stays as it is",
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
has_doc,
new_group
),
+2
View File
@@ -1921,6 +1921,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
.copied()
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
.collect();
let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied());
// The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`.
let compounds: BTreeSet<NodeId> = if keep_empty {
BTreeSet::new()
@@ -2002,6 +2003,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
d.remove(p)?;
}
}
super::edit::release_empty_clips(d, clipped);
selection.set(survivors);
for (id, next) in following {
if !next.is_empty() {
+11 -1
View File
@@ -253,7 +253,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
// A document whose active artboard the script chose uses that choice, not the one the run
// started with.
let chosen = h.session.borrow().active().and_then(|st| {
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
Some((st.uid, super::dom::active_artboard(st)))
});
let active = match &chosen {
Some(chosen) => std::slice::from_ref(chosen),
None => h.active_artboards.as_slice(),
};
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
+44 -21
View File
@@ -18,7 +18,8 @@
//!
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound
//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! gives, and a script may name the application's members without `app.`, as
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
@@ -37,8 +38,7 @@
//! - After `documents[0]`, documents are listed from the one active most recently to the one
//! active longest ago. A change a script makes to a document in the back does not move it.
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the
//! order of a layer's, a group's and a compound path's lists. An index out of range gives
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
//! - Script coordinates are points with Y up from the bottom of the first artboard
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
@@ -184,6 +184,14 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
#[cfg(test)]
thread_local! {
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
/// How many lists of art the art collections have built on this thread.
pub(crate) static ART_SCANS: Cell<u64> = const { Cell::new(0) };
}
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
@@ -224,10 +232,18 @@ pub(super) struct State {
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
/// used first, each kept while its document is unchanged.
art: RefCell<Vec<layers::ArtList>>,
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
/// first, each kept while its document is unchanged.
layers: RefCell<Vec<layers::LayerList>>,
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
pub(super) active_artboards: RefCell<Vec<u64>>,
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
/// Each open document's uid and the index of its active artboard when the run started.
pub(super) boards_at_start: Vec<(u64, usize)>,
/// Each document made during the run whose active artboard `setActiveArtboardIndex` chose,
/// with the index it chose the first time.
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
/// The print option objects ([`print`]).
@@ -245,9 +261,9 @@ pub(super) struct State {
}
impl State {
/// The state of a run whose heap is `heap_bytes` and that starts with the documents `docs` open.
pub(super) fn new(heap_bytes: usize, docs: &[DocState]) -> Self {
Self { preset_limit: heap_bytes as u64, boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() }
/// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`.
pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self {
Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() }
}
/// Whether a call's own savepoint is open: its commands take none of their own.
@@ -2200,7 +2216,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
}
fn items_length(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_length(h, a);
}
let doc = items_doc(h, a)?;
@@ -2209,7 +2225,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
}
fn items_typename(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_typename(h, a);
}
items_doc(h, a)?;
@@ -2217,16 +2233,16 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
}
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
let Data::String(name) = layers::scoped_typename(h, a)? else { return Ok(text("[PageItems]")) };
return Ok(text(format!("[{name}]")));
if layers::is_scoped(a, "PageItems") {
layers::scoped_typename(h, a)?;
return Ok(text("[PageItems]"));
}
items_doc(h, a)?;
Ok(text("[PageItems]"))
}
fn items_parent(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_parent(h, a);
}
let doc = items_doc(h, a)?;
@@ -2248,7 +2264,7 @@ fn position(n: f64) -> Option<usize> {
/// 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 object has it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_at(h, a);
}
let doc = items_doc(h, a)?;
@@ -2274,7 +2290,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
}
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_by_name(h, a);
}
let doc = items_doc(h, a)?;
@@ -2293,10 +2309,11 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
}
fn items_index(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_index(h, a);
}
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
// A number is a position only; a scoped list answers its own positions.
Data::Number(_) if layers::is_scoped(a) => layers::scoped_index(h, a),
Data::Number(n) => {
let doc = items_doc(h, a)?;
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
@@ -2312,7 +2329,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
/// and so does an object on a locked artboard.
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
@@ -2492,8 +2509,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four
/// decimals.
fn reported_opacity(opacity: f32) -> f64 {
(f64::from(opacity) * 100.0 * 1e4).round() / 1e4
}
fn item_opacity(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
}
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
@@ -2510,7 +2533,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0);
let keeps_other =
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
(now, keeps_other)
@@ -3562,8 +3585,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.push(class("PageItem", None, page_item, None));
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
let mut members = variables::item_members(l, c);
members.extend(layers::members(c, l));
let mut members = layers::members(c, l);
members.extend(variables::item_members(l, c));
if *c == "PathItem" {
members.extend(paths::path_item_members(l));
}
+1 -1
View File
@@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[
("PatternColor", &[]),
];
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
let mut items = vec![("typename".to_string(), text(class))];
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
Data::Object(items)
+46 -9
View File
@@ -27,8 +27,10 @@
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
//! is refused.
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
use std::cell::RefCell;
@@ -291,7 +293,8 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
// ---- files ----
/// Whether the script may read `path` now by its own read scope and the read roots
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link
/// to, that a command may also read.
fn may_read(h: &Host, path: &str) -> bool {
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
@@ -496,16 +499,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
}
let old = im.xf;
// The coordinate frame only changes the signs of the linear part, so any change to it
// counts; the offsets compare in points, which absorbs the rounding of the frame.
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
if same {
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
// A coefficient the script left as the getter reports keeps the image's own value, so the
// conversion back does not shift an untouched axis.
let olds = old.as_coeffs();
let [a0, b0, c0, d0, e0, f0] = olds;
let reported = match h.dom.coords.get() {
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
};
let mut wanted = target.as_coeffs();
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
if r == v {
*w = o;
}
}
if wanted == olds {
return Ok(None);
}
if !area_of(old) {
return Err(HostError::Error("the image has no area to transform".into()));
}
Ok(Some((target * old.inverse()).as_coeffs()))
let target = Affine::new(wanted);
let [ta, tb, tc, td, te, tf] = wanted;
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
// A move alone: the offset difference, without the error an inverse adds.
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
}
// A nearly singular image loses precision through the inverse; refuse a change that would
// not land where the script asked rather than move the image somewhere else.
let delta = target * old.inverse();
let landed = delta * old;
if landed.as_coeffs() == olds {
return Ok(None);
}
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
});
if !close || !area_of(landed) {
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
}
Ok(Some(delta.as_coeffs()))
})?;
if let Some(d) = delta {
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
@@ -653,7 +690,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
]);
let mut placed = named(vec![
("file", property(l, placed_file, placed_set_file), typed("File")),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])),
("embed", method(l, placed_embed), returns("undefined", &[])),
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
("boundingBox", get(l, placed_box), typed("Array")),
+277 -161
View File
@@ -20,7 +20,7 @@
//! - `locked` true means the layer is locked.
//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or
//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it.
//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255.
//! - A layer's `color` is an `RGBColor` object with values from 0 to 255.
//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it
//! gives it its paint, as Make Compound Path takes the paint of a path it joins.
//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a
@@ -42,8 +42,8 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
use super::{
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref,
later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, typename, whole,
with_doc,
later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity,
returns, text, typed, typename, whole, with_doc,
};
use crate::script::{Host, Link};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -66,6 +66,8 @@ enum Kind {
Group,
/// Compound paths (`CompoundPathItem`).
Compound,
/// Paths (`PathItem`).
Path,
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
Text,
}
@@ -76,6 +78,7 @@ impl Kind {
Kind::Any => "PageItems",
Kind::Group => "GroupItems",
Kind::Compound => "CompoundPathItems",
Kind::Path => "PathItems",
Kind::Text => "TextFrames",
}
}
@@ -85,6 +88,7 @@ impl Kind {
Kind::Any => typename(n).is_some(),
Kind::Group => typename(n) == Some("GroupItem"),
Kind::Compound => typename(n) == Some("CompoundPathItem"),
Kind::Path => typename(n) == Some("PathItem"),
Kind::Text => typename(n) == Some("TextFrame"),
}
}
@@ -102,16 +106,17 @@ fn result_id(v: &Value, key: &str) -> Option<u64> {
// ---- Layer ----
/// The layer `d` names, which must still be a layer of its document. A layer read before its
/// document was reverted throws `Stale page item`, as page items do.
/// The layer `d` names, which must still be a layer of its document.
pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> {
let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) };
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(type_error("Layer")) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
if Some(with_doc(h, doc, |_, st| st.reverts)) != whole(*reverts) {
return Err(HostError::Error(STALE_ITEM.into()));
if handle.len() != 5 {
return Err(type_error("Layer"));
}
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
// A layer read before File › Revert is stale like the page items read with it.
let (doc, id) = node_of(h, &handle).ok_or_else(|| {
let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some());
HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into())
})?;
let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer));
if !ok {
return Err(HostError::Error(STALE_LAYER.into()));
@@ -123,19 +128,16 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> {
layer_of(h, arg(a, 0))
}
/// The handle of layer `id` of the document `uid`, or of a collection of the layer, group or
/// compound path `id`: the run, the document, the id and the document's revert count, as
/// [`super`]'s page items have.
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
let [high, low] = id_parts(id);
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
[float(h.run), float(uid), high, low, float(reverts)]
}
fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
host_ref("Layer", &layer_handle(h, uid, id))
}
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
let [high, low] = id_parts(id);
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
}
/// Reads the layer `this` names with `f`.
fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer {
let (doc, id) = this_layer(h, a)?;
@@ -239,7 +241,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer {
}
fn layer_opacity(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
}
fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
@@ -247,17 +249,15 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
// The number the getter reports (rounded to 4 decimals), or one that stores as the opacity the
// layer has, leaves the layer as it is.
let same = |n: &crate::doc::Node| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v || n.opacity == (v / 100.0) as f32;
set_layer(h, a, "object.setProps", same, json!({"opacity": v}))
// The number the getter reports, or one that stores as the opacity the layer has, leaves the
// layer as it is.
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v}))
}
fn layer_color(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| {
let [r, g, b] = layer_flags(n).3.rgb();
let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v)));
Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)]))
Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))]))
})
}
@@ -299,9 +299,13 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let list = layer_list(&st.doc, st.doc.parent_of(id));
list.iter().position(|l| *l == id).map(|i| list.len() - i)
});
let parent = st.doc.parent_of(id);
let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len));
h.charge_call(count as u64)?;
let list = layer_list(&st.doc, parent);
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into()))
}
@@ -310,40 +314,64 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
}
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
/// child visited, including skipped children.
fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
let mut count = 0;
for child in n.children().into_iter().flatten() {
count += 1;
if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() {
continue;
}
if child.is_layer() {
count += collect_editable_art(child, out);
} else {
out.push(child.id);
}
}
count
}
/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its
/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays,
/// and no command runs when there is nothing to deselect or add.
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
let (doc, id) = this_layer(h, a)?;
let (ids, total) = with_doc(h, doc, |_, st| {
let (ids, over) = with_doc(h, doc, |_, st| {
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
let selected = &st.selection.objects;
h.charge_call(selected.len() as u64)?;
if !on {
return (selected.iter().copied().filter(inside).collect::<Vec<_>>(), 0);
return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::<Vec<_>>(), false));
}
let locks = st.doc.locked_artboards();
let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default();
let mut art = Vec::new();
let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art));
// The walk is charged by every node it looks at, hidden and locked ones included, whether
// or not anything is added.
h.charge_call(count)?;
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
let mut ids = Vec::new();
for o in art {
if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
have.insert(o);
ids.push(o);
if selected.len() + ids.len() > MAX_LISTED {
break;
}
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
continue;
}
// Only art that would be added counts toward the limit.
if selected.len() + ids.len() >= MAX_LISTED {
return Ok((ids, true));
}
have.insert(o);
ids.push(o);
}
let total = selected.len() + ids.len();
(ids, total)
});
Ok((ids, false))
})?;
if over {
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
}
if ids.is_empty() {
return Ok(Data::Undefined);
}
if total > MAX_LISTED {
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
}
let command_id = if on { "select.add" } else { "select.toggle" };
on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
Ok(Data::Undefined)
@@ -495,9 +523,44 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
None => Some(&d.layers),
Some(p) => d.children(Some(p)),
};
#[cfg(test)]
super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64)));
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
}
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
/// level) and the layers it listed then.
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
/// is charged by the objects it looks at.
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
{
let mut lists = h.dom.layers.borrow_mut();
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
if let Some(at) = at {
let list = lists.remove(at);
let ids = list.3.clone();
lists.push(list);
return Ok(ids);
}
}
let looked_at = match parent {
None => st.doc.layers.len(),
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
};
h.charge_call(looked_at as u64)?;
let ids = Rc::new(layer_list(&st.doc, parent));
let mut lists = h.dom.layers.borrow_mut();
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
if lists.len() >= ART_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
Ok(ids)
}
fn layers_of(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
@@ -505,8 +568,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer {
fn layers_length(h: &Host, a: &[Data]) -> Answer {
let (doc, parent) = layers_scope(h, arg(a, 0))?;
let n = with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))?;
Ok(num(float(n as u64)))
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
}
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
@@ -519,18 +581,30 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Layers"))
}
/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when
/// nothing has the name, as the document's `pageItems` does.
fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer {
match by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
}
}
fn layers_at(h: &Host, a: &[Data]) -> Answer {
let (doc, parent) = layers_scope(h, arg(a, 0))?;
if let Data::String(_) = arg(a, 1) {
return read_by_name(h, a, layers_by_name);
}
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) };
with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
}
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
let (doc, parent) = layers_scope(h, arg(a, 0))?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = layer_ids(h, st, parent)?;
let ids = layers_listed(h, st, parent)?;
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()));
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -573,7 +647,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
if parent.is_none() {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent));
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
if ids.len() > crate::cmd::layer::MAX_ROWS {
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
@@ -592,12 +666,12 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
// A container's collection goes stale with the container when its document is reverted.
[run, uid, high, low, reverts] => {
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
// A collection read before File › Revert is stale like its container.
let holds = with_doc(h, doc, |_, st| {
Some(st.reverts) == whole(*reverts)
whole(*reverts) == Some(st.reverts)
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
});
if !holds {
@@ -609,8 +683,8 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
}
}
/// A document's uid, the document as it was, the [`Kind`] (or [`LAYER_LIST`]) and the container of
/// an art or layer collection, and the ids it listed then.
/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection,
/// and the ids it listed then.
pub(super) type ArtList = (u64, Arc<Document>, u8, Option<NodeId>, Rc<Vec<NodeId>>);
/// How many lists of art [`super::State`] keeps at once.
@@ -621,44 +695,9 @@ pub(super) const ART_LISTS: usize = 4;
/// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds
/// each list once. Each new list is charged by the objects it looks at.
fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
kept_list(h, st, kind as u8, container, || {
Ok(match container {
None => {
let all = page_items(h, st)?;
h.charge_call(all.len() as u64)?;
all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect()
}
Some(c) => {
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
h.charge_call(children.len() as u64)?;
children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect()
}
})
})
}
/// The tag of a list of layers among the kept lists of art.
const LAYER_LIST: u8 = u8::MAX;
/// The layers of `parent` (`None`: the top level), top first, kept as [`art_list`] keeps its
/// lists. Each new list is charged by the rows it looks at.
fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
kept_list(h, st, LAYER_LIST, parent, || {
let rows = match parent {
None => Some(&st.doc.layers),
Some(p) => st.doc.children(Some(p)),
};
h.charge_call(rows.map_or(0, Vec::len) as u64)?;
Ok(layer_list(&st.doc, parent))
})
}
/// The list kept for `tag` and `container` while the document is unchanged, else the one `build`
/// makes, which is kept in place of the least recently used one.
fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option<NodeId>, build: impl FnOnce() -> Result<Vec<NodeId>>) -> Result<Rc<Vec<NodeId>>> {
{
let mut lists = h.dom.art.borrow_mut();
let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == tag && *c == container);
let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container);
if let Some(at) = at {
let list = lists.remove(at);
let ids = list.4.clone();
@@ -666,25 +705,47 @@ fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option<NodeId>, build:
return Ok(ids);
}
}
let ids = Rc::new(build()?);
#[cfg(test)]
super::ART_SCANS.with(|c| c.set(c.get() + 1));
let ids: Vec<NodeId> = match container {
None => {
let all = page_items(h, st)?;
h.charge_call(all.len() as u64)?;
all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect()
}
Some(c) => {
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
h.charge_call(children.len() as u64)?;
children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect()
}
};
let ids = Rc::new(ids);
let mut lists = h.dom.art.borrow_mut();
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
if lists.len() >= ART_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), tag, container, ids.clone()));
lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone()));
Ok(ids)
}
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
/// names the container.
pub(super) fn is_scoped(a: &[Data]) -> bool {
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
/// Whether a `PageItems` or `PathItems` object's handle names its container.
pub(super) fn is_scoped(a: &[Data], class: &str) -> bool {
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5)
}
fn scoped_kind(a: &[Data]) -> Kind {
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any }
}
/// How many times File › Revert has reloaded the document with uid `uid`.
fn reverts_of(h: &Host, uid: u64) -> u64 {
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
}
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
match container {
Some(c) => host_ref(kind.class(), &layer_handle(h, uid, c)),
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
}
}
@@ -700,40 +761,35 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer {
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
}
/// `collection[i]`, and `collection["name"]` as `getByName` reads it, as the document's
/// `pageItems` reads them: a name nothing has throws `Not found` (gives `undefined` for `in`), and
/// the text of a number that is not an array index is looked up as a name, giving `undefined`
/// when nothing has it.
fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
match arg(a, 1) {
Data::String(name) => match art_named(h, doc, c, kind, name) {
Err(HostError::Error(e)) if e == NOT_FOUND && matches!(arg(a, 2), Data::Bool(true)) => Ok(Data::Undefined),
if let Data::String(_) = arg(a, 1) {
return match art_by_name(h, a, kind) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
},
Data::Number(n) => match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
None => match art_named(h, doc, c, kind, &vectorcraft_js::number_to_string(*n)) {
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
r => r,
},
},
_ => Ok(Data::Undefined),
};
}
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
// The text of a number that is not an array index is looked up as a name.
None => with_doc(h, doc, |_, st| {
let ids = art_list(h, st, kind, c)?;
h.charge_call(ids.len() as u64)?;
let name = vectorcraft_js::number_to_string(*n);
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
}),
}
}
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
art_named(h, doc, c, kind, name)
}
/// The first object named `name` in the art collection of `kind` in `c`.
fn art_named(h: &Host, doc: Doc, c: Option<NodeId>, kind: Kind, name: &str) -> Answer {
with_doc(h, doc, |_, st| {
let ids = art_list(h, st, kind, c)?;
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));
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
})
}
@@ -760,7 +816,7 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
/// `pageItems.removeAll()` is stopped.
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
let all = art_list(h, st, kind, c)?;
let d = &st.doc;
let listed: std::collections::HashSet<NodeId> = all.iter().copied().collect();
@@ -770,7 +826,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = d.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let masks: Vec<u64> = ids
.iter()
.filter(|i| {
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
let kids = p.children().map_or(&[][..], Vec::as_slice);
p.clips()
&& kids.first().is_some_and(|f| f.id == **i)
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
})
})
.map(|i| i.0)
.take(20)
.collect();
Ok::<_, HostError>((ids, refused, on_locked, masks))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -780,42 +851,41 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !masks.is_empty() {
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
if !ids.is_empty() {
// The container stays, empty, as a compound path whose last path `remove()` takes out does.
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
// A deletion that takes a clipping path releases its clip group's or clipping layer's mask,
// so neither the object above it nor one added later is made the clipping path. A deletion
// that leaves the clipping path keeps the mask.
let released = with_doc(h, doc, |_, st| super::masks_cleared_by(&st.doc, &ids));
on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, &params))?;
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
}
Ok(Data::Undefined)
}
/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their
/// handle names one ([`is_scoped`]).
/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]).
pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer {
art_length(h, a, Kind::Any)
art_length(h, a, scoped_kind(a))
}
pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer {
art_parent(h, a, Kind::Any)
art_parent(h, a, scoped_kind(a))
}
pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer {
art_at(h, a, Kind::Any)
}
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
art_index(h, a, Kind::Any)
art_at(h, a, scoped_kind(a))
}
pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
art_by_name(h, a, Kind::Any)
art_by_name(h, a, scoped_kind(a))
}
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
art_index(h, a, scoped_kind(a))
}
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
art_remove_all(h, a, Kind::Any)
art_remove_all(h, a, scoped_kind(a))
}
fn groups_length(h: &Host, a: &[Data]) -> Answer {
@@ -861,7 +931,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer {
}
pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer {
art_typename(h, a, Kind::Any)
art_typename(h, a, scoped_kind(a))
}
fn groups_typename(h: &Host, a: &[Data]) -> Answer {
art_typename(h, a, Kind::Group)
@@ -924,6 +994,10 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Any)
}
fn held_paths(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Path)
}
fn held_groups(h: &Host, a: &[Data]) -> Answer {
held(h, a, Kind::Group)
}
@@ -977,11 +1051,10 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
if now == on {
return Ok(Data::Undefined);
}
super::refuse_protected_edit(h, item)?;
if !ok {
return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0)));
}
// A group on a locked artboard keeps its mask, as its other properties do.
super::refuse_protected_edit(h, item)?;
on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?;
Ok(Data::Undefined)
}
@@ -991,11 +1064,6 @@ pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
named(vec![("layer", get(l, item_layer), typed("Layer"))])
}
/// A collection's type for `reflect`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
/// The members a page item class adds to `PageItem`'s.
pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
match class {
@@ -1010,11 +1078,16 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
m
}
"CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items), listed("PageItems"))]),
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
_ => Vec::new(),
}
}
/// What `reflect` tells of a member whose value is a collection of class `data_type`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
// ---- Document ----
fn doc_layers(h: &Host, a: &[Data]) -> Answer {
@@ -1074,15 +1147,14 @@ fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
// An artboard read before its document was reverted is stale, as its layers are.
let index = with_doc(h, doc, |_, st| (Some(st.reverts) == whole(*reverts)).then(|| board_index(st, id)).flatten())
// An artboard read before File › Revert is stale, as the page items read with it are.
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
Ok((Board { doc }, index))
}
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)])
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
}
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
@@ -1188,6 +1260,10 @@ fn board_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboard"))
}
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Artboard", board_name(h, a))
}
/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner
/// with Y down.
fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer {
@@ -1274,6 +1350,24 @@ fn boards_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboards"))
}
/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`.
fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
layers_scope(h, arg(a, 0))?;
Ok(text("[Layers]"))
}
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Group.class())?;
Ok(text("[GroupItems]"))
}
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Compound.class())?;
Ok(text("[CompoundPathItems]"))
}
fn boards_to_string(h: &Host, a: &[Data]) -> Answer {
boards_doc(h, a)?;
Ok(text("[Artboards]"))
}
/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`).
fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
let n = number(d, what)?;
@@ -1285,6 +1379,9 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
fn boards_at(h: &Host, a: &[Data]) -> Answer {
let doc = boards_doc(h, a)?;
if let Data::String(_) = arg(a, 1) {
return read_by_name(h, a, boards_by_name);
}
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) };
Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id))))
@@ -1351,7 +1448,7 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer {
add_board(h, a, None)
}
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → `undefined`.
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing.
fn boards_insert(h: &Host, a: &[Data]) -> Answer {
if matches!(arg(a, 2), Data::Undefined) {
return Err(HostError::Type("insert needs an index".into()));
@@ -1374,22 +1471,36 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer {
}
/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the
/// document changes, and no command runs.
/// document changes, and no command runs. The artboard is kept by its id even when it is already
/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later
/// in the run moves it to the next index instead of taking its place.
fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
let doc = boards_doc(h, a)?;
let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st)));
let i = board_index_arg(arg(a, 1), len, "index")?;
// The artboard's id is stored on every call, so an artboard inserted before it later does not
// change which artboard is active.
{
let mut s = h.session.borrow_mut();
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
}
// A document the run opened is reported whenever an artboard is chosen in it, since the report
// has no start index for it to compare with.
let new_doc = !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid);
if i != now || new_doc {
{
let mut chosen = h.dom.chosen_artboards.borrow_mut();
let reverts = reverts_of(h, doc.uid);
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
*generation = reverts;
} else {
chosen.push((doc.uid, reverts));
}
}
// A document made during the run has no index from the start of the run, so the first choice
// records one; an artboard inserted before it later still puts it in the report.
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
if !made.iter().any(|(uid, _)| *uid == doc.uid) {
made.push((doc.uid, i));
}
}
if i != now {
let mut moved = h.dom.active_artboards.borrow_mut();
if !moved.contains(&doc.uid) {
moved.push(doc.uid);
@@ -1432,8 +1543,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("printable", property(l, layer_printable, layer_set_printable), typed("boolean")),
("preview", property(l, layer_preview, layer_set_preview), typed("boolean")),
("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")),
("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
("color", property(l, layer_color, layer_set_color), typed("*")),
("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")),
("color", property(l, layer_color, layer_set_color), typed("RGBColor")),
("parent", get(l, layer_parent), typed("*")),
("layers", get(l, layers_of), listed("Layers")),
("pageItems", get(l, held_page_items), listed("PageItems")),
@@ -1464,6 +1575,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])),
("add", method(l, layers_add), returns("Layer", &[])),
("removeAll", method(l, layers_remove_all), returns("undefined", &[])),
("toString", method(l, layers_to_string), returns("string", &[])),
]),
Some(super::function(l, layers_at)),
),
@@ -1479,6 +1591,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])),
("add", method(l, groups_add), returns("GroupItem", &[])),
("removeAll", method(l, groups_remove_all), returns("undefined", &[])),
("toString", method(l, groups_to_string), returns("string", &[])),
]);
m.push(later(l, "GroupItems", "createFromFile"));
m
@@ -1496,6 +1609,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])),
("add", method(l, compounds_add), returns("CompoundPathItem", &[])),
("removeAll", method(l, compounds_remove_all), returns("undefined", &[])),
("toString", method(l, compounds_to_string), returns("string", &[])),
]),
Some(super::function(l, compounds_at)),
),
@@ -1513,6 +1627,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")),
("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")),
("remove", method(l, board_remove), returns("undefined", &[])),
("toString", method(l, board_to_string), returns("string", &[])),
]),
None,
),
@@ -1530,6 +1645,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])),
("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])),
("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])),
("toString", method(l, boards_to_string), returns("string", &[])),
]),
Some(super::function(l, boards_at)),
),
+26 -1
View File
@@ -397,21 +397,33 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
}
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
if super::layers::is_scoped(a, "PathItems") {
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
}
doc_of(h, arg(a, 0), "PathItems")
}
/// `typename` of the paths of a document that is still open.
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_typename(h, a);
}
items_doc(h, a)?;
Ok(Data::String("PathItems".into()))
}
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_length(h, a);
}
let doc = items_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
}
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_parent(h, a);
}
let doc = items_doc(h, a)?;
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
}
@@ -420,6 +432,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
/// 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 {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_at(h, a);
}
let doc = items_doc(h, a)?;
match arg(a, 1) {
Data::String(_) => match items_by_name(h, a) {
@@ -443,6 +458,9 @@ fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
}
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_by_name(h, a);
}
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)
@@ -459,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
}
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_index(h, a);
}
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
@@ -476,6 +497,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
/// anything is deleted, as `PageItems.removeAll()` does.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
@@ -1813,8 +1837,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
None,
named(vec![
("typename", get(l, items_typename), typed("string")),
("toString", super::class_text("PathItems"), returns("string", &[])),
("length", get(l, items_length), typed("number")),
("parent", get(l, items_parent), typed("Document")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])),
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
+3 -2
View File
@@ -2431,7 +2431,7 @@ impl Session {
eval_strict: Cell::new(None),
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::new(heap_bytes, self.documents()),
dom: dom::State::new(self.documents(), heap_bytes),
actions: request.actions,
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
artboard_picks,
@@ -2748,7 +2748,8 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) {
let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect();
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
report["activeArtboards"] = boards;
}
// The run ran a Copy or Cut, and the clipboard still holds what one put there.
+76
View File
@@ -262,6 +262,82 @@ fn steps_act_on_the_artboard_active_as_they_run() {
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
}
/// After the script makes another artboard active with `setActiveArtboardIndex`, a step that acts
/// on the active artboard acts on that one.
#[test]
fn steps_act_on_the_artboard_the_script_made_active() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 0);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", &actions);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now[0], was[0], "the artboard active as the run started is unchanged");
assert_ne!(now[1], was[1], "the artboard the script made active is fitted");
// Choosing the artboard that is already active, after an insert moved it, also counts.
make_active(&mut s, 0);
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
log_with(
&mut s,
"var b = app.activeDocument.artboards; b.insert([300, 300, 400, 200], 0); b.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');",
&actions,
);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_ne!(now[1], was[0], "the artboard chosen again is fitted");
}
#[test]
fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 2);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
let report = run_with(
&mut s,
"var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2);\
vc.log(b.getActiveArtboardIndex()); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\
vc.log(app.activeDocument.selection[0].position); app.doScript('Fit', 'Set');",
&actions,
)
.unwrap();
assert_eq!(report["log"], json!([0, [10, 10]]));
assert_eq!(report["activeArtboards"], json!([{"document": 0, "artboard": 0}]));
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now.len(), 2);
assert_ne!(now[0], was[0], "the fallback artboard is fitted");
assert_eq!(now[1], was[1], "the other artboard is unchanged");
}
#[test]
fn steps_discard_the_chosen_artboard_after_revert() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("script-actions-revert-artboard");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 2);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(
&mut s,
"app.activeDocument.artboards.setActiveArtboardIndex(0); app.activeDocument.pageItems[0].name = 'changed'; vc.run('file.revert');\
app.activeDocument.selection = app.activeDocument.pageItems[0]; app.doScript('Fit', 'Set');",
&actions,
);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now[..2], was[..2]);
assert_ne!(now[2], was[2], "playback uses the run's original index after revert");
}
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
#[test]
+537 -76
View File
@@ -754,6 +754,23 @@ fn assigning_the_reported_opacity_changes_nothing() {
assert_eq!(undo_steps(&s), steps + 1);
}
/// An item's or a layer's opacity that differs from the reported one, however little, is set as
/// given.
#[test]
fn an_opacity_near_the_reported_one_is_still_set() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap();
let out = log(
&mut s,
"var q = app.activeDocument.pageItems, i = q[0].opacity === 0 ? q[0] : q[1]; i.opacity = 0.00009; vc.log(i.opacity);\
var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);",
);
assert_eq!(out, vec![json!(0.0001), json!(0.0001)]);
let d = &s.active().unwrap().doc;
assert!(d.node(a).unwrap().opacity > 0.0);
assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0);
}
/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it
/// already has adds no undo step, and any other value throws and changes nothing.
#[test]
@@ -2375,24 +2392,6 @@ fn wrappers_go_stale_after_revert() {
}
}
/// A layer's `pageItems` and `groupItems` read before File › Revert go stale with the layer.
#[test]
fn a_layers_collections_go_stale_after_revert() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-layer-revert");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
for read in ["p.length", "p[0]", "p.removeAll()", "g.length"] {
let source = format!(
"var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems; d.pageItems[0].name = 'changed';\
vc.run('file.revert'); {read};"
);
let e = failure(&mut s, &source);
assert!(e.contains("Stale page item"), "{read}: {e}");
}
assert_eq!(s.active().unwrap().doc.layers[0].children().map(Vec::len), Some(2));
}
/// A layer's or group's `pageItems` reads a name, `index` and `toString` as the document's does.
#[test]
fn a_layers_page_items_read_names_as_the_documents_do() {
@@ -2408,33 +2407,6 @@ fn a_layers_page_items_read_names_as_the_documents_do() {
assert_eq!(out, vec![json!(["Logo", true, false, true, "Logo", "[PageItems]"]), json!("Not found"), json!("Not found")]);
}
/// An artboard read before File › Revert goes stale, and one read after is the loaded one.
#[test]
fn an_artboard_read_before_a_revert_is_stale() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-board-revert");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let e = failure(&mut s, "var d = app.activeDocument, b = d.artboards[0]; d.pageItems[0].name = 'x'; vc.run('file.revert'); b.name = 'gone';");
assert!(e.contains("Stale artboard"), "{e}");
let out = log(
&mut s,
"var d = app.activeDocument; d.pageItems[0].name = 'x'; vc.run('file.revert'); d.artboards[0].name = 'kept'; vc.log(d.artboards[0].name);",
);
assert_eq!(out, vec![json!("kept")]);
}
/// `pathItems.removeAll()` of a compound path deletes its paths and keeps the compound path, empty.
#[test]
fn clearing_a_compound_paths_paths_keeps_it() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
let out = log(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length]);");
assert_eq!(out, vec![json!(["CompoundPathItem", 0])]);
assert!(s.active().unwrap().doc.node(NodeId(c)).is_some_and(|n| n.children().is_some_and(Vec::is_empty)));
}
/// A layer's `textFrames.areaText` refuses a path in a locked layer and leaves it as it was.
#[test]
fn area_text_into_a_layer_refuses_a_locked_path() {
@@ -2461,6 +2433,25 @@ fn clipping_a_group_on_a_locked_artboard_is_refused() {
assert!(!s.active().unwrap().doc.layers[0].children().unwrap().iter().any(|n| n.clips()));
}
/// A layer's or group's collection and an artboard read before File › Revert are stale after it,
/// while the document's own collections follow the loaded document.
#[test]
fn scoped_collections_and_artboards_go_stale_after_revert() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-scoped");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let held = "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems, ab = d.artboards[0], all = d.groupItems;\
d.pageItems[0].name = 'changed'; vc.run('file.revert');";
for (read, stale) in
[("p.length", "Stale page item"), ("g.length", "Stale page item"), ("ab.name", "Stale artboard"), ("ab.name = 'x'", "Stale artboard")]
{
let source = format!("{held} try {{ {read}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}");
assert_eq!(log(&mut s, &source), vec![json!(stale)], "{read}");
}
assert_eq!(log(&mut s, &format!("{held} vc.log(all.length); vc.log(d.artboards[0].name);")), vec![json!(0), json!("Artboard 1")]);
}
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
@@ -2601,6 +2592,24 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
assert_eq!(out, vec![json!(0)]);
}
/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path,
/// empty, as `remove()` on its last path does.
#[test]
fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = layer_order(&s)[0];
let steps = undo_steps(&s);
let out = log(
&mut s,
"var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);",
);
assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]);
assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
assert_eq!(undo_steps(&s), steps + 1);
}
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
/// is runs no command, also in a layer whose ruler guides are above its art.
#[test]
@@ -3273,6 +3282,29 @@ fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
}
/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group
/// clipped as it was; the art the group clips still goes in.
#[test]
fn node_move_refuses_a_clipping_path_for_a_compound_path() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap());
let d = &s.active().unwrap().doc;
assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0)));
let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s));
let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string();
assert!(err.contains("clipping path"), "{err}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(a), Some(cid));
assert!(d.node(g).unwrap().clips());
assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0)));
}
/// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint.
#[test]
fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() {
@@ -3315,6 +3347,211 @@ fn a_compound_paths_path_items_list_the_topmost_path_first() {
assert_eq!(log(&mut s, source), [json!(30), json!(50)]);
}
/// `index(i)` on a layer's `pageItems` and a compound path's `pathItems` gives the object `[i]`
/// gives, and `Not found` past the end.
#[test]
fn scoped_collections_index_by_number() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let out = log(
&mut s,
"var d = app.activeDocument, L = d.layers[0].pageItems, P = d.compoundPathItems[0].pathItems;\
vc.log(L.index(0).typename); vc.log(P.index(1).width === P[1].width);",
);
assert_eq!(out, vec![json!("CompoundPathItem"), json!(true)]);
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.index(5);");
assert!(e.contains("Not found"), "{e}");
}
#[test]
fn scoped_collection_methods_reject_the_other_collection_class() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
rect(&mut s, 200.0, 20.0, 30.0, 40.0);
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
for (class, receiver) in
[("PathItems", "app.activeDocument.layers[0].pageItems"), ("PageItems", "app.activeDocument.compoundPathItems[0].pathItems")]
{
for call in ["removeAll.call(r)", "getByName.call(r, '')", "index.call(r, 0)"] {
let source = format!("var r = {receiver}; {class}.prototype.{call};");
let error = failure(&mut s, &source);
assert!(error.contains(&format!("not a {class}")), "{source}: {error}");
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
for property in ["typename", "length", "parent"] {
let source = format!("Object.getOwnPropertyDescriptor({class}.prototype, '{property}').get.call({receiver});");
let error = failure(&mut s, &source);
assert!(error.contains(&format!("not a {class}")), "{source}: {error}");
}
}
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn clear_releases_a_group_after_removing_its_last_compound_mask_member() {
for mode in ["whole", "anchors", "mixed"] {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
if mode == "anchors" {
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]})).unwrap();
} else if mode == "mixed" {
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
}
let before = s.active().unwrap().doc.clone();
let selection = s.active().unwrap().selection.clone();
let steps = undo_steps(&s);
s.execute("edit.clear", &json!({})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(compound).is_none(), "{mode}");
assert!(d.node(other).is_some(), "{mode}");
assert!(d.node(group).unwrap().children().unwrap().is_empty(), "{mode}");
assert!(!d.node(group).unwrap().clips(), "{mode}");
assert_eq!(undo_steps(&s), steps + 1, "{mode}");
let after = d.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, before, "{mode}");
assert_eq!(s.active().unwrap().selection, selection, "{mode}");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, after, "{mode}");
}
}
/// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the
/// layer's clipping compound path.
#[test]
fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
let layer = s.active().unwrap().doc.parent_of(cid).unwrap();
s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
run(&mut s, "app.activeDocument.layers[0].compoundPathItems.removeAll();").unwrap();
assert!(s.active().unwrap().doc.node(cid).is_none());
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
let added = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
assert_eq!(s.active().unwrap().doc.parent_of(added), Some(layer));
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(cid).is_some());
assert!(s.active().unwrap().doc.node(layer).unwrap().clips());
s.execute("edit.redo", &json!({})).unwrap();
rect(&mut s, 200.0, 20.0, 30.0, 40.0);
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
}
#[test]
fn scoped_remove_all_releases_an_empty_clipping_group_in_one_step() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let steps = undo_steps(&s);
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);");
assert_eq!(out, [json!(false), json!(0)]);
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.pageItems.length);");
assert_eq!(out, [json!(true), json!(2)]);
}
#[test]
fn clipped_setter_refuses_locked_artboards_layers_and_groups() {
for target in ["artboard", "layer", "group"] {
for clipped in [false, true] {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
if clipped {
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
}
let layer = s.active().unwrap().doc.layer_containing(NodeId(g)).unwrap();
s.edit("Lock", |d, _| {
match target {
"artboard" => d.artboards[0].locked = true,
"layer" => d.node_mut(layer).unwrap().locked = true,
_ => d.node_mut(NodeId(g)).unwrap().locked = true,
}
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let src = format!(
"var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {}; vc.log('changed'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);",
!clipped
);
let out = log(&mut s, &src);
assert!(out[0].as_str().unwrap().contains("locked"), "{target}: {out:?}");
assert_eq!(out[1], json!(clipped));
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn scoped_collections_convert_to_strings() {
let (mut s, ..) = doc();
let out = log(
&mut s,
"var l = app.activeDocument.layers[0], g = l.groupItems.add(), c = g.compoundPathItems.add();\
var lists = [l.pageItems, g.pageItems, l.layers, l.groupItems, g.groupItems, l.compoundPathItems, g.compoundPathItems, c.pathItems];\
for (var i = 0; i < lists.length; i++) { vc.log(String(lists[i])); vc.log(lists[i].toString()); }",
);
let expected: Vec<_> = ["PageItems", "PageItems", "Layers", "GroupItems", "GroupItems", "CompoundPathItems", "CompoundPathItems", "PathItems"]
.into_iter()
.flat_map(|name| [json!(format!("[{name}]")), json!(format!("[{name}]"))])
.collect();
assert_eq!(out, expected);
}
#[test]
fn layer_color_can_be_assigned_to_path_paint() {
let (mut s, ..) = doc();
let out = log(
&mut s,
"var l = app.activeDocument.layers[0]; l.color = {red: 10, green: 20, blue: 30};\
var c = l.color; vc.log(c.typename); var p = l.pageItems[0]; p.fillColor = c;\
vc.log([p.fillColor.red, p.fillColor.green, p.fillColor.blue]);",
);
assert_eq!(out, [json!("RGBColor"), json!([10, 20, 30])]);
}
/// `removeAll()` refuses to delete the compound path that clips a group while the group keeps
/// other art, and deletes nothing.
#[test]
fn scoped_remove_all_refuses_a_clipping_compound_path() {
let (mut s, a, b) = doc();
let e = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [cid.0, e.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let steps = undo_steps(&s);
let err = failure(&mut s, "app.activeDocument.groupItems[0].compoundPathItems.removeAll();");
assert!(err.contains("clipping"), "{err}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
}
/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound
/// path's paint and pixel alignment, as Release Compound Path gives them.
#[test]
@@ -3361,6 +3598,33 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() {
assert!(!d.node(a).unwrap().extras().pixel_aligned);
}
/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid
/// with the compound path's other paths.
#[test]
fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let to = s.active().unwrap().doc.parent_of(a).unwrap();
let r = rect(&mut s, 200.3, 100.3, 20.4, 20.4);
s.execute("object.setPixelAligned", &json!({"ids": [r.0], "on": false})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert!(!s.active().unwrap().doc.node(r).unwrap().extras().pixel_aligned);
let before = s.active().unwrap().doc.bounds_of(&[r], false).unwrap();
assert!(before.x0.fract().abs() > 0.01, "{before:?}");
s.execute("node.move", &json!({"id": r.0, "parent": to.0, "index": 0})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(to).unwrap().extras().pixel_aligned);
let after = d.bounds_of(&[r], false).unwrap();
assert_ne!(after, before);
assert!(!d.node(r).unwrap().extras().pixel_aligned);
assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.bounds_of(&[r], false).unwrap(), before);
}
#[test]
fn a_compound_paths_path_items_are_page_items() {
let (mut s, a, b) = doc();
@@ -3369,9 +3633,24 @@ fn a_compound_paths_path_items_are_page_items() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\
vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename);",
vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename); vc.log(p instanceof PathItems);\
vc.log(p instanceof PageItems); vc.log(p.parent === d.compoundPathItems[0]);\
p[0].name = 'member'; vc.log(p.getByName('member') === p[0]); vc.log(p.index(0) === p[0]);",
);
assert_eq!(out, [json!("PageItems"), json!(2), json!("PathItem"), json!("PageItems")]);
assert_eq!(
out,
[json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)]
);
for call in ["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"] {
let source = format!(
"var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);"
);
let out = log(&mut s, &source);
assert!(out[0].as_str().unwrap().contains("not available yet"), "{call}: {out:?}");
assert_eq!(out[1], json!(2));
}
run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap();
assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none());
}
#[test]
@@ -3405,7 +3684,12 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() {
for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\
for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\
vc.log(n);";
let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap());
crate::script::dom::ART_SCANS.with(|c| c.set(0));
let a = run(&mut s, nested).unwrap();
// The groups' list and each group's list are built once: 1 + 5 lists.
let scans = crate::script::dom::ART_SCANS.with(std::cell::Cell::get);
assert!(scans <= 6, "{scans} lists built for 5 groups");
let b = run(&mut s, in_order).unwrap();
assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10])));
assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}");
// A list built again for each lookup would add a host call to both. Building the document's
@@ -3413,6 +3697,74 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() {
assert_eq!(a["hostCalls"], json!(51), "{a}");
}
/// A loop over `layers.length` and `layers[i]` lists the layers once while the document is
/// unchanged, so it looks at each layer a bounded number of times.
#[test]
fn a_loop_over_layers_lists_them_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for _ in 0..39 {
s.execute("layer.new", &json!({})).unwrap();
}
let n = s.active().unwrap().doc.layers.len() as u64;
crate::script::dom::LAYER_SCANS.with(|c| c.set(0));
let out = log(&mut s, "var L = app.activeDocument.layers, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);");
assert_eq!(out, vec![json!(n)]);
let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get);
assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers");
}
/// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the
/// document's `pageItems`, also when the list was already built.
#[test]
fn scoped_name_searches_are_charged_each_time() {
let (mut s, ..) = doc();
let calls = |s: &mut Session, list: &str, k: usize| {
let source = format!("var p = {list}; p.length; for (var i = 0; i < {k}; i++) {{ try {{ p.getByName('none'); }} catch (e) {{}} }}");
run(s, &source).unwrap()["hostCalls"].as_u64().unwrap()
};
let doc_cost = calls(&mut s, "app.activeDocument.pageItems", 6) - calls(&mut s, "app.activeDocument.pageItems", 1);
let layer_cost = calls(&mut s, "app.activeDocument.layers[0].pageItems", 6) - calls(&mut s, "app.activeDocument.layers[0].pageItems", 1);
assert_eq!(layer_cost, doc_cost);
}
#[test]
fn layer_z_order_scans_are_charged_each_time() {
let (mut s, ..) = doc();
let repeated = "var l = app.activeDocument.layers[0]; for (var i = 0; i < 512; i++) l.zOrderPosition;";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let small = run(&mut s, repeated);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
small.unwrap();
for _ in 0..100 {
s.execute("layer.new", &json!({})).unwrap();
}
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let once = run(&mut s, "var l = app.activeDocument.layers[0]; l.zOrderPosition;");
let large = run(&mut s, repeated);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
once.unwrap();
let error = large.unwrap_err().to_string();
assert!(error.contains("passed more data"), "{error}");
}
#[test]
fn has_selected_artwork_keeps_selected_objects_in_other_layers() {
let (mut s, a, b) = doc();
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, other.0]})).unwrap();
for (operation, a_selected, b_selected) in
[("vc.log(l.hasSelectedArtwork)", true, false), ("l.hasSelectedArtwork = false", false, false), ("l.hasSelectedArtwork = true", true, true)]
{
let source = format!("var l = app.activeDocument.layers.getByName('Layer 1'); {operation};");
run(&mut s, &source).unwrap();
assert!(s.active().unwrap().selection.objects.contains(&other), "{operation}");
let selected = &s.active().unwrap().selection.objects;
assert_eq!((selected.contains(&a), selected.contains(&b)), (a_selected, b_selected), "{operation}");
}
}
#[test]
fn group_items_remove_all_refuses_locked_groups() {
let (mut s, a, b) = doc();
@@ -3439,6 +3791,11 @@ fn new_group_command_checks_its_parent() {
assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group"));
assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be"));
let before = format!("{:?}", s.active().unwrap().doc.layers);
assert!(s.execute("object.newGroup", &json!({"parent": null})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": null})).unwrap_err().to_string().contains("index must be"));
assert!(s.execute("object.newGroup", &json!({"compound": null})).unwrap_err().to_string().contains("compound must be"));
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked"));
}
@@ -3565,25 +3922,6 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() {
assert!(r.get("activeArtboards").is_none());
}
/// Choosing the artboard that is already active by default keeps that artboard active when another
/// is inserted before it.
#[test]
fn choosing_the_default_active_artboard_follows_it_past_an_insert() {
let (mut s, _, _) = doc();
run(&mut s, "app.activeDocument.artboards.add([500, 300, 700, 100]);").unwrap();
let first = s.active().unwrap().doc.artboards[0].id;
let out = log(
&mut s,
"var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0); vc.log(A.getActiveArtboardIndex());",
);
assert_eq!(out, [json!(1)]);
assert_eq!(s.active().unwrap().active_artboard, Some(first));
// In a document the run opens, the report gives the chosen artboard's index at the end.
let r = run(&mut s, "var d = app.documents.add(); d.artboards.setActiveArtboardIndex(0); d.artboards.insert([800, 300, 900, 100], 0);").unwrap();
let boards = r["activeArtboards"].as_array().cloned().unwrap_or_default();
assert!(boards.iter().any(|b| b["document"] == json!(1) && b["artboard"] == json!(1)), "{r}");
}
/// A stale container's `pageItems.index(n)` and `groupItems.index(n)` throw the stale error for
/// every number, a negative one included.
#[test]
@@ -3627,9 +3965,9 @@ fn remove_all_on_a_clip_group_releases_its_mask() {
assert_eq!(out, [json!(true), json!(2)]);
}
/// Deleting a clip group's clipping path while other art stays in the group releases the mask, so
/// the art above it is not made the clipping path. `remove()` on the clipping path does the same,
/// and so does emptying a clipping layer with the document's `pageItems.removeAll()`.
/// `remove()` on a clip group's clipping path while other art stays in the group releases the
/// mask, so the art above it is not made the clipping path, and so does emptying a clipping layer
/// with the document's `pageItems.removeAll()`.
#[test]
fn deleting_a_clipping_path_releases_its_mask() {
let (mut s, a, b) = doc();
@@ -3645,11 +3983,6 @@ fn deleting_a_clipping_path_releases_its_mask() {
assert!(matches!(s.active().unwrap().doc.node(mask).unwrap().kind, NodeKind::Compound { .. }));
s.execute("object.setProps", &json!({"id": mask.0, "name": "mask"})).unwrap();
let clips = |s: &Session| s.active().unwrap().doc.node(g).unwrap().clips();
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.compoundPathItems.removeAll(); vc.log([g.clipped, g.pageItems.length]);");
assert_eq!(out, [json!([false, 2])]);
assert!(!clips(&s));
assert_eq!(kids(&s), [a, b]);
s.execute("edit.undo", &json!({})).unwrap();
assert!(clips(&s));
let out =
log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.getByName('mask').remove(); vc.log([g.clipped, g.pageItems.length]);");
@@ -3665,6 +3998,119 @@ fn deleting_a_clipping_path_releases_its_mask() {
assert!(!s.active().unwrap().doc.layers[0].clips());
}
/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it
/// moves it to the next index, and the report gives that index.
#[test]
fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() {
let (mut s, _, _) = doc();
assert_eq!(s.active().unwrap().active_artboard, None);
let first = s.active().unwrap().doc.artboards[0].id;
let r = run(
&mut s,
"var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\
vc.log(A.getActiveArtboardIndex());",
)
.unwrap();
assert_eq!(r["log"], json!([1]));
assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}]));
assert_eq!(s.active().unwrap().active_artboard, Some(first));
}
/// In a document the run makes, choosing artboard 0 and then inserting one before it still puts
/// the document in the report.
#[test]
fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() {
let (mut s, _, _) = doc();
let r = run(
&mut s,
"var d = app.documents.add(); var A = d.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\
vc.log(A.getActiveArtboardIndex());",
)
.unwrap();
assert_eq!(r["log"], json!([1]));
let list = r["activeArtboards"].as_array().cloned().unwrap_or_default();
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
}
/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard.
#[test]
fn artboards_insert_returns_nothing() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var A = app.activeDocument.artboards; vc.log(typeof A.insert([0, -100, 100, -200], 0)); vc.log(A.add([500, 300, 700, 100]).typename);",
);
assert_eq!(out, [json!("undefined"), json!("Artboard")]);
}
/// The collections' `index` is described as giving an element, and `toString` of a collection
/// whose container is gone fails as `typename` does.
#[test]
fn collection_index_reflection_and_stale_to_string() {
let (mut s, a, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument; vc.log([d.layers.reflect.find('index').dataType, d.groupItems.reflect.find('index').dataType,\
d.compoundPathItems.reflect.find('index').dataType, d.artboards.reflect.find('index').dataType]);",
);
assert_eq!(out, [json!(["Layer", "GroupItem", "CompoundPathItem", "Artboard"])]);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let live = log(&mut s, "vc.log(app.activeDocument.groupItems[0].groupItems.toString()); vc.log(app.activeDocument.layers[0].layers.toString());");
assert_eq!(live, [json!("[GroupItems]"), json!("[Layers]")]);
let source = "var g = app.activeDocument.groupItems[0]; var c = g.groupItems; g.remove(); c.toString();";
let error = failure(&mut s, source);
assert!(error.contains("Stale page item"), "{error}");
let source = "var l = app.activeDocument.layers.add(); var c = l.layers; l.remove(); c.toString();";
let error = failure(&mut s, source);
assert!(error.contains("Stale layer"), "{error}");
}
/// Setting `hasSelectedArtwork = true` on a layer whose art is all selected runs no command but
/// is still charged for the art it looks at.
#[test]
fn has_selected_artwork_charges_the_walk_when_nothing_is_added() {
// `locked`: the art is locked, so nothing is selectable; otherwise it is all selected.
let repeated = |n: usize, locked: bool| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect();
if locked {
s.execute("object.setProps", &json!({"ids": ids, "locked": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
} else {
s.execute("select.set", &json!({"ids": ids})).unwrap();
}
let steps = undo_steps(&s);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13)));
let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = true;");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
assert_eq!(undo_steps(&s), steps);
r
};
for locked in [false, true] {
repeated(1, locked).unwrap();
let error = repeated(200, locked).unwrap_err().to_string();
assert!(error.contains("passed more data"), "{locked}: {error}");
}
// `false` on an empty layer is charged for the selection held in another layer, which stays.
let deselect = |n: usize| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect();
s.execute("layer.new", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": ids})).unwrap();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13)));
let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = false;");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
assert_eq!(s.active().unwrap().selection.objects.len(), n);
r
};
deselect(1).unwrap();
let error = deselect(200).unwrap_err().to_string();
assert!(error.contains("passed more data"), "{error}");
}
#[test]
fn the_report_gives_the_active_artboard_the_run_leaves() {
let (mut s, _, _) = doc();
@@ -3749,6 +4195,21 @@ fn has_selected_artwork_keeps_the_rest_of_the_selection() {
assert_eq!(sel.guides.len(), 1);
}
/// The selection limit counts only the art an assignment would add: a layer with nothing to add
/// changes nothing beside a selection already at the limit, and one with art to add throws.
#[test]
fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() {
let (mut s, a, _) = doc();
run(&mut s, "app.activeDocument.layers.add();").unwrap();
// A selection of 10,001 entries, as the limit counts them.
s.active_mut().unwrap().selection.objects = vec![a; 10_001];
run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}"));
assert_eq!(s.active().unwrap().selection.objects.len(), 10_001);
s.active_mut().unwrap().selection.objects = vec![a; 10_000];
let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;");
assert!(e.contains("at most 10000"), "{e}");
}
#[test]
fn has_selected_artwork_on_an_empty_layer_passes_a_full_selection() {
let (mut s, a, _) = doc();
@@ -3802,7 +4263,7 @@ fn every_page_item_has_its_layer_and_members_check_this() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\
vc.log(p.layer.name); vc.log(d.pageItems[1].layer.name); vc.log(p.layer.layers.typename);\
vc.log(p.layer.name); vc.log(d.pageItems[d.pageItems.length - 1].layer.name); vc.log(p.layer.layers.typename);\
vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);",
);
assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]);
+54 -2
View File
@@ -448,6 +448,55 @@ fn image_matrix_assignment_transforms_the_image() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tiny_matrix_change_still_transforms_the_image() {
let base = folder("matrix-tiny");
let g = base.join("main/g.png");
std::fs::write(&g, gray_png(10, 20)).unwrap();
let mut s = session();
let id = place(&mut s, &g, false);
let before = undo_steps(&s);
let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Image(im) => im.xf.as_coeffs()[4],
_ => panic!("not an image"),
};
let old = tx(&s);
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;");
assert_eq!(undo_steps(&s), before + 1);
assert!(tx(&s) != old, "the image did not move");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_stale_placed_item_is_not_a_relative_object() {
let base = folder("stale-relative");
let a = base.join("main/a.png");
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
place(&mut s, &a, true);
place(&mut s, &a, true);
place(&mut s, &a, true);
let out = log(
&mut s,
&base,
&format!(
"var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\
r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\
var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\
p.embed();\
try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
n.embed();\
try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
vc.log(m);",
js_path(&a)
),
);
assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn image_matrix_refuses_bad_values_without_changing_the_image() {
let base = folder("matrix-bad");
@@ -599,16 +648,19 @@ fn stale_and_foreign_placed_items_are_refused() {
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
let id = place(&mut s, &a, true);
place(&mut s, &a, false);
let out = log(
&mut s,
&base,
"var p = app.activeDocument.placedItems[0], m = []; p.remove();\
try { p.relink(null); } catch (e) { m.push(e.message); }\
try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\
var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\
try { g.call(1); } catch (e) { m.push(e.name); }\
m.push(g.call(app.activeDocument.rasterItems[0]));\
try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\
vc.log(m);",
);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]);
assert!(s.active().unwrap().doc.node(id).is_none());
let _ = std::fs::remove_dir_all(base);
}
@@ -97,11 +97,11 @@ const INSIDE: &[(&str, &str)] = &[
(
"",
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType DocumentPreviewMode \
DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement GroupItem GroupItems Layer Layers \
PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem PlacedItems PluginItem PointType \
PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection selection= StrokeCap StrokeJoin Tag Tags \
TracingObject TracingOptions Transformation View Views ZOrderMethod",
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
),
("Application.", "prototype"),
(
@@ -135,8 +135,8 @@ const INSIDE: &[(&str, &str)] = &[
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems \
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
@@ -153,7 +153,7 @@ const INSIDE: &[(&str, &str)] = &[
toString typename visible visible= zOrder zOrderPosition",
),
("Layers.", "prototype"),
("Layers.prototype.", "add constructor getByName index length parent removeAll typename"),
("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"),
("GroupItem.", "prototype"),
(
"GroupItem.prototype.",
@@ -161,22 +161,22 @@ const INSIDE: &[(&str, &str)] = &[
rasterItems rasterItems= symbolItems symbolItems= textFrames",
),
("GroupItems.", "prototype"),
("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll typename"),
("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"),
("CompoundPathItem.", "prototype"),
("CompoundPathItem.prototype.", "constructor pathItems"),
("CompoundPathItems.", "prototype"),
("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll typename"),
("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll toString typename"),
("Artboard.", "prototype"),
(
"Artboard.prototype.",
"artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \
showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= typename",
showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= toString typename",
),
("Artboards.", "prototype"),
(
"Artboards.prototype.",
"add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \
typename",
toString typename",
),
("PageItems.", "prototype"),
("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"),
@@ -184,8 +184,8 @@ const INSIDE: &[(&str, &str)] = &[
(
"PageItem.prototype.",
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer \
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \
left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
@@ -222,7 +222,10 @@ const INSIDE: &[(&str, &str)] = &[
viewVector=",
),
("PathItems.", "prototype"),
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
(
"PathItems.prototype.",
"add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename",
),
("PathItem.", "prototype"),
(
"PathItem.prototype.",
@@ -554,8 +557,7 @@ const INSIDE: &[(&str, &str)] = &[
];
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
/// other than `PathItem`, `GroupItem`, `CompoundPathItem`, `PlacedItem` and `RasterItem`, the color
/// classes and the save and export option classes.
/// that have no members of their own, the color classes, and the save and export option classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
+9
View File
@@ -997,6 +997,15 @@ fn a_host_class_constructor_called_with_new_cannot_wait() {
assert_eq!(could.get(), Some(false));
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() {
let mut r = realm(1_000_000);
let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0)));
with_thing(&mut r, Some(make));
r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap();
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true));
}
#[test]
fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() {
let mut r = realm(1_000_000);
+46 -5
View File
@@ -583,19 +583,24 @@ fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUni
let shown = f64::from(shown_columns(s));
let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid);
if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) {
// A column count replaces a preset's rows.
s.columns = v.round().clamp(1.0, n) as u32;
s.rows = 0;
set_columns(s, v.round().clamp(1.0, n) as u32);
}
});
}
/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns
/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the
/// stored count. At most one for each artboard.
/// stored count, where a stored 0 shows the columns `file.new` lays out for the layout. At most
/// one for each artboard.
fn shown_columns(s: &DocSettings) -> u32 {
let n = s.artboards.max(1);
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) }
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 {
u32::try_from(s.grid_columns()).unwrap_or(n)
} else if s.columns == 0 {
u32::try_from(s.grid_columns()).unwrap_or(n).clamp(1, n)
} else {
s.columns.min(n)
}
}
/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column
@@ -611,6 +616,15 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) {
s.layout = l;
}
/// A column count entered in More Settings replaces the rows of a preset made with `file.new`'s
/// `rows`; the same count as shown changes nothing.
fn set_columns(s: &mut DocSettings, columns: u32) {
if columns != shown_columns(s) {
s.columns = columns;
s.rows = 0;
}
}
/// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a
/// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`.
fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>) {
@@ -1316,6 +1330,33 @@ mod tests {
assert!(app.session.documents().is_empty(), "no document was made");
}
/// A new column count replaces a preset's rows; the count already shown changes nothing.
#[test]
fn a_new_column_count_replaces_a_presets_rows() {
let rows = DocSettings { artboards: 9, layout: ArtboardLayout::GridByColumn, columns: 2, rows: 4, ..DocSettings::default() };
let mut s = rows.clone();
set_columns(&mut s, 3);
assert_eq!(s, rows, "3 is what the rows show");
set_columns(&mut s, 2);
assert_eq!((s.layout, s.columns, s.rows), (ArtboardLayout::GridByColumn, 2, 0));
assert_eq!(s.grid_columns(), 2);
}
/// A stored column count of 0 shows the one row of all the artboards that `file.new` lays out, so
/// entering 1 is stored and the same count as the row changes nothing.
#[test]
fn a_column_count_without_rows_is_stored() {
let mut s = DocSettings { artboards: 4, layout: ArtboardLayout::GridByRow, columns: 0, rows: 0, ..DocSettings::default() };
assert_eq!(shown_columns(&s), u32::try_from(s.grid_columns()).unwrap_or(0));
set_columns(&mut s, 4);
assert_eq!((s.columns, s.rows), (0, 0), "4 is what the row shows");
set_columns(&mut s, 1);
assert_eq!((s.columns, s.rows), (1, 0));
assert_eq!(s.grid_columns(), 1);
let column = DocSettings { artboards: 4, layout: ArtboardLayout::Column, columns: 0, rows: 0, ..DocSettings::default() };
assert_eq!(shown_columns(&column), 1, "the Column layout is one column");
}
/// The preset keeps the artboard layout, spacing and columns More Settings set (#4893); an empty
/// name is refused.
#[test]
+13 -13
View File
@@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC
use craft::ui::display::Divider;
use craft::ui::docking::{DockGrid, GroupAt};
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout_components::Row;
use craft::ui::pickers::{Anchor9, ReferencePointLook, Select};
use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot};
use craft::ui::runtime::commands::{self, CommandRef};
@@ -899,17 +899,21 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) {
}
pub(crate) mod card;
/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last.
/// Search and Edit Toolbar share a row in a wide rail. A one-column rail shows Edit Toolbar alone, so the default
/// rail still fits a 1000 pt window; Search Commands stays in the title bar, the Help menu and on its shortcut.
fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option<egui::Response> {
let enabled = !crate::panel_docking::modal_window_up(app);
let wide = footer.columns > 1;
let mut edit = None;
let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| {
IconButton::command(IconId::new("search"), "help.commandPalette")
.label(tl!("Search commands"))
.tooltip(tl!("Search commands, tools, panels and effects"))
.selected(app.ui.palette_open)
.enabled(enabled)
.show(ui);
if wide {
IconButton::command(IconId::new("search"), "help.commandPalette")
.label(tl!("Search commands"))
.tooltip(tl!("Search commands, tools, panels and effects"))
.selected(app.ui.palette_open)
.enabled(enabled)
.show(ui);
}
edit = Some(
IconButton::new(IconId::new("more"))
.label(tl!("Edit Toolbar"))
@@ -919,11 +923,7 @@ fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter
.response,
);
};
if footer.columns > 1 {
Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
} else {
Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
}
Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
edit
}
+41 -9
View File
@@ -727,19 +727,22 @@ fn review_8758_layout(double: bool) {
let nodes = settled(&mut app, &ctx, 0.0, 1400.0);
review_8758_edit_control(&mut app, &ctx, &nodes);
let nodes = settled(&mut app, &ctx, 3.0, 1400.0);
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap();
let panel = review_8758_panel(&app, &ctx);
if !double {
assert!(panel.contains_rect(edit) && edit.bottom() <= 1400.0, "Edit Toolbar fits the actual Tools panel");
assert!(
!nodes
.iter()
.any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| panel.contains_rect(r))),
"a one-column rail shows Edit Toolbar alone"
);
return;
}
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel");
assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window");
if double {
assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row");
} else {
assert!(
search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01,
"one column keeps both controls in a fitted stack"
);
}
assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row");
let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut");
let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform());
let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center());
@@ -768,10 +771,39 @@ fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette()
}
}
/// The default one-column rail in a window 1000 points tall: its footer ends with Edit Toolbar inside the rail's
/// visible area, so the button shows without scrolling the rail.
#[test]
fn one_column_rail_shows_edit_toolbar_in_a_1000_point_window() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(300, 300);
let ctx = reader();
let nodes = settled(&mut app, &ctx, 0.0, 1000.0);
let panel = review_8758_panel(&app, &ctx);
let rail = nodes
.iter()
.find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools") && bounds(n).is_some_and(|r| panel.contains_rect(r)))
.and_then(bounds)
.expect("the Tools rail is drawn");
let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap();
let screen_mode = named_rect(&nodes, "Change Screen Mode (F)");
assert!(rail.contains_rect(edit), "Edit Toolbar shows inside the rail without scrolling: {edit:?} in {rail:?}");
assert!(screen_mode.bottom() <= edit.top(), "Edit Toolbar stays the last control of the footer");
assert!(
!nodes.iter().any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| rail.intersects(r))),
"one column leaves Search Commands to the title bar, the Help menu and its shortcut"
);
// Edit Toolbar still opens the Tools customization drawer.
click(&mut app, &ctx, 1.0, edit.center(), 1000.0);
assert!(app.ui.tools_drawer, "the footer's Edit Toolbar opens the customization drawer");
}
#[test]
fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(300, 300);
// The two-column rail, whose footer has Search.
app.run("window.toolbarColumns", json!({"double": true})).unwrap();
let ctx = reader();
let nodes = settled(&mut app, &ctx, 0.0, 1400.0);
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
+7 -6
View File
@@ -27,7 +27,7 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe
OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
@@ -857,12 +857,13 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
## G6 Automation and scripting
- **Missing:** the rest of the document object model for scripts (gradient stops and the other classes)
and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
documents, new documents, each document's selection, its page items, layers, groups, compound paths and artboards,
its text frames with their text ranges and
- **Missing:** the rest of the document object model for scripts (gradient stops and the other classes) and the
`#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's
selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and
character and paragraph attributes, their links to each other and the stories they form, its character and
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its
linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing,
rasterizing and capturing images are still missing.
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
+45 -21
View File
@@ -3218,11 +3218,12 @@ through `$`:
a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note`
take a number or a Boolean as the text `String(value)` gives. `String(object)` gives
`[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document <name>]`,
`[Layer <name>]`, `[Application]` and `[PageItems]` (VectorCraft's own rule).
`[Layer <name>]`, `[Artboard <name>]`, `[Application]`, `[PageItems]`, `[Layers]`, `[GroupItems]`,
`[CompoundPathItems]` and `[Artboards]` (VectorCraft's own rule).
`documents[0]` is always the active document, as the same page says. VectorCraft's own rules: the other
documents follow from the one active most recently to the one active longest ago, and a change a script
makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides
(the layers paragraph below gives the order of a layer's, a group's and a compound path's lists). A document's
makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides (the layers
paragraph below gives the order of a layer's, a group's and a compound path's lists). A document's
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates
are points with Y up from the bottom-left corner of the first artboard, or, with
`CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename`
@@ -3232,7 +3233,12 @@ through `$`:
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws
`Stale page item`. Layer objects also become stale after their document is reverted. `remove()` on an object that
`Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`,
`groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`Stale page item`)
and `Artboard` objects (`Stale artboard`); the document's own collections list the reverted document.
`removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's
`groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group
or layer that keeps other objects. `remove()` on an object that
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
@@ -3283,9 +3289,10 @@ through `$`:
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`,
`index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`.
`clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/)
has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`),
`insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not the index the new
artboard got, so an index that appends runs no `artboard.reorder`; returns `undefined`), `remove(index)` (runs
has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns
the new artboard), `insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not
the index the new artboard got, so an index that appends runs no `artboard.reorder`; returns nothing; read
`artboards[index]` afterward), `remove(index)` (runs
`artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard`
(https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`,
`rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its
@@ -3295,22 +3302,30 @@ through `$`:
`pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in
it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any
depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound
path's `pathItems` have the typename `PageItems`. A layer's or artboard's `name` takes a number or a boolean as
`String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole
path's `pathItems` are `PathItems` objects with `length`, `[i]`, `index`, `getByName`, `removeAll` and string conversion.
Their path creation methods throw an error; a script can move existing paths into the compound path.
Scoped collections support `toString()` and `String()`. For `Layers`, `GroupItems`, `CompoundPathItems` and
`Artboards`, the conversion throws the same error as `typename` once the container is deleted or the document is
closed. A layer's or artboard's `name` takes a number or a boolean as
`String()` writes it. `locked` true means the layer is locked. `color` is an `RGBColor` object with `typename` and `{red, green, blue}` of whole
numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers
beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past
beside it from 1 at the bottom, leaving out art; each scan counts toward the script's operation budget.
`zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past
the next layer beside it and any art between them.
`hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false`
deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer
with nothing to add or deselect runs no command, whatever the size of the selection; adding art that takes the
selection past 10,000 objects throws a `RangeError`.
with nothing to add or deselect runs no command. Each assignment counts the current selection toward the script's
operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included.
`clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping
path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the
path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is
hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer
without art releases its mask in the same undo step. `groupItems.add()` makes an empty group on top of the
layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()`
makes an empty compound path in the same place
(https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a
compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. The
compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. An empty
compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. A path moved
into an already pixel-aligned compound path is snapped to the pixel grid. An empty
compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the
compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or
a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths.
@@ -3333,8 +3348,10 @@ through `$`:
default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group,
index 0 puts it directly above the clipping path), as one undo step named Group, and
gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path.
An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false).
Explicit `null` is refused for `parent`, `index` and `compound`.
The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path
gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A
gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A
path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel
alignment, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the
clipping path of a clip group or clipping layer at its bottom: it refuses to move the clipping path until the mask
@@ -3499,8 +3516,9 @@ through `$`:
`null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true
for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY`
that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning
`matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of
the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
`matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value
that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a
nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete
objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the
item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()`
@@ -3874,9 +3892,13 @@ through `$`:
app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own
steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and
Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to
Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run
started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one
past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Selected Art) and does not name one acts on the active document's active artboard. Once the script has called
`setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it
has been deleted, playback uses the same fallback as `getActiveArtboardIndex()`, script coordinates and the view:
the saved active artboard if it still exists, otherwise index 0. File > Revert discards the script's stored choice.
If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard
as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the
end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that
names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's
own rules: the action and its set are matched by their exact names, and a name that matches no action or more than
@@ -4968,6 +4990,7 @@ With `ids`, `guides: true` also deletes the selected ruler guides. The command r
boolean or `null`. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps
it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean or `null`
is rejected. `null` for `guides`, `keepEmpty` or `keepJoined` counts as leaving the key out.
A clipping group or layer left without art releases its mask in the same undo step.
Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as
`path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected
(the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected
@@ -11097,7 +11120,8 @@ that category), `name`, `width`/`height`
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes;
with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays out: one row of all the artboards in a grid),
`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)).
+1 -1
View File
@@ -33,7 +33,7 @@
## Feature submission evidence
Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
+4 -4
View File
@@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in Help › Search Commands… and its shortcut, and in the title bar while the app bar is wide enough to show it. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
@@ -1114,7 +1114,6 @@ 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: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
@@ -1126,16 +1125,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; compound paths expose `PathItems` objects and reject unsupported path creation. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name are not there yet. `crates/engine/src/tests/script_dom.rs`.
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
- Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.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 warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
+2 -2
View File
@@ -29,7 +29,7 @@
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged.
@@ -497,7 +497,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | unknown |
| Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | unknown |
| Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | unknown |
| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown |
| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and Edit Toolbar alone in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown |
| Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | unknown |
| Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | unknown |
| Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | unknown |