//! Paths and their points in the script object model, as the help pages
//! ,
//! ,
//! and
//! 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 {
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 {
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 {
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 {
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 {
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(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::doc::Node, &PathData) -> T) -> std::result::Result {
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 = 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 {
#[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),
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>, 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 {
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(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) -> std::result::Result {
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(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result {
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(
h: &super::Host,
item: Item,
counts_kept: bool,
f: impl FnOnce(&mut Vec) -> T,
) -> std::result::Result {
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) -> 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 =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "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 = 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(h: &super::Host, item: Item, f: impl FnOnce() -> std::result::Result) -> std::result::Result {
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 {
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 {
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, 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, ¶ms)
}
/// 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 {
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, ¶ms)))?
} else {
keeping_paint(h, || edit_item(h, item, id, ¶ms))?
};
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(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, Option, Rc>);
/// 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) -> std::result::Result>, 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> = match container {
Some(c) => {
let children: &[Arc] = 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), 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, 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, 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())),
}
}
#[cfg(test)]
thread_local! {
/// How many objects [`items_remove_all`] walked on this thread, for the tests.
pub(crate) static REMOVE_ALL_VISITS: std::cell::Cell = const { std::cell::Cell::new(0) };
}
/// `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,
/// image, placed document 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 = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
let locks = d.locked_artboards();
let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
// The document's list is checked against every object. A layer's or group's list is checked
// against the container's subtree, or, when the container lies in the clipping path of a
// clipping group above it, against the subtree of the highest such clipping path and the
// group it clips; no other outline holds its paths. An empty list is not walked.
let mut next: Vec<&Arc> = Vec::new();
let mut nodes = Vec::new();
if !ids.is_empty() {
match c.and_then(|c| d.index_path(c)) {
None => next.extend(d.layers.iter()),
Some(at) => {
// A damaged file can give two objects one id; a path that the id finds outside
// the container would be deleted in place of the container's own.
if let Some(id) = ids.iter().find(|i| d.index_path(**i).is_none_or(|p| p.len() != at.len() + 1 || !p.starts_with(&at))) {
return Err(HostError::Error(format!("cannot delete PathItem {}: its id also names another object", id.0)));
}
let mut line: Vec<&Arc> = Vec::with_capacity(at.len());
let mut kids = d.layers.as_slice();
for &i in &at {
let Some(n) = kids.get(i) else { break };
line.push(n);
kids = n.children().map_or(&[][..], Vec::as_slice);
}
// A clipping path is its group's first child, found by place, not by id.
let clip = (1..line.len()).find(|&k| line[k - 1].clips() && at[k] == 0);
if let Some(k) = clip {
#[cfg(test)]
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
nodes.push(line[k - 1]);
}
next.extend(line.get(clip.unwrap_or(line.len().saturating_sub(1))).copied());
}
}
}
while let Some(n) = next.pop() {
#[cfg(test)]
REMOVE_ALL_VISITS.with(|v| v.set(v.get() + 1));
nodes.push(n);
next.extend(n.children().into_iter().flatten());
}
let mut going: std::collections::HashSet = ids.iter().copied().collect();
let mut affected: std::collections::HashSet = 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, the frames of visible images and placed
// documents that enclose an area, 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,
// A frame collapsed to a line or a point encloses nothing to clip by.
NodeKind::Image(_) | NodeKind::PlacedDocument(_) => n.clip_shapes(None).iter().any(|(frame, _)| encloses(frame)),
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);
}
// The live geometry effects of what stays in the clipping path reshape the region it
// clips by, as the renderer draws it; deleting paths that lets an effect shrink the
// region to nothing leaves no outline. A region that was empty before is left as it is.
// The region is the area the outline fills under its fill rule, so outlines that run
// opposite ways over the same area under nonzero fill nothing.
let reshaped_empty = |m: &vectorcraft_doc::Node| {
vectorcraft_render::effects::reshaped_clip_outline(m).is_some_and(|o| !o.is_some_and(|(bp, rule)| fills(&bp, rule)))
};
if n.clips()
&& let Some(mask) = kids.first()
&& affected.contains(&mask.id)
&& (!geometry.contains(&mask.id) || (reshaped_empty(&without(mask, &going, &affected)) && !reshaped_empty(mask)))
&& 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 = 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::>().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::>().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::>(), "keepEmpty": c.is_some()});
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", ¶ms))?;
}
Ok(Data::Undefined)
}
/// Whether a subpath of `outline` encloses an area. Each subpath's area is measured from its first
/// point, so its position does not change the result, and an area within roundoff of its own
/// bounding box's is counted as none.
fn encloses(outline: &kurbo::BezPath) -> bool {
let mut subpaths: Vec = Vec::new();
for el in outline.elements() {
if matches!(el, kurbo::PathEl::MoveTo(_)) || subpaths.is_empty() {
subpaths.push(kurbo::BezPath::new());
}
if let Some(last) = subpaths.last_mut() {
last.push(*el);
}
}
subpaths.into_iter().any(|mut sub| {
let Some(start) = sub.elements().iter().find_map(|e| e.end_point()) else { return false };
sub.apply_affine(kurbo::Affine::translate(-start.to_vec2()));
let area = kurbo::Shape::area(&sub).abs();
area > 0.0 && area > 64.0 * f64::EPSILON * kurbo::Shape::bounding_box(&sub).area()
})
}
/// Whether `outline` fills an area under `rule`: a subpath encloses an area ([`encloses`]) and the
/// outline with its overlaps resolved, thin strips included, has an area. An outline the path
/// operations refuse is judged by [`encloses`] alone.
fn fills(outline: &kurbo::BezPath, rule: vectorcraft_geom::FillRule) -> bool {
if !encloses(outline) {
return false;
}
match vectorcraft_pathops::try_area(&vectorcraft_geom::PathData::from_bezpath(outline), rule) {
Ok(area) => area > 0.0,
Err(_) => true,
}
}
/// `n` without the members in `going`, at every depth. Only the members in `affected` (those that
/// hold a member in `going`) are copied; the others are shared.
fn without(
n: &vectorcraft_doc::Node,
going: &std::collections::HashSet,
affected: &std::collections::HashSet,
) -> vectorcraft_doc::Node {
let mut m = n.clone();
if let Some(kids) = m.children_mut() {
kids.retain(|k| !going.contains(&k.id));
for k in kids.iter_mut().filter(|k| affected.contains(&k.id)) {
*k = Arc::new(without(k, going, affected));
}
}
m
}
/// 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 {
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,
make: impl FnOnce(&super::Host) -> std::result::Result,
) -> 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, 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 {
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, what: &str) -> std::result::Result {
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 {
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 {
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 {
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 {
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 = 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 {
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 {
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::>()?;
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 =
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::>()?;
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,
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 {
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) -> 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 {
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, HostError> {
let lengths: Vec = 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::>()?,
_ => 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