mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Scripts: fix further review findings in the layer and path items
- Point changes that add, remove or replace points deselect the path's direct-selected anchors even when the counts come out the same; path.setAnchors takes `reshaped` for this and refuses a non-boolean. - Moving points or handles, changing a point's type or setting `closed` keeps the index of where each subpath's points start. - A failed write keeps the waiting point changes. - Restoring the selection keeps a segment-only path to its segments. - getIsFileOpen folds `\` and letter case only on Windows. - Assigning `undefined` to Document.selection throws with nothing changed. - A document's path list is charged for the objects it looks at. - A made path keeps an id above 2^53. - A host object's handle is charged to the heap limit. - docs/mcp.md states that node.move into a compound path also needs its layer and groups shown and unlocked and no locked artboard.
This commit is contained in:
1 parent
0c90d0d5c1
commit
a8cd6180ce
9 files changed
+212
-45
No files matched your search
@@ -120,7 +120,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; 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; a path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard, 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
|
||||
),
|
||||
|
||||
@@ -68,7 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Anchors",
|
||||
[],
|
||||
None,
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry",
|
||||
"{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}], reshaped?: bool (true: the anchors were added, removed or replaced, so the path's direct-selected anchors are deselected even when each subpath keeps its count)} replace a path's geometry",
|
||||
has_doc,
|
||||
set_anchors
|
||||
),
|
||||
@@ -757,14 +757,19 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?,
|
||||
);
|
||||
let replaced = match p.get("reshaped") {
|
||||
None => false,
|
||||
Some(Value::Bool(v)) => *v,
|
||||
Some(_) => return Err(bad("path.setAnchors", "reshaped must be a boolean")),
|
||||
};
|
||||
s.edit("Reshape", |d, sel| {
|
||||
let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::<Vec<_>>();
|
||||
let path = path_mut(d, id)?;
|
||||
let reshaped = counts(path) != counts(&data);
|
||||
let reshaped = replaced || counts(path) != counts(&data);
|
||||
*path = data;
|
||||
super::object::resnap(d, id);
|
||||
// Direct-selected anchors and segments are kept by index: when anchors were added or
|
||||
// removed, the path is deselected rather than left with other anchors selected.
|
||||
// Direct-selected anchors and segments are kept by index: when anchors were added,
|
||||
// removed or replaced, the path is deselected rather than left with other anchors selected.
|
||||
if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) {
|
||||
sel.objects.retain(|o| *o != id);
|
||||
sel.prune(d);
|
||||
|
||||
@@ -44,6 +44,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
mod colors;
|
||||
pub(super) mod layers;
|
||||
mod paths;
|
||||
#[cfg(test)]
|
||||
pub(crate) use paths::index_builds;
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
@@ -112,6 +114,12 @@ pub(super) struct State {
|
||||
/// How many times [`paths`] changed the waiting point changes, which makes a
|
||||
/// [`paths::PointIndex`] of them stale.
|
||||
pending_changes: Cell<u64>,
|
||||
/// Whether the waiting point changes added, removed or replaced points, so that writing them
|
||||
/// deselects the path's direct-selected anchors even when the counts come out the same.
|
||||
pending_reshaped: Cell<bool>,
|
||||
/// The path [`flush`] is writing reshaped changes to, whose direct-selected anchors and
|
||||
/// segments [`on_doc`] does not select again.
|
||||
reshaping: Cell<Option<Item>>,
|
||||
/// Where the points of the path the run last read points of start, by subpath ([`paths`]).
|
||||
point_index: RefCell<Option<paths::PointIndex>>,
|
||||
/// How many times the points the run read of each path went stale, by document uid and path id
|
||||
@@ -626,12 +634,15 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
} else {
|
||||
// One `select.anchorsMany` selects every object in its order: a partly selected path with
|
||||
// its anchors, a whole path with all of them and any other object with none.
|
||||
// its anchors, a whole path with all of them and any other object with none. A path with
|
||||
// only segments selected gets no anchors here, so `select.segments` below selects it with
|
||||
// just those segments.
|
||||
let items: Vec<Value> = kept
|
||||
.iter()
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
};
|
||||
json!({"id": i.0, "anchors": anchors})
|
||||
@@ -747,15 +758,16 @@ fn on_doc_layer<T>(
|
||||
let s = h.session.borrow();
|
||||
s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone())
|
||||
};
|
||||
// Anchors and segments are selected by index: a path that gained or lost anchors is not
|
||||
// selected again, so that other anchors of it are not selected in their place.
|
||||
// Anchors and segments are selected by index: a path that gained, lost or replaced anchors
|
||||
// is not selected again, so that other anchors of it are not selected in their place.
|
||||
if let Some(doc) = &doc {
|
||||
let counts = |d: &Document, id: NodeId| {
|
||||
d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::<Vec<_>>())
|
||||
};
|
||||
let reshaped = h.dom.reshaping.get().filter(|it| it.doc.uid == uid).map(|it| it.id);
|
||||
let partial: Vec<NodeId> = before.anchors.keys().chain(before.segments.keys()).copied().collect();
|
||||
for id in partial {
|
||||
if counts(&old, id) != counts(doc, id) {
|
||||
if reshaped == Some(id) || counts(&old, id) != counts(doc, id) {
|
||||
before.anchors.remove(&id);
|
||||
before.segments.remove(&id);
|
||||
before.objects.retain(|o| *o != id);
|
||||
@@ -840,13 +852,15 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter
|
||||
/// or a `\`) letters in one case.
|
||||
/// A path as `getIsFileOpen` compares it, without a trailing `/`: on Windows, `\` and `/` alike and
|
||||
/// letters in one case; elsewhere `\` is part of a name and case counts.
|
||||
fn path_key(p: &str) -> String {
|
||||
let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':');
|
||||
let p = p.replace('\\', "/");
|
||||
let p = p.trim_end_matches('/').to_string();
|
||||
if windows { p.to_lowercase() } else { p }
|
||||
path_key_on(p, cfg!(windows))
|
||||
}
|
||||
|
||||
/// [`path_key`] for Windows when `windows`, else for macOS and Linux.
|
||||
pub(crate) fn path_key_on(p: &str, windows: bool) -> String {
|
||||
if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() }
|
||||
}
|
||||
|
||||
/// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is
|
||||
@@ -1391,7 +1405,8 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
/// `[]`. Every one must be an object of that document that can be selected.
|
||||
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
let list: Vec<&Data> = match v {
|
||||
Data::Null | Data::Undefined => Vec::new(),
|
||||
Data::Null => Vec::new(),
|
||||
Data::Undefined => return Err(HostError::Type("the selection takes a page item, a list of them, null or [], not undefined".into())),
|
||||
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
|
||||
Data::Array(a) => a.iter().collect(),
|
||||
d => vec![d],
|
||||
|
||||
@@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru
|
||||
use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float,
|
||||
frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get,
|
||||
point_method, point_property, property, this_doc, typename_of, whole, with_doc,
|
||||
Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, edit_item, editable,
|
||||
find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point,
|
||||
point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -176,6 +176,18 @@ impl PointIndex {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`point_place`] built a [`PointIndex`] on this thread.
|
||||
static INDEX_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times a [`PointIndex`] was built on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn index_builds() -> u64 {
|
||||
INDEX_BUILDS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The number of points of the path of `item`, its waiting point changes included, and the subpath
|
||||
/// and the place in it of point `i` when `i` is given and in the path. The index of the path's
|
||||
/// subpaths is kept in [`super::State`] until the path's points change.
|
||||
@@ -198,6 +210,8 @@ fn point_place(h: &super::Host, item: Item, i: Option<usize>) -> std::result::Re
|
||||
}
|
||||
});
|
||||
if !fresh {
|
||||
#[cfg(test)]
|
||||
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
|
||||
let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?;
|
||||
*h.dom.point_index.borrow_mut() = Some(index);
|
||||
}
|
||||
@@ -230,12 +244,27 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
|
||||
/// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object
|
||||
/// that is, is written at once, so that its points read as the grid snaps them.
|
||||
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
|
||||
h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1));
|
||||
edit_points_keeping(h, item, false, f)
|
||||
}
|
||||
|
||||
/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as
|
||||
/// they are, so a [`PointIndex`] of the waiting changes stays good.
|
||||
fn edit_points_keeping<T>(
|
||||
h: &super::Host,
|
||||
item: Item,
|
||||
counts_kept: bool,
|
||||
f: impl FnOnce(&mut Vec<SubPath>) -> T,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
|
||||
&& same_path(*waiting, item)
|
||||
{
|
||||
if !counts_kept {
|
||||
h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1));
|
||||
h.dom.pending_reshaped.set(true);
|
||||
}
|
||||
return Ok(f(subs));
|
||||
}
|
||||
h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1));
|
||||
flush(h)?;
|
||||
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
|
||||
let r = f(&mut subs);
|
||||
@@ -249,6 +278,7 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
|
||||
return Err(cannot_edit(item.id));
|
||||
}
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
h.dom.pending_reshaped.set(!counts_kept);
|
||||
if aligned {
|
||||
flush(h)?;
|
||||
}
|
||||
@@ -262,9 +292,13 @@ fn write_path(h: &super::Host, item: Item, subs: Vec<SubPath>) -> std::result::R
|
||||
}
|
||||
|
||||
/// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless
|
||||
/// the path has those points already.
|
||||
/// the path has those points already. Changes that added, removed or replaced points are written
|
||||
/// with `reshaped`, so the path's direct-selected anchors are deselected even when the counts come
|
||||
/// out the same, and the selection the run puts back leaves them out. When the write fails, the
|
||||
/// changes stay waiting.
|
||||
pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) };
|
||||
let reshaped = h.dom.pending_reshaped.replace(false);
|
||||
let same = {
|
||||
let s = h.session.borrow();
|
||||
let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id));
|
||||
@@ -277,7 +311,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
|
||||
}
|
||||
let subpaths: Vec<Value> =
|
||||
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
|
||||
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
|
||||
let mut params = json!({"id": item.id.0, "subpaths": subpaths});
|
||||
if reshaped {
|
||||
params["reshaped"] = json!(true);
|
||||
}
|
||||
let kept = h.dom.reshaping.replace(reshaped.then_some(item));
|
||||
let r = edit_item(h, item, "path.setAnchors", ¶ms);
|
||||
h.dom.reshaping.set(kept);
|
||||
if let Err(e) = r {
|
||||
*h.dom.pending.borrow_mut() = Some((item, subs));
|
||||
h.dom.pending_reshaped.set(reshaped);
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -336,8 +381,8 @@ pub(super) const PATH_LISTS: usize = 4;
|
||||
|
||||
/// The ids of a document's paths, in the order of its page items, or of the paths directly in the
|
||||
/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their
|
||||
/// documents are unchanged, so a loop over a collection builds its list once. A new list of a
|
||||
/// container is charged by the objects it looks at.
|
||||
/// documents are unchanged, so a loop over a collection builds its list once. A new list is
|
||||
/// charged by the objects it looks at.
|
||||
fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
{
|
||||
let mut lists = h.dom.paths.borrow_mut();
|
||||
@@ -357,6 +402,7 @@ fn path_items(h: &super::Host, st: &DocState, container: Option<NodeId>) -> std:
|
||||
}
|
||||
None => {
|
||||
let all = super::page_items(h, st);
|
||||
h.charge_call(all.len() as u64)?;
|
||||
Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect())
|
||||
}
|
||||
};
|
||||
@@ -464,13 +510,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The id in the result of a command that made an object.
|
||||
fn made_id(r: &Data) -> std::result::Result<NodeId, HostError> {
|
||||
let id = match r {
|
||||
Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }),
|
||||
_ => None,
|
||||
};
|
||||
id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
/// The id in the result of a command that made an object, read from the command's own result (not
|
||||
/// the script's copy, whose numbers are exact only up to 2^53).
|
||||
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
|
||||
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
|
||||
}
|
||||
|
||||
/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or
|
||||
@@ -516,7 +559,7 @@ fn make_in(
|
||||
/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path.
|
||||
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
|
||||
make_in(h, doc, container, |h| {
|
||||
let id = made_id(&drawing_normally(h, || command(h, id, params))?)?;
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?)?;
|
||||
if reversed {
|
||||
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
|
||||
}
|
||||
@@ -673,7 +716,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let ap = h.session.borrow().new_art();
|
||||
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
|
||||
};
|
||||
let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?;
|
||||
let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?)?;
|
||||
if unpainted {
|
||||
keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?;
|
||||
}
|
||||
@@ -697,7 +740,7 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let closed = boolean(arg(a, 1), "closed")?;
|
||||
let item = this_path(h, a)?;
|
||||
edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1426,7 +1469,7 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords,
|
||||
/// coordinates (for a point property) or the value itself.
|
||||
fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer {
|
||||
let (item, s, j) = this_point_place(h, a)?;
|
||||
edit_points(h, item, |subs| {
|
||||
edit_points_keeping(h, item, true, |subs| {
|
||||
if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) {
|
||||
f(an);
|
||||
}
|
||||
|
||||
@@ -855,6 +855,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() {
|
||||
assert!(s.active().unwrap().doc.node(a).is_none());
|
||||
}
|
||||
|
||||
/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round.
|
||||
#[test]
|
||||
fn a_path_made_with_a_large_id_keeps_its_id() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);");
|
||||
assert_eq!(out, vec![json!("big")]);
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big"));
|
||||
}
|
||||
|
||||
/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and
|
||||
/// leaves the selection as it was; `null` still clears it.
|
||||
#[test]
|
||||
fn assigning_undefined_to_the_selection_throws() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];");
|
||||
assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}");
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![a]);
|
||||
log(&mut s, "app.activeDocument.selection = null;");
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_class_constructors_construct() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1349,6 +1375,18 @@ fn get_is_file_open_cannot_probe_outside_script_scope() {
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
|
||||
/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a
|
||||
/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`.
|
||||
#[test]
|
||||
fn get_is_file_open_compares_paths_by_the_platform_s_rules() {
|
||||
use crate::script::dom::path_key_on;
|
||||
assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false));
|
||||
assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false));
|
||||
assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false));
|
||||
assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true));
|
||||
assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_dom_values_do_not_reenter_or_exceed_limits() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -1626,12 +1664,15 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost
|
||||
vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\
|
||||
vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\
|
||||
var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\
|
||||
G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);",
|
||||
sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\
|
||||
vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);",
|
||||
);
|
||||
let expected =
|
||||
[json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)];
|
||||
assert_eq!(out[..11], expected);
|
||||
assert_eq!(out[11..], [json!(true), json!(true), json!(true)]);
|
||||
// With the sublayer's path above the group, the layer's own path and both of the group's paths
|
||||
// named `B`, each collection's named lookups give its own topmost path.
|
||||
assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1716,6 +1757,22 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() {
|
||||
assert!(failure(&mut s, src).contains(REFUSED), "{src}");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
}
|
||||
// Caught inside the script, each refusal leaves both collections as they were, and the group,
|
||||
// shown and unlocked itself, is refused for its locked layer.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\
|
||||
var n = [L.pathItems.length, g.pathItems.length];\
|
||||
try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.add(); } catch (e) { m.push(e.message); }\
|
||||
try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\
|
||||
vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);",
|
||||
);
|
||||
let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(refused.len(), 3, "{out:?}");
|
||||
assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}");
|
||||
assert_eq!(out[1], out[2], "the collections are unchanged inside the script");
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked);
|
||||
s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap();
|
||||
s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap();
|
||||
let hidden = format!("{:?}", s.active().unwrap().doc.layers);
|
||||
@@ -1981,7 +2038,7 @@ fn a_compound_paths_path_items_add_makes_the_path_inside_it() {
|
||||
let d = &s.active().unwrap().doc;
|
||||
let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap();
|
||||
assert_eq!(compound.children().unwrap().len(), 2);
|
||||
assert!(undo_steps(&s) > steps);
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -170,6 +170,12 @@ fn removing_a_point_deselects_a_path_with_direct_selected_anchors() {
|
||||
s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||||
log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];");
|
||||
assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1);
|
||||
// Removing a point and adding one in a single write ends with as many points, but the
|
||||
// selected anchor's index now names another point, so the path is deselected.
|
||||
log(&mut s, "var pp = app.activeDocument.pathItems[1].pathPoints; pp[0].remove(); pp.add();");
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3));
|
||||
assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -188,6 +194,14 @@ fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() {
|
||||
let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]);
|
||||
s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap();
|
||||
assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1);
|
||||
// `reshaped` deselects them at the same count; a value that is not a boolean is refused.
|
||||
for bad in [json!(null), json!(1), json!("yes")] {
|
||||
assert!(s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1);
|
||||
s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": true})).unwrap();
|
||||
let sel = &s.active().unwrap().selection;
|
||||
assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}");
|
||||
}
|
||||
|
||||
/// Points are found by their index across subpaths, through changes that wait to be written and
|
||||
@@ -220,6 +234,26 @@ fn points_are_found_across_subpaths_as_their_counts_change() {
|
||||
assert_eq!(counts, vec![1, 3]);
|
||||
}
|
||||
|
||||
/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points
|
||||
/// start: the index is built again only when a change adds or removes points.
|
||||
#[test]
|
||||
fn moving_each_point_keeps_the_index_of_the_subpaths() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
let subs: Vec<Value> =
|
||||
(0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect();
|
||||
s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap();
|
||||
let before = crate::script::dom::index_builds();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([49, 7])]);
|
||||
let built = crate::script::dom::index_builds() - before;
|
||||
assert!(built <= 3, "the index was built {built} times");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_entire_path_replaces_points_and_keeps_closed() {
|
||||
let (mut s, a, _) = doc();
|
||||
|
||||
@@ -779,11 +779,18 @@ fn trace_object(o: &Object, work: &mut Vec<u32>, strings: &mut StringSizes) -> u
|
||||
extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len());
|
||||
}
|
||||
Class::UnitValue(_) => extra = UNIT_VALUE_BYTES,
|
||||
Class::Host(h) => extra = host_handle_bytes(h.handle.len()),
|
||||
_ => {}
|
||||
}
|
||||
OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra
|
||||
}
|
||||
|
||||
/// The bytes an object of a host class keeps for a handle of `numbers` numbers: the handle itself
|
||||
/// and its copy in the realm's map of host objects.
|
||||
pub(crate) fn host_handle_bytes(numbers: usize) -> usize {
|
||||
numbers.saturating_mul(16)
|
||||
}
|
||||
|
||||
fn add_name(name: &XmlName, strings: &mut StringSizes) {
|
||||
strings.add_key(&name.local);
|
||||
name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k));
|
||||
|
||||
@@ -155,7 +155,7 @@ impl Interp {
|
||||
}
|
||||
return Ok(Value::Object(id));
|
||||
}
|
||||
self.reserve_heap(crate::heap::OBJECT_BYTES)?;
|
||||
self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?;
|
||||
let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto));
|
||||
o.extensible = false;
|
||||
let id = self.heap.alloc_object(o);
|
||||
|
||||
+12
-6
@@ -2749,11 +2749,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw
|
||||
`Not found`; and
|
||||
`app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item,
|
||||
a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with
|
||||
nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or
|
||||
a list of at most 10,000, `null` or `[]`; `undefined` (such as a page item looked up past the end of a list)
|
||||
throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or
|
||||
with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other
|
||||
selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path,
|
||||
letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when
|
||||
selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (on Windows,
|
||||
letter case is ignored and `\` matches `/`; on macOS and Linux, `\` is part of a file name) and does not resolve the
|
||||
path it is given. A document counts only when
|
||||
the automation read roots allow its file, and that check can look the document's file up on disk. A path with
|
||||
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application,
|
||||
Document and PageItem pages list, such as `Document.views`, `PageItem.blendingMode`, `PageItem.rotate` and
|
||||
@@ -2825,7 +2826,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
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.
|
||||
The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path
|
||||
The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path (its layer and
|
||||
groups shown and unlocked too, and not on a locked artboard), 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
|
||||
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.
|
||||
@@ -2859,6 +2861,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
`setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the
|
||||
script uses any other member or command, or the points of another path, and when the script ends; a path aligned
|
||||
to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them.
|
||||
Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the
|
||||
path ends with as many points as before; changes that only move points or handles, change a point's type or set
|
||||
`closed` keep them selected.
|
||||
`pathPoints`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and
|
||||
`removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`,
|
||||
@@ -6744,7 +6749,8 @@ and `layerRows`, the rows highlighted in the panel.
|
||||
that is the target, which would put them inside it (#8237). Dragging the
|
||||
selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level
|
||||
form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts
|
||||
a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that
|
||||
a path into a shown, unlocked compound path whose layer and groups are also shown and unlocked and that is not on
|
||||
a locked artboard (see `object.newGroup` for the paint the path keeps or takes). A row that
|
||||
either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the
|
||||
group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and
|
||||
listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join,
|
||||
|
||||
Reference in new issue
Block a user