mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 12:21:08 +01:00
Scripts: remove() keeps an emptied compound path, and note takes numbers
- remove() on the last path of a compound path keeps the compound path, empty, as move() does, so a script that holds it can still read it. edit.clear takes keepEmpty: true for this, and passes it on to path.deleteAnchors when it deletes direct-selected anchors; without it, Clear still deletes a compound path it empties. - note, like name, takes a number or a Boolean as the text String() gives it. - Assigning a graph mark or label the opacity it already has throws Cannot edit in a hidden or locked layer when the graph keeps another opacity for its series or kind, since the assignment would still change the graph. - Only the exact opacity the getter reports counts as the opacity an object already has; a value that differs from it by less than 0.0001 is now applied instead of being dropped. - Reading a document's selection orders only the selected objects, by their place in the tree, so its cost no longer grows with the size of the document. - docs/mcp.md: the opacity exception, note, keepEmpty, and that strict-mode code throws a TypeError when it assigns a member an object lacks. Docs: docs/mcp.md.
This commit is contained in:
1 parent
fe0e408607
commit
112eacbb1c
5 files changed
+268
-96
No files matched your search
@@ -225,7 +225,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Clear",
|
||||
["Edit"],
|
||||
Some("Delete"),
|
||||
"{ids?, guides?: bool (with ids: also delete the selected ruler guides)} 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); 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), 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",
|
||||
has_selection_or_guides,
|
||||
clear
|
||||
),
|
||||
@@ -1221,6 +1221,7 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
|
||||
|
||||
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")?;
|
||||
let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None };
|
||||
// An object of a symbol instance's art can't be removed from the instance alone.
|
||||
if explicit.is_none() && s.doc()?.selection.symbol_part.is_some() {
|
||||
@@ -1252,8 +1253,11 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return ok();
|
||||
}
|
||||
s.edit("Clear", |d, sel| {
|
||||
let parents: Vec<_> =
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect();
|
||||
let parents: Vec<_> = if keep_empty {
|
||||
Vec::new()
|
||||
} else {
|
||||
ids.iter().filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))).collect()
|
||||
};
|
||||
d.remove_many(&ids)?;
|
||||
for p in parents {
|
||||
if d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) {
|
||||
|
||||
@@ -122,7 +122,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Delete Anchor Points",
|
||||
[],
|
||||
None,
|
||||
"{} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)",
|
||||
"{keepEmpty?: bool (keep a compound path left with no members)} delete the direct-selected anchors and their segments, opening closed paths there, and delete objects selected whole alongside them; what remains of a path stays selected, so a second Delete removes it (the Delete key)",
|
||||
has_anchors,
|
||||
delete_anchors
|
||||
),
|
||||
@@ -1654,6 +1654,7 @@ fn convert_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// `guides: true` (Cut, #3226): the selected ruler guides go in the same undo step.
|
||||
let with_guides = switch_or(p, "guides", false, "path.deleteAnchors")?;
|
||||
let keep_empty = switch_or(p, "keepEmpty", false, "path.deleteAnchors")?;
|
||||
let st = s.doc()?;
|
||||
let sel = st.selection.anchors.clone();
|
||||
let segments = st.selection.segments.clone();
|
||||
@@ -1671,12 +1672,16 @@ pub(crate) fn delete_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.copied()
|
||||
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
|
||||
.collect();
|
||||
// The compound paths that hold a deleted object; one left with no members goes too.
|
||||
let compounds: BTreeSet<NodeId> = whole_ids
|
||||
.iter()
|
||||
.chain(sel.keys())
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect();
|
||||
// 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()
|
||||
} else {
|
||||
whole_ids
|
||||
.iter()
|
||||
.chain(sel.keys())
|
||||
.filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))))
|
||||
.collect()
|
||||
};
|
||||
if !whole_ids.is_empty() {
|
||||
d.remove_many(&whole_ids)?;
|
||||
}
|
||||
|
||||
@@ -43,9 +43,14 @@
|
||||
//! must be one of that document's that can be selected, or nothing changes.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
//! object in a hidden or locked layer throws `Cannot edit` and changes nothing; its `name` and
|
||||
//! `note` still change. An object that is hidden or locked itself, or is in a hidden or locked
|
||||
//! group, takes them.
|
||||
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
|
||||
//! nothing, even for the value the object has. The exception is `opacity` given the value the
|
||||
//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps
|
||||
//! another opacity it would still change the graph, so it is refused too. Its `name` and `note`
|
||||
//! still change. An object that is hidden or locked itself, or is in a hidden or locked group,
|
||||
//! takes them.
|
||||
//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives.
|
||||
//! - A compound path whose last path `move` or `remove()` takes out stays, empty.
|
||||
//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out,
|
||||
//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing.
|
||||
|
||||
@@ -1263,21 +1268,28 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
if picked.len() > MAX_LISTED {
|
||||
return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects")));
|
||||
}
|
||||
let ids: Vec<NodeId> = if picked.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
let all = page_items(h, st);
|
||||
h.charge_call(all.len() as u64)?;
|
||||
let mut ids: Vec<NodeId> = all.iter().copied().filter(|i| picked.contains(i)).collect();
|
||||
// A selected object that `pageItems` does not list still comes last, in the order it was
|
||||
// selected.
|
||||
if ids.len() < picked.len() {
|
||||
let mut listed: HashSet<NodeId> = ids.iter().copied().collect();
|
||||
ids.extend(st.selection.objects.iter().copied().filter(|i| picked.contains(i) && listed.insert(*i)));
|
||||
// Only the selected objects are ordered, by their place in the tree, so the cost follows the
|
||||
// size of the selection and not of the document. `pageItems` walks each list of children
|
||||
// topmost first and puts a group before the objects in it: a higher index comes first, and an
|
||||
// ancestor's path, a prefix of its descendants' paths, sorts before them.
|
||||
let mut placed: Vec<(Vec<std::cmp::Reverse<usize>>, NodeId)> = Vec::with_capacity(picked.len());
|
||||
let mut unplaced: Vec<NodeId> = Vec::new();
|
||||
let mut seen: HashSet<NodeId> = HashSet::with_capacity(picked.len());
|
||||
let mut steps = 0u64;
|
||||
for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) {
|
||||
match st.doc.index_path(id) {
|
||||
Some(path) => {
|
||||
steps += path.len() as u64;
|
||||
placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id));
|
||||
}
|
||||
// A selected object outside the tree's walk still comes last, in the order it was
|
||||
// selected.
|
||||
None => unplaced.push(id),
|
||||
}
|
||||
ids
|
||||
};
|
||||
h.charge_call(16 * ids.len() as u64)?;
|
||||
}
|
||||
placed.sort();
|
||||
let ids: Vec<NodeId> = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect();
|
||||
h.charge_call(steps + 16 * ids.len() as u64)?;
|
||||
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
|
||||
}
|
||||
|
||||
@@ -1482,15 +1494,20 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) ->
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the
|
||||
/// text `String(value)` gives, and any other value that is not a string is refused.
|
||||
fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
|
||||
match v {
|
||||
Data::String(s) => Ok(s.clone()),
|
||||
Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)),
|
||||
Data::Bool(b) => Ok(b.to_string()),
|
||||
_ => Err(HostError::Type(format!("{what} must be a string"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let name = match arg(a, 1) {
|
||||
Data::String(s) => s.clone(),
|
||||
Data::Number(n) => vectorcraft_js::number_to_string(*n),
|
||||
Data::Bool(b) => b.to_string(),
|
||||
_ => return Err(HostError::Type("name must be a string".into())),
|
||||
};
|
||||
let name = &name;
|
||||
let name = &text_arg(arg(a, 1), "name")?;
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
@@ -1505,9 +1522,10 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| Ok(text(note_of(n))))
|
||||
}
|
||||
|
||||
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it.
|
||||
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
|
||||
/// or a Boolean becomes the text `String(value)` gives.
|
||||
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) };
|
||||
let note = &text_arg(arg(a, 1), "note")?;
|
||||
if note.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the note is too long".into()));
|
||||
}
|
||||
@@ -1565,14 +1583,21 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
// A value the getter reports for the item's opacity sends the opacity it has, and
|
||||
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let item = this_item(h, a)?;
|
||||
let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0));
|
||||
let Some(v) = now.filter(|now| (now - v).abs() < 1e-4) else {
|
||||
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 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)
|
||||
});
|
||||
if now.is_none() || keeps_other {
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
return set_props(h, a, |_| false, json!({"opacity": v}));
|
||||
};
|
||||
set_props(h, a, |_| false, json!({"opacity": v}))
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
|
||||
fn item_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1731,7 +1756,7 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
|
||||
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
|
||||
/// refuses it.
|
||||
/// refuses it. A compound path whose last path this is stays, empty.
|
||||
fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -1743,7 +1768,8 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?;
|
||||
// A compound path whose last path this is stays, empty, as it does after `move`.
|
||||
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
|
||||
@@ -242,6 +242,20 @@ fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() {
|
||||
s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap();
|
||||
assert_eq!(kept(&s), Some(0.5));
|
||||
s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap();
|
||||
// In a hidden or locked layer the same assignment would still change the graph, so it is refused.
|
||||
let layer = s.active().unwrap().doc.layers[0].id;
|
||||
for (on, off) in [
|
||||
(json!({"ids": [layer.0], "visible": false}), json!({"ids": [layer.0], "visible": true})),
|
||||
(json!({"ids": [layer.0], "locked": true}), json!({"ids": [layer.0], "locked": false})),
|
||||
] {
|
||||
s.execute("object.setProps", &on).unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "var m = app.activeDocument.pageItems.getByName('mark'); m.opacity = m.opacity;");
|
||||
assert!(e.contains("Cannot edit"), "{on}: {e}");
|
||||
assert_eq!(kept(&s), Some(0.5), "{on}");
|
||||
assert_eq!(undo_steps(&s), steps, "{on}");
|
||||
s.execute("object.setProps", &off).unwrap();
|
||||
}
|
||||
log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;");
|
||||
assert_eq!(kept(&s), None);
|
||||
}
|
||||
@@ -256,6 +270,12 @@ fn assigning_the_reported_opacity_changes_nothing() {
|
||||
assert_eq!(out, vec![json!(33.3333)]);
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
// A value close to the reported one but not equal to it is still applied.
|
||||
s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
|
||||
log(&mut s, "app.activeDocument.pageItems[1].opacity = 50.00005;");
|
||||
assert!(s.active().unwrap().doc.node(a).unwrap().opacity > before, "the assigned opacity was applied");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -524,6 +544,54 @@ fn moving_the_last_path_out_of_a_compound_path_keeps_the_compound_path() {
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
}
|
||||
|
||||
/// `remove()` on the last path of a compound path keeps the compound path, empty, as `move` does,
|
||||
/// and a document holding it saves, reopens, exports and releases it.
|
||||
#[test]
|
||||
fn removing_the_last_path_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 d = app.activeDocument, c = d.pageItems[0]; d.pageItems[2].remove(); d.pageItems[1].remove();\
|
||||
vc.log([c.typename, d.pageItems.length, c === d.pageItems[0]]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["CompoundPathItem", 1, true])]);
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
assert!(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, "the run is one undo step");
|
||||
assert!(s.execute("edit.clear", &json!({"ids": [compound.0], "keepEmpty": 1})).is_err(), "keepEmpty must be a boolean");
|
||||
// The native format keeps it, and the other writers and Release Compound Path accept it.
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap();
|
||||
assert!(back.node(compound).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }) && n.children().is_some_and(|c| c.is_empty())));
|
||||
for format in ["svg", "pdf", "vectorcraft"] {
|
||||
s.execute("document.export", &json!({"format": format})).unwrap_or_else(|e| panic!("{format}: {e}"));
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
|
||||
s.execute("object.compoundPath.release", &json!({})).unwrap();
|
||||
}
|
||||
|
||||
/// Clear with `keepEmpty` keeps the emptied compound path also when it deletes direct-selected
|
||||
/// anchors, and without it deletes the compound path as before.
|
||||
#[test]
|
||||
fn clearing_anchors_with_keep_empty_keeps_the_compound_path() {
|
||||
for keep in [true, false] {
|
||||
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];
|
||||
for (id, mode) in [(a, "set"), (b, "add")] {
|
||||
s.execute("select.anchors", &json!({"id": id.0, "anchors": [[0, 0], [0, 1], [0, 2]], "mode": mode})).unwrap();
|
||||
}
|
||||
s.execute("edit.clear", &json!({"keepEmpty": keep})).unwrap();
|
||||
let d = &s.active().unwrap().doc;
|
||||
assert!(d.node(a).is_none() && d.node(b).is_none(), "keepEmpty {keep}: both paths are deleted");
|
||||
assert_eq!(d.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), keep, "keepEmpty {keep}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_of_an_object_with_a_large_id_is_the_copy() {
|
||||
let mut s = Session::new();
|
||||
@@ -921,7 +989,12 @@ fn note_is_the_attributes_note() {
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
log(&mut s, "app.activeDocument.pageItems[1].note = 'check bleed';");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the same note adds no step");
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = 5;").contains("note must be a string"));
|
||||
// A number or a Boolean becomes its text, as it does for `name`.
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[1]; i.note = 5; vc.log([typeof i.note, i.note]); i.note = true; vc.log(i.note);");
|
||||
assert_eq!(out, vec![json!(["string", "5"]), json!("true")]);
|
||||
for value in ["null", "undefined", "{}"] {
|
||||
assert!(failure(&mut s, &format!("app.activeDocument.pageItems[0].note = {value};")).contains("note must be a string"), "{value}");
|
||||
}
|
||||
assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long"));
|
||||
}
|
||||
|
||||
@@ -1332,24 +1405,20 @@ fn unsupported_members_say_so() {
|
||||
assert!(failure(&mut s, "app.activeDocument.layers;").contains("Document.layers is not available yet"));
|
||||
}
|
||||
|
||||
/// A script that lowers each selected object's opacity by 10 points, checking each member with
|
||||
/// `hasOwnProperty` and the selection's `length` first, as scripts written for the object model do.
|
||||
const LOWER_OPACITY: &str = "\
|
||||
var doc = app.activeDocument;\
|
||||
var sel = doc.selection;\
|
||||
if (sel.length === 0) { alert('Nothing selected.'); }\
|
||||
else {\
|
||||
var done = 0;\
|
||||
for (var i = 0; i < sel.length; i++) {\
|
||||
var item = sel[i];\
|
||||
if (item.hasOwnProperty('opacity') && typeof item.opacity === 'number') {\
|
||||
item.opacity = Math.max(0, item.opacity - 10);\
|
||||
done++;\
|
||||
}\
|
||||
if (item.hasOwnProperty('blendingMode')) { item.blendingMode; }\
|
||||
}\
|
||||
if (done === 0) { alert('No object with an opacity.'); }\
|
||||
}";
|
||||
/// A script that names each visible selected object after its place in `app.selection`, testing
|
||||
/// the members it uses with `hasOwnProperty` and `propertyIsEnumerable` first. A member that is not
|
||||
/// available yet, such as `blendingMode`, is read only when `hasOwnProperty` reports it, so it is
|
||||
/// never read.
|
||||
const NAME_PICKED: &str = "\
|
||||
var picked = app.selection, k = picked.length, named = 0;\
|
||||
if (!k) alert('Select something first.');\
|
||||
while (k--) {\
|
||||
var obj = picked[k];\
|
||||
var usable = obj.propertyIsEnumerable('name') && obj.hasOwnProperty('hidden') && !obj.hidden;\
|
||||
if (obj.hasOwnProperty('blendingMode') && obj.blendingMode) usable = false;\
|
||||
if (usable) { obj.name = 'picked ' + k; named += 1; }\
|
||||
}\
|
||||
if (picked.length && named < picked.length) alert('Some objects were skipped.');";
|
||||
|
||||
#[test]
|
||||
fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object() {
|
||||
@@ -1364,20 +1433,40 @@ fn a_script_that_checks_has_own_property_changes_every_kind_of_selected_object()
|
||||
s.execute("select.set", &json!({"ids": [c1.0, c2.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.active().unwrap().selection.objects[0];
|
||||
s.execute("object.setProps", &json!({"ids": [group.0], "opacity": 55})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [text.0], "opacity": 5})).unwrap();
|
||||
let objects = [path, group, text, compound];
|
||||
s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::<Vec<_>>()})).unwrap();
|
||||
let opacities = |s: &Session| -> Vec<f64> {
|
||||
let names = |s: &Session| -> Vec<Option<String>> {
|
||||
let d = &s.active().unwrap().doc;
|
||||
objects.iter().map(|n| (f64::from(d.node(*n).unwrap().opacity) * 1000.0).round() / 10.0).collect()
|
||||
objects.iter().map(|n| d.node(*n).unwrap().name.clone()).collect()
|
||||
};
|
||||
let before = names(&s);
|
||||
let steps = undo_steps(&s);
|
||||
// The run shows no alert: without an answer for one, it would stop there.
|
||||
let r = run(&mut s, NAME_PICKED).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(r["dialogs"], json!([]), "{r}");
|
||||
let after = names(&s);
|
||||
assert!(after.iter().all(|n| n.as_deref().is_some_and(|n| n.starts_with("picked "))), "every kind was named: {after:?}");
|
||||
assert_eq!(after.iter().collect::<std::collections::HashSet<_>>().len(), objects.len(), "each got its own name: {after:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(names(&s), before);
|
||||
// Opacity reads and writes on every kind too: each object goes to its own value, read back from the script.
|
||||
s.execute("select.set", &json!({"ids": objects.iter().map(|n| n.0).collect::<Vec<_>>()})).unwrap();
|
||||
let opacities = |s: &Session| -> Vec<f32> {
|
||||
let d = &s.active().unwrap().doc;
|
||||
objects.iter().map(|n| d.node(*n).unwrap().opacity).collect()
|
||||
};
|
||||
let before = opacities(&s);
|
||||
let steps = undo_steps(&s);
|
||||
// The run shows no alert: without an answer for one, it would stop there.
|
||||
let r = run(&mut s, LOWER_OPACITY).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert_eq!(r["dialogs"], json!([]), "{r}");
|
||||
assert_eq!(opacities(&s), vec![90.0, 45.0, 0.0, 90.0]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var sel = app.activeDocument.selection, read = [];\
|
||||
for (var i = 0; i < sel.length; i++) { sel[i].opacity = 20 + 10 * i; read.push(sel[i].opacity); }\
|
||||
vc.log(read);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([20, 30, 40, 50])]);
|
||||
let after = opacities(&s);
|
||||
assert!(after.iter().zip(&before).all(|(a, b)| a < b), "every kind got a lower opacity: {before:?} -> {after:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(opacities(&s), before);
|
||||
@@ -1390,8 +1479,8 @@ fn the_selection_is_an_empty_list_when_nothing_is_selected() {
|
||||
let out = log(&mut s, "var d = app.activeDocument; vc.log([d.selection instanceof Array, d.selection.length, app.selection.length]);");
|
||||
assert_eq!(out, vec![json!([true, 0, 0])]);
|
||||
let steps = undo_steps(&s);
|
||||
let r = s.execute("script.run", &json!({"source": LOWER_OPACITY, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap();
|
||||
assert_eq!(r["dialogs"][0]["message"], json!("Nothing selected."), "{r}");
|
||||
let r = s.execute("script.run", &json!({"source": NAME_PICKED, "name": "t.js", "answers": [{"kind": "alert", "value": "ok"}]})).unwrap();
|
||||
assert_eq!(r["dialogs"][0]["message"], json!("Select something first."), "{r}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
@@ -1484,6 +1573,41 @@ fn page_items_and_the_selection_list_the_topmost_object_first() {
|
||||
assert_eq!(out, vec![json!(["top", "last", "last"])]);
|
||||
}
|
||||
|
||||
/// The selection lists a group before the objects in it, in `pageItems`' order, and reading it
|
||||
/// costs as much in a large document as in a small one.
|
||||
#[test]
|
||||
fn the_selection_follows_page_items_and_costs_the_same_in_a_large_document() {
|
||||
let (mut s, a, b) = doc();
|
||||
let c = rect(&mut s, 200.0, 200.0, 20.0, 20.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let group = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, c.0, group]})).unwrap();
|
||||
let source = "var d = app.activeDocument, want = [], got = [];\
|
||||
for (var i = 0; i < d.pageItems.length; i++) if (d.pageItems[i].selected) want.push(d.pageItems[i].typename + i);\
|
||||
for (var i = 0; i < d.pageItems.length; i++) for (var j = 0; j < d.selection.length; j++)\
|
||||
if (d.selection[j] === d.pageItems[i]) got[j] = d.pageItems[i].typename + i;\
|
||||
vc.log([want, got]);";
|
||||
let out = log(&mut s, source);
|
||||
assert_eq!(out[0][0], out[0][1], "the selection is in pageItems' order");
|
||||
assert_eq!(out[0][0].as_array().map(Vec::len), Some(3));
|
||||
// Each pass edits the document, so nothing kept from the last read can be reused.
|
||||
let edits = "var d = app.activeDocument; for (var i = 0; i < 50; i++) d.selection[0].opacity = 50 + i % 2;";
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
let small = run(&mut s, edits).unwrap()["fuelUsed"].as_u64().unwrap();
|
||||
// 3 objects doubled 11 times: 6,144.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
for _ in 0..11 {
|
||||
s.execute("edit.duplicate", &json!({})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
}
|
||||
s.execute("select.set", &json!({"ids": [c.0]})).unwrap();
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
|
||||
let large = run(&mut s, edits);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let large = large.unwrap_or_else(|e| panic!("the reads in a large document went over: {e}"))["fuelUsed"].as_u64().unwrap();
|
||||
assert_eq!(small, large);
|
||||
}
|
||||
|
||||
/// A collection read with a name gives what `getByName` gives, and throws as it does for no match.
|
||||
#[test]
|
||||
fn a_collection_read_with_a_name_gives_the_named_object() {
|
||||
@@ -1632,6 +1756,11 @@ fn assigning_a_name_a_collection_lacks_throws() {
|
||||
}
|
||||
let out = log(&mut s, "var p = app.activeDocument.pageItems; p[0] = 3; vc.log(typeof p[0]);");
|
||||
assert_eq!(out, vec![json!("object")]);
|
||||
// On a page item the value is not kept; strict-mode code throws instead.
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; i.qux = 4; vc.log(typeof i.qux);");
|
||||
assert_eq!(out, vec![json!("undefined")]);
|
||||
let e = failure(&mut s, "'use strict'; app.activeDocument.pageItems[0].qux = 4;");
|
||||
assert!(e.contains("TypeError") && e.contains("qux"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
|
||||
+31
-23
@@ -2671,29 +2671,33 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an
|
||||
object, with or without a relative object, throws `Cannot duplicate` and makes no copy. Assigning `hidden`,
|
||||
`locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an object in a hidden or locked layer
|
||||
throws `Cannot edit` and changes nothing, even when the value is the one the object has, except for `opacity`, and
|
||||
`zOrder()` on such an object throws `Cannot edit` too. Its `name` and `note` still change, and an object that is
|
||||
hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself as the relative object and
|
||||
`PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move` takes the last path out of
|
||||
a compound path, the compound path stays, empty, so a script that holds it can still read it. An object with
|
||||
nothing in it, such as an empty group or that compound path, reads its bounds, `position`, `width` and `height`
|
||||
as zeros, and assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws
|
||||
throws `Cannot edit` and changes nothing, even when the value is the one the object has, and `zOrder()` on such
|
||||
an object throws `Cannot edit` too. The one exception is `opacity` given the value the object already has, which
|
||||
changes nothing and does not throw; on a graph's mark or label whose series or kind keeps another opacity, that
|
||||
value would still change the graph, so it throws `Cannot edit` as well. Its `name` and `note` still change, and an
|
||||
object that is hidden or locked itself takes all of them (VectorCraft's own rule). `move` with the object itself
|
||||
as the relative object and `PLACEBEFORE` or `PLACEAFTER` leaves it where it is and adds no undo step. When `move`
|
||||
or `remove()` takes the last path out of a compound path, the compound path stays, empty, so a script that holds
|
||||
it can still read it (`remove()` runs `edit.clear` with `keepEmpty: true`). An object with nothing in it, such
|
||||
as an empty group or that compound path, reads its bounds, `position`, `width` and `height` as zeros, and
|
||||
assigning them does nothing (VectorCraft's own rule). `duplicate` on a path inside a compound path throws
|
||||
`Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws
|
||||
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the
|
||||
same object when the image is embedded: the next read gives that object, now a `RasterItem`. The
|
||||
enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
|
||||
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that
|
||||
holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a
|
||||
`RasterItem`. The enumerations `ElementPlacement`, `ZOrderMethod`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
|
||||
`DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
|
||||
`DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
`pageItems` lists the art topmost first, as the example on
|
||||
[CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`,
|
||||
and a document's `selection` lists the selected objects in the same order, whatever order they were selected or
|
||||
made in. This is VectorCraft's own rule: the page cited below says the first object in a selection is the one last
|
||||
added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as `pageItems["Logo"]` or
|
||||
`documents["Untitled-1"]`, gives the object `getByName` gives, as
|
||||
added to the page, and VectorCraft does not follow that sentence. A collection read with a name, such as
|
||||
`pageItems["Logo"]` or `documents["Untitled-1"]`, gives the object `getByName` gives, as
|
||||
[Accessing and referencing objects](https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/)
|
||||
shows. A read with a name that nothing has, a name the collection class lacks as a member included, throws
|
||||
`Not found`; `"name" in pageItems` is false then, and assigning to such a name throws `Not found` too
|
||||
(VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` takes a number or a Boolean as the text `String(value)` gives. `String(object)` gives
|
||||
(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).
|
||||
Documents are listed in tab order; the same page says `documents[0]` is always the active document, and
|
||||
@@ -2706,11 +2710,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each
|
||||
changed document. A value that changes nothing runs no command, and a change to another document leaves the active
|
||||
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, or that a named engine
|
||||
kept from an earlier run, throws `Stale page item`. `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` and delete nothing. Setting `width` or `height` scales the object along
|
||||
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
|
||||
deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `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`
|
||||
and delete nothing. Setting `width` or `height` scales the object along
|
||||
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,
|
||||
@@ -2725,9 +2730,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
|
||||
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
|
||||
other properties but not the methods. `Object.keys`, `Object.getOwnPropertyNames` and
|
||||
`Object.getOwnPropertyDescriptor` do not report those members. Assigning a member that a page item, a layer, a
|
||||
document or the application does not have does not keep the value and does not throw; on a collection it throws `Not found`,
|
||||
as described above. Other members
|
||||
`Object.getOwnPropertyDescriptor` do not report any member of the class. Assigning a member that a page item, a
|
||||
layer, a document or the application does not have does not keep the value; it does not throw, except in
|
||||
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, as described above. Other members
|
||||
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
|
||||
themselves, such as a path's fill, are not defined yet and read as `undefined`.
|
||||
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
|
||||
@@ -3381,7 +3386,8 @@ or unknown id leaves the document unchanged. An empty `ids` array does nothing.
|
||||
are kept, and selecting an ancestor together with its descendants deletes that subtree once.
|
||||
Without `ids`, direct-selected anchors or selected ruler guides retain their usual Clear behavior.
|
||||
With `ids`, `guides: true` also deletes the selected ruler guides. The command rejects a `guides` value that is not a
|
||||
boolean.
|
||||
boolean. 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 is rejected.
|
||||
|
||||
`edit.copy` takes a compound-path member selected on its own (whole or in part, with Direct or Group Selection) as an
|
||||
ordinary path with the compound's paint, transparency, opacity mask and fill rule. The path is linked to the compound's
|
||||
@@ -6992,7 +6998,9 @@ their facing handles are refitted so one cubic follows the two old segments; two
|
||||
The anchor after each removed one is then selected (the one before at an open path's end), so running
|
||||
`path.removeAnchors` again goes on along the path.
|
||||
`path.removeAnchor {id, subpath?, anchor}` (the Delete Anchor Point tool) removes one anchor the same way, and
|
||||
`path.deleteAnchors {}` (the Delete key) deletes the selected anchors with their segments, opening closed paths there.
|
||||
`path.deleteAnchors {keepEmpty?}` (the Delete key) deletes the selected anchors with their segments, opening closed paths
|
||||
there. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given; `edit.clear` passes its
|
||||
`keepEmpty` on when it deletes direct-selected anchors.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"select.anchors","params":{"id":12,"anchors":[[0,1],[0,3]]}}}
|
||||
|
||||
Reference in new issue
Block a user