Files
vectorcraft/crates/engine/src/script/dom/paths.rs
T
dotCooCoo a4b2e4fe36 Scripts: remove the unused empty-path closed set
Setting `closed` on a path with no points gives it an empty closed
subpath, so the path's own data keeps the setting. The separate set of
empty paths, its key, its cleanup after commands and its copy in the
command trail were no longer written to by anything. `closed` and
`setEntirePath` now read the closed state from the subpaths only.
2026-12-04 16:52:48 -08:00

2449 lines
116 KiB
Rust

//! Paths and their points in the script object model, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/> describe them.
//!
//! A `PathPoints` object holds its path's handle, and a `PathPoint` the path's handle and the
//! point's index, counted across the path's subpaths in order. Each read looks the path up again.
//! Every change runs one command inside the run's one undo step, and a change that changes nothing
//! runs no command. Changes to the points of one path wait in the run's [`super::State`] and are
//! written together with one `path.setAnchors` ([`flush`]) before any other member, command or
//! path's points are read or changed, and when the script ends.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside
//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in
//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden
//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`].
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a
//! range error when it is assigned.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
//! the recent colors as they were. `fillOverprint` and `strokeOverprint` read and change the top
//! fill or stroke only.
//! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes
//! them all.
//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's
//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or
//! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds
//! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points.
//! Removing the last points leaves the path, with no points.
//! - A point whose index is past the end of its path throws `Stale path point`, and so does a
//! point read before the run removed a point of its path or replaced its points
//! (`PathPoint.remove()`, `PathPoints.removeAll()`, `setEntirePath`), or before anything other
//! than the object model changed the path's points (a command run with `vc.run`, such as
//! `path.setAnchors`, `object.move` or `edit.undo`). Points stay valid through the object
//! model's other changes to the path or to an object that holds it, such as `translate()`.
//! - Shape creators take sizes and radii that are finite and not negative; `sides` is a whole
//! number from 3 to 1000 and `points` one from 2 to 1000. `inscribed` true throws an error that
//! says it is not available yet. `rotateAbout` and `scaleAbout` default to
//! `Transformation.CENTER`. A transform that leaves the path where it is (`rotate(360)`,
//! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too.
//! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole
//! as a selected anchor point, and not the endpoints of selected segments; a path in a selected
//! group or compound path is selected as a whole. Direction handles are not selected on their
//! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they
//! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or
//! compound path. Selecting a point of a path with selected segments replaces that path's
//! segment selection. Selecting a point of a guide while guides are locked throws an error. A
//! clipping path cannot be made a guide. Assigning `guides` a value the path does not have
//! throws an error that says it is not available yet on a path inside a compound path, throws
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
//! are locked; assigning the value the path has runs no command.
//! - The transforms are `PageItem`'s, with their rules in [`super::transform`].
use std::rc::Rc;
use std::sync::Arc;
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::pattern::pattern_paint;
use vectorcraft_doc::{GraphicStyle, LineCap, LineJoin};
use vectorcraft_geom::path::{Anchor, AnchorKind, FillRule, PathData, SubPath};
use vectorcraft_geom::{Point, Rect};
use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref};
use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, class_text, colors, command,
coordinate, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair,
point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
/// The error of a point whose index is past the end of its path, or that was read before the run
/// removed or replaced points of its path.
pub const STALE_POINT: &str = "Stale path point";
/// The most points `setEntirePath` takes.
pub const MAX_POINTS: usize = 100_000;
/// The most lengths `strokeDashes` takes.
pub const MAX_DASHES: usize = 64;
/// The largest stroke weight a script may set, in points.
pub const MAX_STROKE_WIDTH: f64 = 1000.0;
/// The enumerations of paths, as frozen objects whose members are `"Name.MEMBER"` strings.
pub(super) const ENUMS: &[(&str, &[&str])] = &[
("PointType", &["CORNER", "SMOOTH"]),
("PathPointSelection", &["ANCHORPOINT", "LEFTDIRECTION", "LEFTRIGHTPOINT", "NOSELECTION", "RIGHTDIRECTION"]),
("StrokeCap", &["BUTTENDCAP", "PROJECTINGENDCAP", "ROUNDENDCAP"]),
("StrokeJoin", &["BEVELENDJOIN", "MITERENDJOIN", "ROUNDENDJOIN"]),
("PolarityValues", &["NEGATIVE", "POSITIVE"]),
("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]),
];
/// Adds the enumerations of [`ENUMS`] to `realm`.
pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunError> {
for (name, members) in ENUMS {
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(Data::String(format!("{name}.{m}"))))).collect();
realm.define_host_object(name, items)?;
}
Ok(())
}
fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is
/// hidden or locked, or it is on a locked artboard.
fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option<HostError> {
if !editable(&st.doc, id) {
Some(cannot_edit(id))
} else if super::on_locked_artboard(h, st, id) {
Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)))
} else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) {
Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)))
} else {
None
}
}
/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin.
fn in_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
}
/// The path `d` names, which must still be in its document.
fn path_of(h: &super::Host, d: &Data) -> std::result::Result<Item, HostError> {
let item = item_of(h, d)?;
let is_path = with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })));
if is_path { Ok(item) } else { Err(HostError::Type("this is not a PathItem".into())) }
}
fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
path_of(h, arg(a, 0))
}
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
return Err(HostError::Error(STALE_ITEM.into()));
}
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
path_of(h, &path_ref(h, Item { doc, id }))
}
/// Reads the path of `item` with `f`.
fn read_path<T>(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::doc::Node, &PathData) -> T) -> std::result::Result<T, HostError> {
with_doc(h, item.doc, |_, st| match st.doc.node(item.id) {
Some(n) => match n.path_data() {
Some(pd) => Ok(f(st, n, pd)),
None => Err(HostError::Type("this is not a PathItem".into())),
},
None => Err(HostError::Error(STALE_ITEM.into())),
})
}
/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count).
fn path_ref(h: &super::Host, item: Item) -> Data {
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
host_ref("PathItem", &handle)
}
#[cfg(test)]
thread_local! {
/// How many times [`point_starts`] counted the points of a path on this thread.
static INDEX_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// The index of the first point of each subpath of `subs`, followed by the number of points.
fn starts(subs: &[SubPath]) -> Vec<usize> {
#[cfg(test)]
crate::script::LAYOUTS_BUILT.with(|n| n.set(n.get() + 1));
let mut out = Vec::with_capacity(subs.len() + 1);
let mut n = 0;
for sp in subs {
out.push(n);
n += sp.anchors.len();
}
out.push(n);
out
}
/// The subpath and the place in it of point `i`, given the [`starts`] of a path's subpaths.
fn locate_at(starts: &[usize], i: usize) -> Option<(usize, usize)> {
if i >= *starts.last()? {
return None;
}
let s = starts.partition_point(|first| *first <= i).checked_sub(1)?;
Some((s, i - starts.get(s)?))
}
/// What the [`starts`] that [`super::State`] keeps were counted from: a path's node as its document
/// holds it, by document uid, or the waiting point changes of a path ([`edit_points`]).
pub(super) enum Counted {
Node(u64, Arc<crate::doc::Node>),
Waiting(Item),
}
/// The [`starts`] of the path of `item`, its waiting point changes included. They are kept while
/// the path's node is the same one, or until the waiting changes add or remove points.
fn point_starts(h: &super::Host, item: Item) -> std::result::Result<Rc<Vec<usize>>, HostError> {
let waiting = matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item));
if waiting {
if let Some((Counted::Waiting(k), kept)) = &*h.dom.point_starts.borrow()
&& same_path(*k, item)
{
return Ok(kept.clone());
}
#[cfg(test)]
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
let counted = Rc::new(read_points(h, item, starts)?);
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted.clone()));
return Ok(counted);
}
let node = with_doc(h, item.doc, |_, st| node_arc(&st.doc, item.id).cloned()).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if let Some((Counted::Node(uid, kept_node), kept)) = &*h.dom.point_starts.borrow()
&& *uid == item.doc.uid
&& Arc::ptr_eq(kept_node, &node)
{
return Ok(kept.clone());
}
#[cfg(test)]
INDEX_BUILDS.with(|n| n.set(n.get() + 1));
let counted = Rc::new(starts(&node.path_data().ok_or_else(|| HostError::Type("this is not a PathItem".into()))?.subpaths));
*h.dom.point_starts.borrow_mut() = Some((Counted::Node(item.doc.uid, node), counted.clone()));
Ok(counted)
}
/// How many points the path of `item` has, its waiting point changes included ([`point_starts`]).
fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostError> {
Ok(point_starts(h, item)?.last().copied().unwrap_or(0))
}
/// How many times [`point_starts`] counted the points of a path on this thread.
#[cfg(test)]
pub(crate) fn index_builds() -> u64 {
INDEX_BUILDS.with(std::cell::Cell::get)
}
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
for (s, sp) in subs.iter().enumerate() {
#[cfg(test)]
tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1));
if i < sp.anchors.len() {
return Some((s, i));
}
i -= sp.anchors.len();
}
None
}
fn anchor_json(a: &Anchor) -> Value {
json!({"x": a.p.x, "y": a.p.y, "in": [a.h_in.x, a.h_in.y], "out": [a.h_out.x, a.h_out.y], "smooth": a.kind == AnchorKind::Smooth})
}
fn same_path(a: Item, b: Item) -> bool {
a.doc.uid == b.doc.uid && a.id == b.id
}
/// Reads the subpaths of the path of `item` with `f`, its waiting point changes included.
fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result<T, HostError> {
if let Some((waiting, subs)) = &*h.dom.pending.borrow()
&& same_path(*waiting, item)
{
return Ok(f(subs));
}
read_path(h, item, |_, _, pd| f(&pd.subpaths))
}
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked or is on a locked artboard ([`protected`]), 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> {
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 the [`starts`] of the waiting changes stay kept.
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 !counts_kept {
forget_waiting_starts(h);
}
if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut()
&& same_path(*waiting, item)
{
return Ok(f(subs));
}
flush(h)?;
let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?;
let r = f(&mut subs);
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
let same = pd.subpaths == subs;
(same, if same { None } else { protected(h, st, item.id) }, aligned)
})?;
if !same {
if let Some(e) = refused {
return Err(e);
}
*h.dom.pending.borrow_mut() = Some((item, subs));
if aligned {
flush(h)?;
}
}
Ok(r)
}
/// Drops the [`starts`] that [`super::State`] keeps of waiting point changes, which a change can
/// make wrong.
fn forget_waiting_starts(h: &super::Host) {
let mut kept = h.dom.point_starts.borrow_mut();
if matches!(&*kept, Some((Counted::Waiting(_), _))) {
*kept = None;
}
}
/// Changes the anchor at index `i` of the path of `item` with `f` ([`edit_points`]). The change
/// adds and removes no points, so the [`starts`] of the path stay kept.
fn edit_anchor(h: &super::Host, item: Item, i: usize, f: impl FnOnce(&mut Anchor)) -> std::result::Result<(), HostError> {
let counted = point_starts(h, item)?;
let at = locate_at(&counted, i);
edit_points_keeping(h, item, true, |subs| {
if let Some((s, j)) = at
&& let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j))
{
f(an);
}
})?;
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted));
}
Ok(())
}
/// Gives the path of `item` the subpaths `subs` ([`edit_points`]).
fn write_path(h: &super::Host, item: Item, subs: Vec<SubPath>) -> std::result::Result<(), HostError> {
edit_points(h, item, |s| *s = subs)
}
/// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless
/// the path has those points already.
pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) };
forget_waiting_starts(h);
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));
node.and_then(|n| n.path_data()).map(|pd| pd.subpaths == subs)
};
match same {
Some(true) => return Ok(()),
Some(false) => {}
None => return Err(HostError::Error(STALE_ITEM.into())),
}
let subpaths: Vec<Value> =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
super::atomically(h, |h| {
// The anchors and segments the new points no longer have leave the selection before the
// points are written. The undo step of the edit keeps the selection from before that, so
// undoing it selects them again.
let mut kept = None;
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
kept = Some(st.selection.clone());
let selection = &mut st.selection;
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
}
if let Some(segments) = selection.segments.get_mut(&item.id) {
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
if segments.is_empty() {
selection.segments.remove(&item.id);
}
}
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
selection.key_anchor = None;
}
if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id))
&& (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()))
{
selection.remove(item.id);
}
if kept.as_ref().is_some_and(|before| *before == st.selection) {
kept = None;
}
}
// The document as the edit's step keeps it, read after the switch to it, which can measure
// its type again.
let doc = keeping_paths(h, item, || {
super::edit_item_with(h, item, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone());
super::command(h, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?;
Ok(doc)
})
})?;
if let Some((doc, selection)) = doc.zip(kept)
&& let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid)
&& let Some(step) = st.history.undo.last_mut().filter(|step| Arc::ptr_eq(&step.doc, &doc))
{
step.selection = Arc::new(selection);
}
Ok(())
})?;
Ok(())
}
#[cfg(test)]
thread_local! {
/// How many times this thread listed a document's paths ([`path_items`]), for the tests.
pub(crate) static PATH_LIST_BUILDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// Runs `f`, a command that changes the paint, stroke or points of the path `item` and adds,
/// removes and reorders no object of its own. When it succeeds, the document made no new object,
/// and the path is not inside a Shaper group, the lists of the document's, its layers' and its
/// groups' paths ([`path_items`]) stay kept. An edit inside a Shaper group regenerates the group's
/// paths, which can drop a path without making a new id.
fn keeping_paths<T>(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
let doc_state = |h: &super::Host, run: &mut dyn FnMut(&DocState)| {
let s = h.session.borrow();
if let Some(st) = s.documents().iter().find(|d| d.uid == item.doc.uid) {
run(st);
}
};
let mut kept = None;
doc_state(h, &mut |st| {
let in_shaper = st.doc.ancestry(item.id).unwrap_or_default().iter().filter_map(|i| st.doc.node(*i)).any(|a| a.extras().shaper.is_some());
if !in_shaper {
let listed = h.dom.paths.borrow().iter().any(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc));
if listed {
kept = Some((st.doc.clone(), st.doc.peek_next_id()));
}
}
});
let r = f()?;
if let Some((before, next)) = kept {
doc_state(h, &mut |st| {
if st.doc.peek_next_id() == next {
for list in h.dom.paths.borrow_mut().iter_mut().filter(|(uid, doc, ..)| *uid == st.uid && Arc::ptr_eq(doc, &before)) {
list.1 = st.doc.clone();
}
}
});
}
Ok(r)
}
/// The object whose paint the path `n` with id `id` shows: the outermost compound shape it is
/// inside, at any depth, or else its compound path when it is a member of one. The paint setters
/// paint that owner ([`edit_paint`]).
pub(super) fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node) -> &'a crate::doc::Node {
let ancestors = d.ancestry(id).unwrap_or_default();
let above = ancestors.split_last().map_or(&[][..], |(_, rest)| rest);
if let Some(shape) = above.iter().filter_map(|i| d.node(*i)).find(|p| p.is_compound_shape()) {
return shape;
}
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n)
}
/// Runs the paint command `id` with `params` on the object whose paint the path shows
/// ([`paint_owner`]).
fn edit_paint(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
let owner = read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).id)?;
if let Some(o) = params.as_object_mut() {
o.insert("ids".into(), json!([owner.0]));
}
edit_path(h, item, id, params)
}
/// A script's new path goes on the active layer while it is shown and unlocked, or the topmost
/// shown, unlocked layer otherwise. While an opacity mask, pattern or symbol is being edited,
/// the path goes on the layer recorded by that edit mode. `create::on_layer` validates the layer.
fn new_path_layer(st: &crate::DocState) -> Option<NodeId> {
let d = &st.doc;
if let Some(layer) =
d.mask_edit.map(|e| e.layer).or_else(|| d.pattern_edit.as_ref().map(|e| e.layer)).or_else(|| d.symbol_edit.as_ref().map(|e| e.layer))
{
return Some(layer);
}
st.current_layer().filter(|l| d.is_editable(*l)).or_else(|| d.default_layer())
}
/// Runs a path creation command with its layer placement recorded.
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
let mut params = params.clone();
params["onLayer"] = json!(parent.map(|p| p.0));
super::command_value(h, id, &params)
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit ([`protected`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) {
return Err(e);
}
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
o.insert("objectOnly".into(), json!(true));
}
}
let result = if KEEP_PATHS.contains(&id) {
keeping_paint(h, || keeping_paths(h, item, || edit_item(h, item, id, &params)))?
} else {
keeping_paint(h, || edit_item(h, item, id, &params))?
};
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
}
Ok(result)
}
/// The commands [`edit_path`] runs that change only paint, stroke or fill rule, after which the
/// document's paths are the ones listed before ([`keeping_paths`]).
const KEEP_PATHS: &[&str] = &["paint.setFill", "paint.setStroke", "stroke.set", "object.setOverprint", "path.setFillRule"];
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
/// and gradient and the recent colors as they were before it.
fn keeping_paint<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
let kept = {
let s = h.session.borrow();
(s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone())
};
let r = f();
let mut s = h.session.borrow_mut();
(s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors) = kept;
r
}
// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ----
/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the
/// document's), and the ids it listed then.
pub(super) type PathList = (u64, Arc<crate::Document>, Option<NodeId>, Rc<Vec<NodeId>>);
/// How many lists of paths [`super::State`] keeps at once.
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 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();
if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) {
let list = lists.remove(at);
let ids = list.3.clone();
lists.push(list);
return Ok(ids);
}
}
#[cfg(test)]
PATH_LIST_BUILDS.with(|n| n.set(n.get() + 1));
let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. });
let ids: Rc<Vec<NodeId>> = match container {
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)?;
Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect())
}
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())
}
};
let mut lists = h.dom.paths.borrow_mut();
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
if lists.len() >= PATH_LISTS {
lists.remove(0);
}
lists.push((st.uid, st.doc.clone(), container, ids.clone()));
Ok(ids)
}
pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)]))
}
/// The `pathItems` of the layer or group `id` in the document `uid`.
pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data {
host_ref("PathItems", &super::scoped_handle(h, uid, id))
}
/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths
/// of, if any.
fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) };
match handle.as_slice() {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)),
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its container is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let holds = with_doc(h, doc, |_, st| {
st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
});
if !holds {
return Err(HostError::Error(STALE_ITEM.into()));
}
Ok((doc, Some(id)))
}
_ => Err(HostError::Type("this is not a PathItems".into())),
}
}
/// `typename` of the paths of a document that is still open.
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
items_scope(h, a)?;
Ok(Data::String("PathItems".into()))
}
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64)))
}
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
Ok(match c {
None => host_ref("Document", &[float(h.run), float(doc.uid)]),
Some(c) => with_doc(h, doc, |_, st| {
if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) }
}),
})
}
/// `pathItems[i]`, and `pathItems["name"]` as `getByName` reads it. A key that is the text of a
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
/// looked up as that name, giving `undefined` when no path has it.
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
match arg(a, 1) {
Data::String(_) => match items_by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && super::probing(a) => Ok(Data::Undefined),
r => r,
},
Data::Number(n) => match super::position(*n) {
Some(i) => item_at(h, doc, c, i),
None => match items_named(h, doc, c, &vectorcraft_js::number_to_string(*n)) {
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
r => r,
},
},
_ => Ok(Data::Undefined),
}
}
/// The path at position `i` of `pathItems`, or `undefined` past the end.
fn item_at(h: &super::Host, doc: Doc, c: Option<NodeId>, i: usize) -> Answer {
with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id))))
}
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(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, c, name)
}
/// The first path of `pathItems` named `name`, or `Not found`.
fn items_named(h: &super::Host, doc: Doc, c: Option<NodeId>, name: &str) -> Answer {
with_doc(h, doc, |_, st| {
let ids = path_items(h, st, 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));
id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
})
}
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
let (doc, c) = items_scope(h, a)?;
match whole(*n).and_then(|i| usize::try_from(i).ok()).map(|i| item_at(h, doc, c, i)).transpose()? {
Some(Data::Undefined) | None => Err(HostError::Error(NOT_FOUND.into())),
Some(d) => Ok(d),
}
}
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or
/// locked 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. A compound path's
/// `pathItems.removeAll()` leaves the compound path, empty, as `remove()` of its last path does.
/// It also throws and deletes nothing when it would delete the clipping path of a group or layer
/// that keeps other objects, or leave a compound path or group that clips one with no visible path
/// or visible type that lays out glyphs to clip by.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let (doc, c) = items_scope(h, a)?;
let (ids, refused, on_locked, masks, tracing) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st, c)?;
let d = &st.doc;
if h.session.borrow().menu.guides_locked
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
}
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **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();
let mut next: Vec<_> = d.layers.iter().collect();
let mut nodes = Vec::new();
while let Some(n) = next.pop() {
nodes.push(n);
next.extend(n.children().into_iter().flatten());
}
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut affected: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
for n in nodes.iter().rev() {
if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) {
affected.insert(n.id);
}
}
// Type is laid out only inside a mask that loses a path; no other outline decides a refusal.
let mut in_mask = std::collections::HashSet::new();
for n in &nodes {
if n.clips()
&& let Some(mask) = n.children().and_then(|k| k.first())
&& affected.contains(&mask.id)
{
let mut stack = vec![mask];
while let Some(m) = stack.pop() {
if in_mask.insert(m.id) {
stack.extend(m.children().into_iter().flatten());
}
}
}
}
let mut geometry = std::collections::HashSet::new();
let mut masks = Vec::new();
for n in nodes.into_iter().rev() {
let kids = n.children().map_or(&[][..], Vec::as_slice);
// Without `keepEmpty`, clear removes compound paths emptied of direct members, but keeps
// empty groups. A compound path's own `pathItems.removeAll()` keeps it, empty.
if c.is_none()
&& matches!(n.kind, NodeKind::Compound { .. })
&& !kids.is_empty()
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
{
going.insert(n.id);
}
// A clip outline takes in visible paths and the glyphs of visible type, as
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
let shape = n.visible
&& match &n.kind {
NodeKind::Path { .. } => true,
NodeKind::Text(t) => {
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
}
_ => false,
};
// A clipping group's outline is its first member's alone.
let inner =
if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) };
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
geometry.insert(n.id);
}
if n.clips()
&& let Some(mask) = kids.first()
&& affected.contains(&mask.id)
&& !geometry.contains(&mask.id)
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
&& masks.len() < 20
{
masks.push(mask.id.0);
}
}
let going: Vec<NodeId> = going.into_iter().collect();
// Deleting the objects above an image in an ordinary group named as a tracing would make it one.
let tracing = super::removal_makes_tracing(d, &going);
Ok::<_, HostError>((ids, refused, on_locked, masks, tracing))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}")));
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
super::layers::refuse_kept_clipping_paths(&masks)?;
if tracing {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
if !ids.is_empty() {
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &params))?;
}
Ok(Data::Undefined)
}
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
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
/// locked layer or group.
pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group";
/// The error of an object made in a Live Paint group, which would join the group's paths instead
/// of staying in the group's own list.
pub const LIVE_PAINT_CONTAINER: &str = "Cannot add an object to a Live Paint group";
/// Whether `id` is a Live Paint group, which takes no new objects from the object model.
pub(super) fn is_live_paint_group(st: &DocState, id: NodeId) -> bool {
st.doc.node(id).is_some_and(vectorcraft_tools::builder::is_live_paint)
}
/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the
/// selection and the current layer kept. With a layer or group `container`, the container's layer
/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made
/// outside the container then moves on top of its contents in the same step; a container that is
/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]
/// before anything is made, and a Live Paint group throws [`LIVE_PAINT_CONTAINER`]. → the new path.
fn make_in(
h: &super::Host,
doc: Doc,
container: Option<NodeId>,
make: impl FnOnce(&super::Host) -> std::result::Result<NodeId, HostError>,
) -> Answer {
if let Some(c) = container {
let (open, live) = with_doc(h, doc, |_, st| (editable(&st.doc, c), is_live_paint_group(st, c)));
if !open {
return Err(HostError::Error(CONTAINER_LOCKED.into()));
}
if live {
return Err(HostError::Error(LIVE_PAINT_CONTAINER.into()));
}
}
let made = match container {
// Making a path can take more than one command (a stroke, a reversal): a failure of a later
// one undoes the path too.
None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?,
Some(c) => super::atomically(h, |h| {
let id = on_doc(h, doc.uid, true, |h| {
command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?;
make(h)
})?;
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
Ok(id)
})?,
};
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
Ok(super::item_ref(h, st, made))
}
/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s
/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path.
/// Selecting the new path and putting the selection back load the selected objects' paint and
/// stroke width into new art, so new art's paint from before, the defaults a script set included,
/// is put back.
fn make(h: &super::Host, doc: Doc, container: Option<NodeId>, id: &str, params: &Value, reversed: bool) -> Answer {
keeping_paint(h, || {
make_in(h, doc, container, |h| {
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
if reversed {
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
}
Ok(id)
})
})
}
/// Argument `i`, or `default` when it is left out.
fn number_or(a: &[Data], i: usize, default: f64, what: &str) -> std::result::Result<f64, HostError> {
given(arg(a, i)).map_or(Ok(default), |d| number(d, what))
}
/// A size or radius: finite and not negative.
fn size(a: &[Data], i: usize, default: Option<f64>, what: &str) -> std::result::Result<f64, HostError> {
let v = match (given(arg(a, i)), default) {
(Some(d), _) => number(d, what)?,
(None, Some(v)) => v,
(None, None) => return Err(HostError::Type(format!("{what} must be a finite number"))),
};
if !(0.0..=super::MAX_SIZE).contains(&v) {
return Err(HostError::Range(format!("{what} must be from 0 to 3999856 points")));
}
Ok(v)
}
/// A whole number argument from `min` to `max`.
fn count(a: &[Data], i: usize, default: f64, min: f64, max: f64, what: &str) -> std::result::Result<f64, HostError> {
let v = number_or(a, i, default, what)?;
if v.fract() != 0.0 || !(min..=max).contains(&v) {
return Err(HostError::Range(format!("{what} must be a whole number from {min} to {max}")));
}
Ok(v)
}
fn flag(a: &[Data], i: usize, what: &str) -> std::result::Result<bool, HostError> {
given(arg(a, i)).map_or(Ok(false), |d| boolean(d, what))
}
/// The top-left corner, in document coordinates, of a box whose top-left corner the script gives.
fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result<Point, HostError> {
with_doc(h, doc, |_, st| Ok(frame(st)?.to_document(h.dom.coords.get(), [left, top])))
}
/// `rectangle(top, left, width, height, reversed?)`.
fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
let top = coordinate(arg(a, 1), "top")?;
let left = coordinate(arg(a, 2), "left")?;
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
let reversed = flag(a, 5, "reversed")?;
let p = corner(h, doc, left, top)?;
make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
}
/// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the
/// page from the top of the left side.
fn rounded(r: Rect, rx: f64, ry: f64) -> Vec<Anchor> {
const K: f64 = 0.552_284_749_830_793_4;
let (rx, ry) = (rx.min(r.width() / 2.0), ry.min(r.height() / 2.0));
let (kx, ky) = (rx * K, ry * K);
let a = |p: Point, h_in: Point, h_out: Point| Anchor { p, h_in, h_out, kind: AnchorKind::Corner };
let (x0, y0, x1, y1) = (r.x0, r.y0, r.x1, r.y1);
let mut out = vec![
a(Point::new(x0, y0 + ry), Point::new(x0, y0 + ry), Point::new(x0, y0 + ry - ky)),
a(Point::new(x0 + rx, y0), Point::new(x0 + rx - kx, y0), Point::new(x0 + rx, y0)),
a(Point::new(x1 - rx, y0), Point::new(x1 - rx, y0), Point::new(x1 - rx + kx, y0)),
a(Point::new(x1, y0 + ry), Point::new(x1, y0 + ry - ky), Point::new(x1, y0 + ry)),
a(Point::new(x1, y1 - ry), Point::new(x1, y1 - ry), Point::new(x1, y1 - ry + ky)),
a(Point::new(x1 - rx, y1), Point::new(x1 - rx + kx, y1), Point::new(x1 - rx, y1)),
a(Point::new(x0 + rx, y1), Point::new(x0 + rx, y1), Point::new(x0 + rx - kx, y1)),
a(Point::new(x0, y1 - ry), Point::new(x0, y1 - ry + ky), Point::new(x0, y1 - ry)),
];
out.dedup_by(|b, a| {
b.p.distance(a.p) < 1e-9 && {
a.h_out = b.h_out;
true
}
});
if out.len() > 1
&& out.first().zip(out.last()).is_some_and(|(f, l)| f.p.distance(l.p) < 1e-9)
&& let Some(l) = out.pop()
&& let Some(f) = out.first_mut()
{
f.h_in = l.h_in;
}
out
}
/// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20,
/// reversed = false)`: a closed path with `path.create`.
fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
let top = coordinate(arg(a, 1), "top")?;
let left = coordinate(arg(a, 2), "left")?;
let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?);
let (rx, ry) = (size(a, 5, Some(15.0), "horizontalRadius")?, size(a, 6, Some(20.0), "verticalRadius")?);
let reversed = flag(a, 7, "reversed")?;
let p = corner(h, doc, left, top)?;
let anchors: Vec<Value> = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect();
make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed)
}
/// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`.
fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?;
let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?;
let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?);
let reversed = flag(a, 5, "reversed")?;
if flag(a, 6, "inscribed")? {
return Err(HostError::Error("ellipse with inscribed true is not available yet".into()));
}
let p = corner(h, doc, left, top)?;
make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed)
}
/// The center of a polygon or star, in document coordinates.
fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result<Point, HostError> {
let x = given(arg(a, 1)).map_or(Ok(200.0), |d| coordinate(d, "centerX"))?;
let y = given(arg(a, 2)).map_or(Ok(300.0), |d| coordinate(d, "centerY"))?;
corner(h, doc, x, y)
}
/// `polygon(centerX = 200, centerY = 300, radius = 50, sides = 8, reversed = false)`.
fn items_polygon(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
let c = center(h, doc, a)?;
let r = size(a, 3, Some(50.0), "radius")?;
let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?;
let reversed = flag(a, 5, "reversed")?;
make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed)
}
/// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed =
/// false)`.
fn items_star(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
let c = center(h, doc, a)?;
let r1 = size(a, 3, Some(50.0), "radius")?;
let r2 = size(a, 4, Some(20.0), "innerRadius")?;
let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?;
let reversed = flag(a, 6, "reversed")?;
make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed)
}
/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or
/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art.
/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set
/// back to none in the same step, and new art keeps the paint it had before.
fn items_add(h: &super::Host, a: &[Data]) -> Answer {
let (doc, into) = items_scope(h, a)?;
// New art's paint is read with the document active, since activating a document can load its
// selection's appearance into new art. Selecting the new path loads its temporary stroke into
// new art, and putting the selection back does not undo that, so new art's paint from before
// the path is put back.
keeping_paint(h, || {
make_in(h, doc, into, |h| {
let unpainted = {
let ap = h.session.borrow().new_art();
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
};
let parent = with_doc(h, doc, |_, st| new_path_layer(st));
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
if unpainted {
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
}
Ok(id)
})
})
}
// ---- PathItem geometry ----
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
Ok(host_ref("PathPoints", &handle))
}
/// Whether the path of `item` is closed: it has a subpath and every subpath is. Setting `closed` on
/// a path with no subpath gives it an empty closed one ([`path_set_closed`]).
fn is_closed(h: &super::Host, item: Item) -> std::result::Result<bool, HostError> {
read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))
}
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
Ok(Data::Bool(is_closed(h, item)?))
}
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
let closed = boolean(arg(a, 1), "closed")?;
let item = this_path(h, a)?;
// A path with no subpath gets an empty closed one to keep the value in; any other change keeps
// the number of points, so the kept starts of the waiting changes stay valid.
if closed && read_points(h, item, |subs| subs.is_empty())? {
edit_points(h, item, |subs| subs.push(SubPath::new(Vec::new(), closed)))?;
} else {
edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
}
Ok(Data::Undefined)
}
/// Whether the path fills by the even-odd rule: its compound path's rule when it is a member of one,
/// as `path.setFillRule` sets it there.
fn path_evenodd(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |st, n, _| {
let owner = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. })).unwrap_or(n);
Data::Bool(matches!(owner.kind, NodeKind::Path { rule: FillRule::EvenOdd, .. } | NodeKind::Compound { rule: FillRule::EvenOdd, .. }))
})
}
fn path_set_evenodd(h: &super::Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "evenodd")?;
let item = this_path(h, a)?;
if path_evenodd(h, a)? != Data::Bool(on) {
edit_path(h, item, "path.setFillRule", json!({"rule": if on { "evenOdd" } else { "nonZero" }}))?;
}
Ok(Data::Undefined)
}
/// The area in square points: negative when the path runs counterclockwise on the page.
fn path_area(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |_, _, pd| num(pd.subpaths.iter().map(SubPath::signed_area).sum()))
}
fn path_length(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |_, _, pd| num(pd.length()))
}
fn path_guides(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. })))
}
/// The error of assigning `guides` on a path inside a compound path.
pub const COMPOUND_MEMBER_GUIDES: &str = "Changing guides on a path inside a compound path is not available yet";
/// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again
/// with `view.guides.release`; the selection stays as it was. A value the path has already runs no
/// command and throws no error. Otherwise a clipping path cannot be a guide, a path inside a
/// compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both values throw
/// an error.
fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "guides")?;
let item = this_path(h, a)?;
let (now, clipping) = read_path(h, item, |_, n, _| match &n.kind {
NodeKind::Path { guide, clipping, .. } => (*guide, *clipping),
_ => (false, false),
})?;
if now == on {
return Ok(Data::Undefined);
}
let (member, editable, selectable) = with_doc(h, item.doc, |_, st| {
let member = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id);
(member, editable(&st.doc, item.id), selectable)
});
if member {
return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into()));
}
if !editable || !selectable {
return Err(cannot_edit(item.id));
}
if h.session.borrow().menu.guides_locked {
return Err(HostError::Error(format!("Cannot change guides on PathItem {}: guides are locked", item.id.0)));
}
if !on {
edit_path(h, item, "view.guides.release", json!({}))?;
return Ok(Data::Undefined);
}
if clipping {
return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0)));
}
see_all_points(h)?;
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
command(h, "view.guides.make", &json!({}))
});
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
fn path_clipping(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { clipping: true, .. })))
}
/// `setEntirePath([[x, y], ...])`: corner points with no handles in place of every point, in one
/// subpath that stays closed when the path was.
fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let Data::Array(list) = arg(a, 1) else { return Err(HostError::Type("setEntirePath needs an array of [x, y] points".into())) };
if list.len() > MAX_POINTS {
return Err(HostError::Range(format!("setEntirePath takes at most {MAX_POINTS} points")));
}
let script: Vec<[f64; 2]> = list.iter().map(|d| point(d, "each point")).collect::<std::result::Result<_, _>>()?;
let f = with_doc(h, item.doc, |_, st| frame(st))?;
let closed = is_closed(h, item)?;
let c = h.dom.coords.get();
let anchors: Vec<Anchor> =
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
write_path(h, item, subs)?;
cut_points(h, item);
Ok(Data::Undefined)
}
// ---- PathItem paint ----
/// The top fill's paint and the top stroke's paint, width, cap, join, miter limit, dashes and
/// offset, and the overprint flags of both.
struct Look {
fill: Paint,
fill_overprint: bool,
stroke: Paint,
width: f64,
cap: LineCap,
join: LineJoin,
miter: f64,
dashes: Vec<f64>,
offset: f64,
stroke_overprint: bool,
}
/// The look of `item`, read from its compound path or compound shape when it is a member of one,
/// since the paint commands paint that owner in its place.
fn look(h: &super::Host, item: Item) -> std::result::Result<Look, HostError> {
read_path(h, item, |st, n, _| {
let ap = &paint_owner(&st.doc, item.id, n).appearance;
let fill = ap.fill();
let stroke = ap.stroke();
Look {
fill: fill.map_or(Paint::None, |f| f.paint.clone()),
fill_overprint: fill.is_some_and(|f| f.overprint),
stroke: stroke.map_or(Paint::None, |s| s.paint.clone()),
width: stroke.map_or(0.0, |s| s.width),
cap: stroke.map_or(LineCap::default(), |s| s.cap),
join: stroke.map_or(LineJoin::default(), |s| s.join),
miter: stroke.map_or(10.0, |s| s.miter_limit),
dashes: stroke.and_then(|s| s.dash.as_ref()).map_or_else(Vec::new, |d| d.pattern.clone()),
offset: stroke.and_then(|s| s.dash.as_ref()).map_or(0.0, |d| d.offset),
stroke_overprint: stroke.is_some_and(|s| s.overprint),
}
})
}
fn this_look(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, Look), HostError> {
let item = this_path(h, a)?;
Ok((item, look(h, item)?))
}
fn path_filled(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Bool(!this_look(h, a)?.1.fill.is_none()))
}
fn path_stroked(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Bool(!this_look(h, a)?.1.stroke.is_none()))
}
/// Sets the fill (`fill`) or the stroke to `color`, or to none, with `paint.setFill` or
/// `paint.setStroke`.
fn set_paint(h: &super::Host, item: Item, fill: bool, color: Option<Color>) -> std::result::Result<(), HostError> {
let id = if fill { "paint.setFill" } else { "paint.setStroke" };
let params = match color {
Some(c) => json!({"color": colors::param(&c)}),
None => json!({"none": true}),
};
edit_paint(h, item, id, params)?;
Ok(())
}
/// The paint new art gets for its fill or stroke, as `paint.setFill` or `paint.setStroke` params for
/// the path `item`: a solid color, linked to its global or spot swatch while the document has that
/// swatch; a gradient, a placed one moved onto the bounds of the path or of the compound path or
/// compound shape whose paint it shows, as new art takes it; or a pattern.
/// A fill or stroke of none gives black. A pattern that its swatch does not give as new art has it
/// (its own placement, or a pattern the document does not have) throws an error.
fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Result<Value, HostError> {
let mut ap = h.session.borrow().new_art();
let top = |ap: &vectorcraft_doc::Appearance| if fill { ap.fill_paint() } else { ap.stroke_paint() };
let what = if fill { "filled" } else { "stroked" };
let paint = top(&ap);
match &paint {
Paint::None => Ok(json!({"color": colors::param(&Color::BLACK)})),
Paint::Solid { color, swatch: Some(name), tint } => {
let linked = read_path(h, item, |st, _, _| st.doc.swatch(name).is_some())?;
Ok(match linked {
true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}),
true => json!({"swatch": name}),
false => json!({"color": colors::param(color), "keepModel": true}),
})
}
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})),
Paint::Gradient(g) => {
let mut g = g.clone();
if g.geom.is_some() || g.freeform.is_some() {
match read_path(h, item, |st, n, _| paint_owner(&st.doc, item.id, n).geometric_bounds())? {
Some(b) => {
ap.rebase_gradients(GraphicStyle::UNIT_BOX, b);
if let Paint::Gradient(placed) = top(&ap) {
g = placed;
}
}
None => (g.geom, g.freeform) = (None, None),
}
}
Ok(json!({"gradient": gradient_params(&g), "keepModel": true}))
}
Paint::Pattern { pattern, .. } => {
let given = read_path(h, item, |st, _, _| {
let d = &st.doc;
d.swatch(pattern).map(|sw| sw.paint.clone()).or_else(|| d.pattern(pattern).map(|_| pattern_paint(pattern)))
})?;
match given {
Some(p) if p == paint => Ok(json!({"swatch": pattern})),
Some(_) => Err(HostError::Error(format!(
"Cannot set {what}: new art's pattern `{pattern}` has a placement of its own, which is not available yet"
))),
None => Err(HostError::Error(format!("Cannot set {what}: new art's pattern `{pattern}` is not in this document"))),
}
}
}
}
fn set_painted(h: &super::Host, a: &[Data], fill: bool) -> Answer {
let on = boolean(arg(a, 1), if fill { "filled" } else { "stroked" })?;
let (item, look) = this_look(h, a)?;
let now = if fill { !look.fill.is_none() } else { !look.stroke.is_none() };
if now != on {
let params = if on { new_art_params(h, item, fill)? } else { json!({"none": true}) };
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, params)?;
}
Ok(Data::Undefined)
}
fn path_set_filled(h: &super::Host, a: &[Data]) -> Answer {
set_painted(h, a, true)
}
fn path_set_stroked(h: &super::Host, a: &[Data]) -> Answer {
set_painted(h, a, false)
}
fn path_fill_color(h: &super::Host, a: &[Data]) -> Answer {
let (item, look) = this_look(h, a)?;
super::resources::paint_color(h, item.doc, &look.fill)
}
fn path_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
let (item, look) = this_look(h, a)?;
super::resources::paint_color(h, item.doc, &look.stroke)
}
/// Links the fill (`fill`) or the stroke to the Spot `spot` at `tint` (0 to 100), unless it is
/// linked to it at that tint already. A `SpotColor` without a `spot`, as a color linked to a global
/// process swatch reads, throws: it does not name the swatch it was read from.
fn set_spot_color(h: &super::Host, a: &[Data], fill: bool, spot: &Data, tint: f64) -> Answer {
if matches!(spot, Data::Undefined) {
return Err(HostError::Error("SpotColor.spot must be a Spot; a color read from a global process swatch cannot be assigned yet".into()));
}
let (item, look) = this_look(h, a)?;
let now = if fill { &look.fill } else { &look.stroke };
let at_tint = |t: &f32| *t == colors::unit(tint, 100.0);
let name = super::resources::assigned_spot(h, spot, item.doc)?;
let same = matches!(now, Paint::Solid { swatch: Some(n), tint: t, .. } if *n == name && at_tint(t));
if !same {
edit_paint(h, item, if fill { "paint.setFill" } else { "paint.setStroke" }, json!({"swatch": name, "tint": tint}))?;
}
Ok(Data::Undefined)
}
fn set_color(h: &super::Host, a: &[Data], fill: bool) -> Answer {
if let Some((spot, tint)) = colors::spot_parts(arg(a, 1))? {
return set_spot_color(h, a, fill, spot, tint);
}
let color = colors::assigned(arg(a, 1), if fill { "fillColor" } else { "strokeColor" })?;
let (item, look) = this_look(h, a)?;
let now = if fill { &look.fill } else { &look.stroke };
if !colors::unchanged(arg(a, 1), color, now, |c| c) {
set_paint(h, item, fill, color)?;
}
Ok(Data::Undefined)
}
fn path_set_fill_color(h: &super::Host, a: &[Data]) -> Answer {
set_color(h, a, true)
}
fn path_set_stroke_color(h: &super::Host, a: &[Data]) -> Answer {
set_color(h, a, false)
}
/// Runs `stroke.set` with `params` on the path, unless `same`.
fn set_stroke_option(h: &super::Host, item: Item, same: bool, params: Value) -> Answer {
if !same {
edit_paint(h, item, "stroke.set", params)?;
}
Ok(Data::Undefined)
}
fn path_stroke_width(h: &super::Host, a: &[Data]) -> Answer {
Ok(num(this_look(h, a)?.1.width))
}
fn path_set_stroke_width(h: &super::Host, a: &[Data]) -> Answer {
let w = number(arg(a, 1), "strokeWidth")?;
if !(0.0..=MAX_STROKE_WIDTH).contains(&w) {
return Err(HostError::Range("strokeWidth must be from 0 to 1000 points".into()));
}
let (item, look) = this_look(h, a)?;
set_stroke_option(h, item, (look.width - w).abs() < 1e-9, json!({"weight": w}))
}
/// Each stroke cap, its `StrokeCap` value and its name in `stroke.set`.
pub(super) const CAPS: &[(LineCap, &str, &str)] = &[
(LineCap::Butt, "StrokeCap.BUTTENDCAP", "butt"),
(LineCap::Round, "StrokeCap.ROUNDENDCAP", "round"),
(LineCap::Square, "StrokeCap.PROJECTINGENDCAP", "square"),
];
/// Each stroke join, its `StrokeJoin` value and its name in `stroke.set`.
pub(super) const JOINS: &[(LineJoin, &str, &str)] = &[
(LineJoin::Bevel, "StrokeJoin.BEVELENDJOIN", "bevel"),
(LineJoin::Round, "StrokeJoin.ROUNDENDJOIN", "round"),
(LineJoin::Miter, "StrokeJoin.MITERENDJOIN", "miter"),
];
fn path_stroke_cap(h: &super::Host, a: &[Data]) -> Answer {
let cap = this_look(h, a)?.1.cap;
Ok(Data::String(CAPS.iter().find(|c| c.0 == cap).map_or("StrokeCap.BUTTENDCAP", |c| c.1).into()))
}
fn path_set_stroke_cap(h: &super::Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => CAPS.iter().find(|c| c.1 == s),
_ => None,
};
let Some(&(cap, _, name)) = found else { return Err(HostError::Type("strokeCap must be a StrokeCap value".into())) };
let (item, look) = this_look(h, a)?;
set_stroke_option(h, item, look.cap == cap, json!({"cap": name}))
}
fn path_stroke_join(h: &super::Host, a: &[Data]) -> Answer {
let join = this_look(h, a)?.1.join;
Ok(Data::String(JOINS.iter().find(|j| j.0 == join).map_or("StrokeJoin.MITERENDJOIN", |j| j.1).into()))
}
fn path_set_stroke_join(h: &super::Host, a: &[Data]) -> Answer {
let found = match arg(a, 1) {
Data::String(s) => JOINS.iter().find(|j| j.1 == s),
_ => None,
};
let Some(&(join, _, name)) = found else { return Err(HostError::Type("strokeJoin must be a StrokeJoin value".into())) };
let (item, look) = this_look(h, a)?;
set_stroke_option(h, item, look.join == join, json!({"join": name}))
}
fn path_miter(h: &super::Host, a: &[Data]) -> Answer {
Ok(num(this_look(h, a)?.1.miter))
}
fn path_set_miter(h: &super::Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "strokeMiterLimit")?;
if !(1.0..=500.0).contains(&v) {
return Err(HostError::Range("strokeMiterLimit must be from 1 to 500".into()));
}
let (item, look) = this_look(h, a)?;
set_stroke_option(h, item, (look.miter - v).abs() < 1e-9, json!({"miterLimit": v}))
}
fn path_dashes(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Array(this_look(h, a)?.1.dashes.into_iter().map(num).collect()))
}
/// The dash and gap lengths a script assigned to `what`: at most [`MAX_DASHES`] finite lengths
/// that are not negative and not all 0; `[]` or `{}` gives a solid line.
pub(super) fn dash_lengths(d: &Data, what: &str) -> std::result::Result<Vec<f64>, HostError> {
let lengths: Vec<f64> = match d {
Data::Object(o) if o.is_empty() => Vec::new(),
Data::Array(list) if list.len() > MAX_DASHES => return Err(HostError::Range(format!("{what} takes at most {MAX_DASHES} lengths"))),
Data::Array(list) => list.iter().map(|d| number(d, "each dash length")).collect::<std::result::Result<_, _>>()?,
_ => return Err(HostError::Type(format!("{what} must be an array of lengths"))),
};
use crate::cmd::newart::DashFault;
match crate::cmd::newart::dash_fault(&lengths) {
None => Ok(lengths),
Some(DashFault::TooMany) => Err(HostError::Range(format!("{what} takes at most {MAX_DASHES} lengths"))),
Some(DashFault::OutOfRange) => Err(HostError::Range("each dash length must be from 0 to 1000000 points".into())),
Some(DashFault::AllZero) => Err(HostError::Range(format!("{what} needs a length that is not 0"))),
}
}
/// `strokeDashes = [lengths]`, as [`dash_lengths`] takes them.
fn path_set_dashes(h: &super::Host, a: &[Data]) -> Answer {
let lengths = dash_lengths(arg(a, 1), "strokeDashes")?;
let (item, look) = this_look(h, a)?;
let dash = if lengths.is_empty() { Value::Null } else { json!(lengths) };
set_stroke_option(h, item, look.dashes == lengths, json!({"dash": dash}))
}
fn path_dash_offset(h: &super::Host, a: &[Data]) -> Answer {
Ok(num(this_look(h, a)?.1.offset))
}
fn path_set_dash_offset(h: &super::Host, a: &[Data]) -> Answer {
let v = number(arg(a, 1), "strokeDashOffset")?;
if v.abs() > MAX_STROKE_WIDTH * 1000.0 {
return Err(HostError::Range("strokeDashOffset must be from -1000000 to 1000000 points".into()));
}
let (item, look) = this_look(h, a)?;
if look.dashes.is_empty() && v != 0.0 {
return Err(HostError::Error("strokeDashOffset needs strokeDashes first".into()));
}
set_stroke_option(h, item, (look.offset - v).abs() < 1e-9, json!({"dashOffset": v}))
}
fn path_fill_overprint(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Bool(this_look(h, a)?.1.fill_overprint))
}
fn path_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Bool(this_look(h, a)?.1.stroke_overprint))
}
fn set_overprint(h: &super::Host, a: &[Data], fill: bool) -> Answer {
let key = if fill { "fill" } else { "stroke" };
let on = boolean(arg(a, 1), if fill { "fillOverprint" } else { "strokeOverprint" })?;
let (item, look) = this_look(h, a)?;
let (now, paint) = if fill { (look.fill_overprint, &look.fill) } else { (look.stroke_overprint, &look.stroke) };
if now != on {
// The top fill or stroke of the object `look` reads, as `item` names it to the command.
let top = read_path(h, item, |st, n, _| {
let owner = paint_owner(&st.doc, item.id, n);
owner.appearance.items.iter().rposition(|i| i.is_fill() == fill).map(|index| (owner.id, index))
})?;
let (Some((owner, index)), false) = (top, paint.is_none()) else {
return Err(HostError::Error(format!("the path has no {key} to overprint")));
};
edit_path(h, item, "object.setOverprint", json!({key: on, "item": index, "ids": [owner.0]}))?;
}
Ok(Data::Undefined)
}
fn path_set_fill_overprint(h: &super::Host, a: &[Data]) -> Answer {
set_overprint(h, a, true)
}
fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer {
set_overprint(h, a, false)
}
// ---- PathItem stroke weights for `resize` ----
/// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None`
/// when the weight stays. A `custom` percent, one other than the resize's own scale, is at most
/// 100000.
pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, custom: bool) -> std::result::Result<Option<f64>, HostError> {
if custom && !(0.0..=100_000.0).contains(&percent) {
return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into()));
}
let width = look(h, item)?.width;
let new_width = width * percent / 100.0;
if new_width > MAX_STROKE_WIDTH {
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
}
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
}
/// The largest stroke weight in the path `item`'s own appearance, in points.
pub(super) fn largest_stroke_weight(h: &super::Host, item: Item) -> std::result::Result<f64, HostError> {
read_path(h, item, |_, n, _| {
n.appearance
.items
.iter()
.filter_map(|item| match item {
vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width),
vectorcraft_doc::AppearanceItem::Fill(_) => None,
})
.fold(0.0, f64::max)
})
}
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
}
/// Whether the path `item` is a member of a compound path or compound shape, whose stroke the
/// compound holds.
pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
}
/// Sets the stroke weight of the path `item` to `weight` points, on the object whose paint the
/// path shows ([`edit_paint`]).
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
edit_paint(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
}
// ---- PathPoints ----
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
Ok(item)
}
/// Writes the waiting point changes of another path in the same Objects on Path group as `item`.
fn flush_other(h: &super::Host, item: Item) -> std::result::Result<(), HostError> {
let waiting = h.dom.pending.borrow().as_ref().map(|(w, _)| *w);
let other = waiting.is_some_and(|w| {
w.doc.uid == item.doc.uid
&& w.id != item.id
&& with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let read = d.ancestry(item.id).unwrap_or_default();
d.ancestry(w.id).is_some_and(|a| {
a.iter().any(|g| read.contains(g) && d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path))
})
})
});
if other { flush(h) } else { Ok(()) }
}
/// `typename` of the points of a path that is still in its document.
fn points_typename(h: &super::Host, a: &[Data]) -> Answer {
points_path(h, a)?;
Ok(Data::String("PathPoints".into()))
}
fn points_length(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
Ok(num(float(points_of(h, item)? as u64)))
}
fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
Ok(path_ref(h, item))
}
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
handle.extend([float(i as u64), float(point_cuts(h, item))]);
host_ref("PathPoint", &handle)
}
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
/// made to them since the run last saw them.
fn point_cuts(h: &super::Host, item: Item) -> u64 {
let key = (item.doc.uid, item.id.0);
see_points(h, key, || false);
h.dom.point_cuts.borrow().get(&key).copied().unwrap_or(0)
}
/// Notes that the run removed or replaced points of `item`, which makes the points read before
/// stale.
fn cut_points(h: &super::Host, item: Item) {
cut_key(h, (item.doc.uid, item.id.0));
}
/// [`cut_points`] for the path of document uid and path id `key`.
fn cut_key(h: &super::Host, key: (u64, u64)) {
let mut cuts = h.dom.point_cuts.borrow_mut();
let n = cuts.entry(key).or_insert(0);
*n = n.saturating_add(1);
}
#[cfg(test)]
thread_local! {
/// How many times this thread looked at a path's points ([`see_points`]), for the tests.
pub(crate) static POINT_LOOKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// The node of `id` in `d`, as the document holds it.
fn node_arc(d: &crate::Document, id: NodeId) -> Option<&Arc<crate::doc::Node>> {
let at = d.index_path(id)?;
let (first, rest) = at.split_first()?;
let mut cur = d.layers.get(*first)?;
for &i in rest {
cur = cur.children()?.get(i)?;
}
Some(cur)
}
/// Keeps the path of document uid and path id `key` as it is now, the first time the run reads its
/// points and after each later look. When its points differ from the ones the run last saw, the
/// points read before go stale, unless `own`: the object model made the change
/// ([`see_all_points`]), which `own` is asked only after a change. The kept node is shared with
/// the document, so a node whose pointer is unchanged has unchanged points, and any change to it
/// makes a new node.
fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
#[cfg(test)]
POINT_LOOKS.with(|n| n.set(n.get() + 1));
let node = {
let s = h.session.borrow();
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| {
h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone());
node_arc(&st.doc, NodeId(key.1)).cloned()
})
};
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
// stale.
let Some(node) = node else {
if h.dom.point_nodes.borrow_mut().get_mut(&key.0).and_then(|paths| paths.remove(&key.1)).is_some() {
cut_key(h, key);
}
return;
};
let changed = match h.dom.point_nodes.borrow_mut().entry(key.0).or_default().insert(key.1, node.clone()) {
Some(old) => !Arc::ptr_eq(&old, &node) && old.path_data().map(|pd| &pd.subpaths) != node.path_data().map(|pd| &pd.subpaths),
None => false,
};
if changed && !own() {
cut_key(h, key);
}
}
/// [`see_points`] for each path whose points the run has read, after each command, so that a
/// change that a later command reverses still makes the points stale. Paths under the object that
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid; the other Global Edit members, which take the
/// object model's edit too, are looked at as well. A document that is the one the run last looked
/// at is skipped, as are its paths. The look is charged by the objects it looks at.
pub(super) fn see_all_points(h: &super::Host) -> std::result::Result<(), HostError> {
let (keys, looked_at): (Vec<(u64, u64)>, u64) = {
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
let seen = h.dom.point_nodes.borrow();
let mut keys = Vec::new();
let mut looked_at = 0u64;
docs.retain(|uid, before| {
let state = s.documents().iter().find(|d| d.uid == *uid);
let after = state.map(|st| &st.doc);
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
return true;
}
// A document none of whose paths the run still holds points of is not looked at; reading
// points again keeps it as it is then.
if seen.get(uid).is_none_or(std::collections::HashMap::is_empty) {
return false;
}
// Editing a path in an Objects on Path group can move the other paths in the group, so
// the outermost such group is looked at in place of the path. While Global Edit is on,
// an edit of the selected member (also one made by moving a group that holds it) is
// given to the other members, so each of them, or the outermost Objects on Path group
// holding it, is looked at too. Subtrees the command left as they were are skipped.
// Each node is paired with the node of the same id under the same parent now, so that no
// node is searched for through the whole document.
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
Some(item) => {
let root = |id: NodeId| {
before
.ancestry(id)
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)))
.unwrap_or(id)
};
let members = state.and_then(|st| st.global_edit.as_ref()).map(|ge| ge.members.iter().map(|(id, _)| *id)).into_iter().flatten();
let mut roots = std::collections::HashSet::new();
std::iter::once(item.id)
.chain(members)
.map(root)
.filter(|id| roots.insert(*id))
.filter_map(|id| node_arc(before, id).map(|n| (n, after.and_then(|d| node_arc(d, id)))))
.collect()
}
None => paired(&before.layers, after.map(|d| &d.layers), &mut looked_at),
};
// A group that moved to another parent keeps its node, so a node with children that is
// not found under its old parent is looked for among all the nodes now, listed once.
let mut all: Option<std::collections::HashMap<NodeId, &Arc<crate::doc::Node>>> = None;
while let Some((node, mut now)) = todo.pop() {
looked_at += 1;
if now.is_none()
&& node.children().is_some()
&& let Some(d) = after
{
let all = all.get_or_insert_with(|| {
let mut m = std::collections::HashMap::new();
let mut stack: Vec<&Arc<crate::doc::Node>> = d.layers.iter().collect();
while let Some(n) = stack.pop() {
m.insert(n.id, n);
stack.extend(n.children().into_iter().flatten());
}
looked_at += m.len() as u64;
m
});
now = all.get(&node.id).copied();
}
if now.is_some_and(|n| Arc::ptr_eq(node, n)) {
continue;
}
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
keys.push((*uid, node.id.0));
}
if let Some(children) = node.children() {
todo.extend(paired(children, now.and_then(|n| n.children()), &mut looked_at));
}
}
if let Some(after) = after {
*before = after.clone();
true
} else {
false
}
});
keys.sort_unstable();
keys.dedup();
(keys, looked_at)
};
if looked_at > 0 {
h.charge_call(looked_at)?;
}
let editing = h.dom.editing.get();
for (uid, id) in keys {
let own = || match editing {
Some(e) if e.doc.uid == uid => {
let s = h.session.borrow();
let id = NodeId(id);
id == e.id || s.documents().iter().find(|d| d.uid == uid).and_then(|st| st.doc.ancestry(id)).is_some_and(|a| a.contains(&e.id))
}
_ => false,
};
see_points(h, (uid, id), own);
}
Ok(())
}
/// Pairs each node of `before` with the node of the same id in `after`, adding to `looked_at` the
/// nodes of `after` it looks at.
fn paired<'a>(
before: &'a [Arc<crate::doc::Node>],
after: Option<&'a Vec<Arc<crate::doc::Node>>>,
looked_at: &mut u64,
) -> Vec<(&'a Arc<crate::doc::Node>, Option<&'a Arc<crate::doc::Node>>)> {
let after = after.map_or(&[][..], Vec::as_slice);
*looked_at += after.len() as u64;
let now: std::collections::HashMap<NodeId, &Arc<crate::doc::Node>> = after.iter().map(|n| (n.id, n)).collect();
before.iter().map(|n| (n, now.get(&n.id).copied())).collect()
}
fn points_at(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
let n = points_of(h, item)?;
Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined })
}
/// `index(key)`: the points are not named, so a key that is not a number throws `Not found`.
fn points_index(h: &super::Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::Number(_) => match points_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Error(NOT_FOUND.into())),
}
}
fn points_add(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0])));
let mut counted = point_starts(h, item)?;
let n = counted.last().copied().unwrap_or(0);
if n >= MAX_POINTS {
return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points")));
}
let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?;
let p = match last {
Some(p) => p,
None => origin?,
};
let closed = last.is_none() && is_closed(h, item)?;
// The kept starts are dropped, so that `counted` is their only copy and grows in place.
*h.dom.point_starts.borrow_mut() = None;
edit_points(h, item, |subs| match subs.last_mut() {
Some(sp) => sp.anchors.push(Anchor::corner(p)),
None => subs.push(SubPath::new(vec![Anchor::corner(p)], closed)),
})?;
if matches!(&*h.dom.pending.borrow(), Some((w, _)) if same_path(*w, item)) {
let grown = Rc::make_mut(&mut counted);
if grown.len() > 1 {
if let Some(total) = grown.last_mut() {
*total += 1;
}
} else {
*grown = vec![0, 1];
}
*h.dom.point_starts.borrow_mut() = Some((Counted::Waiting(item), counted));
}
Ok(point_ref(h, item, n))
}
fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let item = points_path(h, a)?;
write_path(h, item, Vec::new())?;
cut_points(h, item);
Ok(Data::Undefined)
}
// ---- PathPoint ----
/// The path and the index of the point `this` names, which must still be in the path, with no
/// point of the path removed or replaced since `this` was read.
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
}
let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?;
if i >= points_of(h, item)? {
return Err(HostError::Error(STALE_POINT.into()));
}
Ok((item, i))
}
/// Reads the anchor `this` names with `f`, given the frame and the coordinate system.
fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer {
let (item, i) = this_point(h, a)?;
let c = h.dom.coords.get();
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
let at = locate_at(&point_starts(h, item)?, i);
read_points(h, item, |subs| {
let anchor = at.and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j)));
anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into()))
})?
}
/// Changes the anchor `this` names with `f`, given the point the script assigned in document
/// 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, i) = this_point(h, a)?;
edit_anchor(h, item, i, f)?;
Ok(Data::Undefined)
}
/// The point the script assigned to a point property, in document coordinates.
fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Result<Point, HostError> {
let p = point(arg(a, 1), what)?;
let (item, _) = this_point(h, a)?;
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
in_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer {
read_point(h, a, |f, c, an| pair(f.to_script(c, an.p)))
}
fn pt_set_anchor(h: &super::Host, a: &[Data]) -> Answer {
let p = assigned_point(h, a, "anchor")?;
edit_point(h, a, |an| an.p = p)
}
fn pt_left(h: &super::Host, a: &[Data]) -> Answer {
read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_in)))
}
fn pt_set_left(h: &super::Host, a: &[Data]) -> Answer {
let p = assigned_point(h, a, "leftDirection")?;
edit_point(h, a, |an| an.h_in = p)
}
fn pt_right(h: &super::Host, a: &[Data]) -> Answer {
read_point(h, a, |f, c, an| pair(f.to_script(c, an.h_out)))
}
fn pt_set_right(h: &super::Host, a: &[Data]) -> Answer {
let p = assigned_point(h, a, "rightDirection")?;
edit_point(h, a, |an| an.h_out = p)
}
fn pt_type(h: &super::Host, a: &[Data]) -> Answer {
read_point(h, a, |_, _, an| Data::String(if an.kind == AnchorKind::Smooth { "PointType.SMOOTH" } else { "PointType.CORNER" }.into()))
}
fn pt_set_type(h: &super::Host, a: &[Data]) -> Answer {
let kind = match arg(a, 1) {
Data::String(s) if s == "PointType.CORNER" => AnchorKind::Corner,
Data::String(s) if s == "PointType.SMOOTH" => AnchorKind::Smooth,
_ => return Err(HostError::Type("pointType must be a PointType value".into())),
};
edit_point(h, a, |an| an.kind = kind)
}
fn pt_parent(h: &super::Host, a: &[Data]) -> Answer {
let (item, _) = this_point(h, a)?;
Ok(path_ref(h, item))
}
/// `typename` of a point that is still on its path.
fn pt_typename(h: &super::Host, a: &[Data]) -> Answer {
this_point(h, a)?;
Ok(Data::String("PathPoint".into()))
}
/// Whether a group or compound path that holds the path `id` is selected, which selects the path
/// as a whole whatever the path's own selection is.
fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer())))
}
/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every
/// point of a path selected as a whole is (a path is when a group or compound path that holds it
/// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The
/// endpoints of selected segments are not.
fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool {
if held {
return true;
}
if !sel.contains(id) {
return false;
}
match sel.partial(id) {
None => true,
Some(picked) => locate(subs, i).is_some_and(|(s, j)| {
picked.contains(&(s, j))
&& !sel
.segments
.get(&id)
.is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j)))
}),
}
}
/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a
/// point index names the same anchor in both.
fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len())
}
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
/// [`super::State`] are written first when they add or remove points of this path or invalidate
/// selected segments.
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
let moved = match &*h.dom.pending.borrow() {
Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| {
!same_layout(subs, &pd.subpaths)
|| st
.selection
.segments
.get(&item.id)
.is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count())))
})?,
_ => false,
};
if moved {
super::flush(h)?;
}
let on =
read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?;
Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into()))
}
/// The `PathPointSelection` values that select a point's direction handles.
const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPointSelection.RIGHTDIRECTION", "PathPointSelection.LEFTRIGHTPOINT"];
/// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and
/// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay
/// selected, except that selecting an anchor of a path with selected segments replaces that path's
/// segment selection, as `select.anchorsMany` does. A value the point has already runs no command.
/// Direction handles cannot be selected, so `LEFTDIRECTION`, `RIGHTDIRECTION` and
/// `LEFTRIGHTPOINT` throw an error, and so does `NOSELECTION` on a path selected through a group or
/// compound path that holds it, and `ANCHORPOINT` on a guide while guides are locked. The setter
/// writes the waiting point changes first, as every member that is not a point function does.
fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer {
let on = match arg(a, 1) {
Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true,
Data::String(s) if s == "PathPointSelection.NOSELECTION" => false,
Data::String(s) if HANDLE_SELECTIONS.contains(&s.as_str()) => {
return Err(HostError::Error(format!("PathPoint.selected = {s} is not available yet: only anchor points can be selected")));
}
_ => return Err(HostError::Type("selected must be a PathPointSelection value".into())),
};
let (item, i) = this_point(h, a)?;
let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| {
let node = st.doc.node(item.id);
let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]);
let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }));
let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id);
let held = held_selected(&st.doc, &st.selection, item.id);
(anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide)
});
if now == on {
return Ok(Data::Undefined);
}
let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) };
if held {
return Err(HostError::Error(format!(
"PathPoint.selected = PathPointSelection.NOSELECTION is not available yet on PathItem {}: the group or compound path that holds it is selected",
item.id.0
)));
}
if on && !selectable {
return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0)));
}
if on && guide && h.session.borrow().menu.guides_locked {
return Err(HostError::Error(format!("Cannot select PathItem {}: guides are locked", item.id.0)));
}
let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }});
on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", &params))?;
Ok(Data::Undefined)
}
/// `selectedPathPoints`: the points that are selected anchor points ([`anchor_selected`]), in the
/// order of `pathPoints`.
fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let picked: Vec<usize> = read_path(h, item, |st, _, pd| {
let sel = &st.selection;
let held = held_selected(&st.doc, sel, item.id);
if !held && !sel.contains(item.id) {
return Vec::new();
}
let segments = sel.segments.get(&item.id);
let ends: std::collections::BTreeSet<_> = segments
.into_iter()
.flatten()
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
.flatten()
.collect();
let firsts = starts(&pd.subpaths);
match sel.partial(item.id).filter(|_| !held) {
// Direct-selected anchors that no selected segment ends at, in subpath and anchor
// order, which is the order of `pathPoints`.
Some(anchors) => anchors
.iter()
.filter(|&&(s, j)| pd.subpaths.get(s).is_some_and(|sp| j < sp.anchors.len()) && !ends.contains(&(s, j)))
.filter_map(|(s, j)| firsts.get(*s).map(|first| first + j))
.collect(),
None => (0..firsts.last().copied().unwrap_or(0)).collect(),
}
})?;
h.charge_call(picked.len() as u64)?;
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
Ok(Data::Array(points))
}
/// `remove()`: deletes the point; a subpath left with no points goes too.
fn pt_remove(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
// A direct selection of the path's points is renumbered after the removal.
let selected = {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
let sel = &st.selection;
(sel.anchors.contains_key(&item.id) || sel.segments.contains_key(&item.id)).then(|| sel.clone())
};
// Writing the points can prune the selection, and selecting loads the selected paths' paint
// into new art, so new art's paint, the defaults a script set included, is put back.
keeping_paint(h, || remove_point(h, item, i, selected))?;
cut_points(h, item);
Ok(Data::Undefined)
}
/// Removes point `i` of the path of `item` for [`pt_remove`], and renumbers `selected`, the
/// direct selection of the path's points before the removal.
fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::doc::Selection>) -> std::result::Result<(), HostError> {
let removed = edit_points(h, item, |subs| {
let (s, j) = locate(subs, i)?;
let sp = subs.get_mut(s)?;
// The segment that closes a closed subpath runs from its last anchor to its first.
let last = sp.closed.then(|| sp.anchors.len() - 1);
sp.anchors.remove(j);
let gone = sp.anchors.is_empty();
if gone {
subs.remove(s);
}
Some((s, j, gone, last))
})?;
if let (Some((s, j, gone, last)), Some(before)) = (removed, selected) {
let mut sel = before.clone();
renumber_selected(&mut sel, item.id, s, j, gone, last);
// A selection the removal leaves as it was waits with the points, so that removals in a
// row are written together, unless its anchors are now all of the path's, which selects
// the path whole, or the path is in an Objects on Path group, which places it again.
let wait = sel == before && {
let valid = read_points(h, item, |subs| {
sel.anchors.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| *k < sp.anchors.len())))
&& sel.segments.get(&item.id).is_none_or(|a| a.iter().all(|(p, k)| subs.get(*p).is_some_and(|sp| sp.has_segment(*k, true))))
})?;
let total = points_of(h, item)?;
let all = sel.anchors.get(&item.id).is_some_and(|a| a.len() >= total) && !sel.segments.contains_key(&item.id);
let on_path = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
d.ancestry(item.id).is_some_and(|a| a.iter().any(|g| d.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)))
});
valid && !all && !on_path
};
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
// The current layer and the highlighted Layers rows are put back after the selection is set.
let (layer, rows) = with_doc(h, item.doc, |_, st| (st.active_layer, st.highlighted_rows()));
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)?;
super::restore_layer(h, item.doc.uid, layer, &rows)
})?;
}
}
Ok(())
}
/// Updates the direct selection `sel` of the path `id` after the anchor `j` of its subpath `s` was
/// removed, and the subpath with it when `gone`: the anchor, the segments it ended and their other
/// ends leave the selection, unless a segment still selected ends there, and the anchors, segments
/// and subpaths after it keep the points they selected. `last` is the index of the subpath's last
/// anchor before the removal when the subpath is closed: its closing segment runs from that anchor
/// to anchor 0.
fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: usize, gone: bool, last: Option<usize>) {
// The closing segment ends at the removed anchor when the removed anchor is the first one.
let closing = last.filter(|_| j == 0);
// An anchor (or a segment, by its first anchor) after the removed one moves down one place.
let shift = |(p, k): (usize, usize), segment: bool| -> Option<(usize, usize)> {
match p.cmp(&s) {
std::cmp::Ordering::Less => Some((p, k)),
std::cmp::Ordering::Greater => Some((if gone { p - 1 } else { p }, k)),
std::cmp::Ordering::Equal if gone => None,
std::cmp::Ordering::Equal if k == j || (segment && (k + 1 == j || closing == Some(k))) => None,
std::cmp::Ordering::Equal => Some((p, if k > j { k - 1 } else { k })),
}
};
// The other ends of the selected segments that the removal joins, in the new numbering: the
// anchor before the removed one and the one after it.
let mut ends: Vec<(usize, usize)> = Vec::new();
if let Some(segments) = sel.segments.get_mut(&id) {
let cut: Vec<(usize, usize)> = segments.iter().copied().filter(|g| shift(*g, true).is_none() && g.0 == s && !gone).collect();
for (p, k) in cut {
// Segment k runs from anchor k to anchor k + 1; one of the two is the removed one.
// The closing segment of a closed subpath ends at anchor 0.
let other = if k != j {
k
} else if last == Some(k) {
0
} else {
k + 1
};
// The closing segment's other end is its first anchor, the old last one.
let other = if closing == Some(k) { k } else { other };
ends.extend(shift((p, other), false));
}
*segments = segments.iter().filter_map(|g| shift(*g, true)).collect();
if segments.is_empty() {
sel.segments.remove(&id);
}
}
let kept_ends: Vec<(usize, usize)> =
sel.segments.get(&id).map(|g| g.iter().flat_map(|(p, k)| [(*p, *k), (*p, k + 1)]).collect()).unwrap_or_default();
if let Some(anchors) = sel.anchors.get_mut(&id) {
*anchors = anchors.iter().filter_map(|a| shift(*a, false)).filter(|a| !ends.contains(a) || kept_ends.contains(a)).collect();
}
if let Some((key, a)) = sel.key_anchor
&& key == id
{
sel.key_anchor = shift(a, false).filter(|a| sel.anchors.get(&id).is_some_and(|set| set.contains(a))).map(|a| (key, a));
}
}
// ---- Registration ----
/// The members `PathItem` adds to `PageItem`'s.
pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
// `translate`, `rotate` and `resize` are `PageItem`'s ([`super::transform`]).
let mut m = named(vec![
("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }),
("closed", point_property(l, path_closed, path_set_closed), typed("boolean")),
("evenodd", property(l, path_evenodd, path_set_evenodd), typed("boolean")),
("area", get(l, path_area), typed("number")),
("length", get(l, path_length), typed("number")),
("guides", property(l, path_guides, path_set_guides), typed("boolean")),
("clipping", get(l, path_clipping), typed("boolean")),
("setEntirePath", point_method(l, path_set_entire), returns("undefined", &[("pathPoints", "Array")])),
("filled", property(l, path_filled, path_set_filled), typed("boolean")),
("fillColor", property(l, path_fill_color, path_set_fill_color), typed("Color")),
("fillOverprint", property(l, path_fill_overprint, path_set_fill_overprint), typed("boolean")),
("stroked", property(l, path_stroked, path_set_stroked), typed("boolean")),
("strokeColor", property(l, path_stroke_color, path_set_stroke_color), typed("Color")),
("strokeOverprint", property(l, path_stroke_overprint, path_set_stroke_overprint), typed("boolean")),
(
"strokeWidth",
property(l, path_stroke_width, path_set_stroke_width),
MemberInfo { min: Some(0.0), max: Some(MAX_STROKE_WIDTH), ..typed("number") },
),
("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")),
("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }),
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
]);
m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n)));
m
}
/// `PathItems`, `PathPoints` and `PathPoint`.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let corner = [("top", "number"), ("left", "number"), ("width", "number"), ("height", "number")];
let center = [("centerX", "number"), ("centerY", "number"), ("radius", "number")];
let with = |first: &[(&'static str, &'static str)], rest: &[(&'static str, &'static str)]| -> Vec<(&'static str, &'static str)> {
first.iter().chain(rest).copied().collect()
};
vec![
class(
"PathItems",
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("*")),
("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", &[])),
("add", method(l, items_add), returns("PathItem", &[])),
("rectangle", method(l, items_rectangle), returns("PathItem", &with(&corner, &[("reversed", "boolean")]))),
(
"roundedRectangle",
method(l, items_rounded_rectangle),
returns("PathItem", &with(&corner, &[("horizontalRadius", "number"), ("verticalRadius", "number"), ("reversed", "boolean")])),
),
("ellipse", method(l, items_ellipse), returns("PathItem", &with(&corner, &[("reversed", "boolean"), ("inscribed", "boolean")]))),
("polygon", method(l, items_polygon), returns("PathItem", &with(&center, &[("sides", "number"), ("reversed", "boolean")]))),
(
"star",
method(l, items_star),
returns("PathItem", &with(&center, &[("innerRadius", "number"), ("points", "number"), ("reversed", "boolean")])),
),
]),
Some(super::function(l, items_at)),
),
class(
"PathPoints",
None,
named(vec![
("typename", point_get(l, points_typename), typed("string")),
("length", point_get(l, points_length), typed("number")),
("parent", point_get(l, points_parent), typed("PathItem")),
("index", point_method(l, points_index), returns("PathPoint", &[("itemKey", "*")])),
("add", point_method(l, points_add), returns("PathPoint", &[])),
("removeAll", point_method(l, points_remove_all), returns("undefined", &[])),
("toString", class_text("PathPoints"), returns("string", &[])),
]),
Some(super::point_function(l, points_at)),
),
class(
"PathPoint",
None,
named(vec![
("typename", point_get(l, pt_typename), typed("string")),
("parent", point_get(l, pt_parent), typed("PathItem")),
("anchor", point_property(l, pt_anchor, pt_set_anchor), typed("Array")),
("leftDirection", point_property(l, pt_left, pt_set_left), typed("Array")),
("rightDirection", point_property(l, pt_right, pt_set_right), typed("Array")),
("pointType", point_property(l, pt_type, pt_set_type), typed("PointType")),
(
"selected",
HostMember::Property { get: super::point_function(l, pt_selected), set: super::function(l, pt_set_selected) },
typed("PathPointSelection"),
),
("remove", point_method(l, pt_remove), returns("undefined", &[])),
("toString", class_text("PathPoint"), returns("string", &[])),
]),
None,
),
]
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
use crate::Session;
thread_local! {
pub(super) static LOCATE_STEPS: Cell<usize> = const { Cell::new(0) };
}
#[test]
fn selected_points_do_not_rescan_subpaths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128];
s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap();
s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap();
LOCATE_STEPS.with(|steps| steps.set(0));
let out = s
.execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"}))
.unwrap();
assert_eq!(out["log"], json!([2]));
LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get()));
}
#[test]
fn undoing_a_point_write_selects_the_anchors_it_removed_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap();
let source = "var p = app.activeDocument.pathItems[0]; p.setEntirePath([[0, 0], [10, 0], [10, 10]]); \
vc.log(p.selectedPathPoints.length); app.undo();";
let out = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
assert_eq!(out["log"], json!([1]));
let id = NodeId(id.as_u64().unwrap());
let anchors: Vec<(usize, usize)> = s.active().unwrap().selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default();
assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed");
}
#[test]
fn undoing_a_point_write_in_a_background_document_selects_its_anchors_again() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let text = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Text"})).unwrap()["id"].as_u64().unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 1], [0, 3]]})).unwrap();
let uid = s.active().unwrap().uid;
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let st = s.document_mut(uid).unwrap();
let NodeKind::Text(t) = &mut Arc::make_mut(&mut st.doc).node_mut(NodeId(text)).unwrap().kind else { panic!("not a text object") };
t.cached_bounds = None;
let before_activation = st.doc.clone();
let source = "var d; for (var i = 0; i < app.documents.length; i++) { if (app.documents[i].pathItems.length) d = app.documents[i]; } \
d.pathItems[0].setEntirePath([[0, 0], [10, 0], [10, 10]]); app.activeDocument = d; app.undo();";
s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap();
let id = NodeId(id.as_u64().unwrap());
let st = s.documents().iter().find(|d| d.uid == uid).unwrap();
assert!(!Arc::ptr_eq(&st.doc, &before_activation));
assert!(matches!(&st.doc.node(NodeId(text)).unwrap().kind, NodeKind::Text(t) if t.cached_bounds.is_some()));
assert_eq!(st.doc.node(id).and_then(|n| n.path_data()).map(|pd| pd.subpaths[0].anchors.len()), Some(4));
let anchors: Vec<(usize, usize)> = st.selection.anchors.get(&id).map(|a| a.iter().copied().collect()).unwrap_or_default();
assert_eq!(anchors, vec![(0, 1), (0, 3)], "the undo puts back the selection the write changed");
}
#[test]
fn a_made_id_above_two_to_the_53_stays_exact() {
let made = |v: Value| made_id(&(Data::Undefined, v));
assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made(json!({"id": 7})), Ok(NodeId(7)));
assert!(made(json!({"id": 1.5})).is_err());
assert!(made(json!({})).is_err());
}
}