mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into feat/scripts-layer-text-frames
This commit is contained in:
commit
e4e6dd517d
25 files changed
+1292
-358
No files matched your search
@@ -253,7 +253,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
|
||||
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
|
||||
// passed over.
|
||||
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
// A document whose active artboard the script chose uses that choice, not the one the run
|
||||
// started with.
|
||||
let chosen = h.session.borrow().active().and_then(|st| {
|
||||
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
|
||||
Some((st.uid, super::dom::active_artboard(st)))
|
||||
});
|
||||
let active = match &chosen {
|
||||
Some(chosen) => std::slice::from_ref(chosen),
|
||||
None => h.active_artboards.as_slice(),
|
||||
};
|
||||
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
|
||||
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
|
||||
let outer = h.session.borrow_mut().set_replaying(true);
|
||||
let r = command(h, &s.id, ¶ms);
|
||||
|
||||
@@ -18,7 +18,8 @@
|
||||
//!
|
||||
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
|
||||
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound
|
||||
//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
|
||||
//! gives, and a script may name the application's members without `app.`, as
|
||||
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
|
||||
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
|
||||
@@ -37,8 +38,7 @@
|
||||
//! - After `documents[0]`, documents are listed from the one active most recently to the one
|
||||
//! active longest ago. A change a script makes to a document in the back does not move it.
|
||||
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
|
||||
//! group or compound path, and leaves out layers and ruler guides. The `layers` module gives the
|
||||
//! order of a layer's, a group's and a compound path's lists. An index out of range gives
|
||||
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
|
||||
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
|
||||
//! - Script coordinates are points with Y up from the bottom of the first artboard
|
||||
//! (`DOCUMENTCOORDINATESYSTEM`, the default) or points with Y down from the top-left corner of
|
||||
@@ -184,6 +184,14 @@ pub(super) enum Coords {
|
||||
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
|
||||
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
|
||||
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
/// How many lists of art the art collections have built on this thread.
|
||||
pub(crate) static ART_SCANS: Cell<u64> = const { Cell::new(0) };
|
||||
}
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
|
||||
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
|
||||
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
|
||||
@@ -224,10 +232,18 @@ pub(super) struct State {
|
||||
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
|
||||
/// used first, each kept while its document is unchanged.
|
||||
art: RefCell<Vec<layers::ArtList>>,
|
||||
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
|
||||
/// first, each kept while its document is unchanged.
|
||||
layers: RefCell<Vec<layers::LayerList>>,
|
||||
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
|
||||
pub(super) active_artboards: RefCell<Vec<u64>>,
|
||||
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
|
||||
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
|
||||
/// Each open document's uid and the index of its active artboard when the run started.
|
||||
pub(super) boards_at_start: Vec<(u64, usize)>,
|
||||
/// Each document made during the run whose active artboard `setActiveArtboardIndex` chose,
|
||||
/// with the index it chose the first time.
|
||||
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
|
||||
/// `app.userInteractionLevel` ([`save_open`]).
|
||||
save_options: save_open::State,
|
||||
/// The print option objects ([`print`]).
|
||||
@@ -245,9 +261,9 @@ pub(super) struct State {
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state of a run whose heap is `heap_bytes` and that starts with the documents `docs` open.
|
||||
pub(super) fn new(heap_bytes: usize, docs: &[DocState]) -> Self {
|
||||
Self { preset_limit: heap_bytes as u64, boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), ..Self::default() }
|
||||
/// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`.
|
||||
pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self {
|
||||
Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether a call's own savepoint is open: its commands take none of their own.
|
||||
@@ -2200,7 +2216,7 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
}
|
||||
|
||||
fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2209,7 +2225,7 @@ fn items_length(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
@@ -2217,16 +2233,16 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
let Data::String(name) = layers::scoped_typename(h, a)? else { return Ok(text("[PageItems]")) };
|
||||
return Ok(text(format!("[{name}]")));
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
layers::scoped_typename(h, a)?;
|
||||
return Ok(text("[PageItems]"));
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2248,7 +2264,7 @@ fn position(n: f64) -> Option<usize> {
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no object has it.
|
||||
fn items_at(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2274,7 +2290,7 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2293,10 +2309,11 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
// A number is a position only; a scoped list answers its own positions.
|
||||
Data::Number(_) if layers::is_scoped(a) => layers::scoped_index(h, a),
|
||||
Data::Number(n) => {
|
||||
let doc = items_doc(h, a)?;
|
||||
match position(*n).map(|i| item_at(h, doc, i)).transpose()? {
|
||||
@@ -2312,7 +2329,7 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
|
||||
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
|
||||
/// and so does an object on a locked artboard.
|
||||
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if layers::is_scoped(a) {
|
||||
if layers::is_scoped(a, "PageItems") {
|
||||
return layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
@@ -2492,8 +2509,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four
|
||||
/// decimals.
|
||||
fn reported_opacity(opacity: f32) -> f64 {
|
||||
(f64::from(opacity) * 100.0 * 1e4).round() / 1e4
|
||||
}
|
||||
|
||||
fn item_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
|
||||
read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
|
||||
}
|
||||
|
||||
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -2510,7 +2533,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
// Only the exact number the getter reports counts as the same opacity.
|
||||
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
|
||||
let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0);
|
||||
let keeps_other =
|
||||
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
|
||||
(now, keeps_other)
|
||||
@@ -3562,8 +3585,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
|
||||
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
|
||||
let mut members = variables::item_members(l, c);
|
||||
members.extend(layers::members(c, l));
|
||||
let mut members = layers::members(c, l);
|
||||
members.extend(variables::item_members(l, c));
|
||||
if *c == "PathItem" {
|
||||
members.extend(paths::path_item_members(l));
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[
|
||||
("PatternColor", &[]),
|
||||
];
|
||||
|
||||
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
|
||||
let mut items = vec![("typename".to_string(), text(class))];
|
||||
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
|
||||
Data::Object(items)
|
||||
|
||||
@@ -27,8 +27,10 @@
|
||||
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
|
||||
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
|
||||
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
|
||||
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
|
||||
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
|
||||
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
|
||||
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
|
||||
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
|
||||
//! is refused.
|
||||
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
|
||||
|
||||
use std::cell::RefCell;
|
||||
@@ -291,7 +293,8 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
|
||||
// ---- files ----
|
||||
|
||||
/// Whether the script may read `path` now by its own read scope and the read roots
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
|
||||
/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link
|
||||
/// to, that a command may also read.
|
||||
fn may_read(h: &Host, path: &str) -> bool {
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
|
||||
@@ -496,16 +499,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
|
||||
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
|
||||
}
|
||||
let old = im.xf;
|
||||
// The coordinate frame only changes the signs of the linear part, so any change to it
|
||||
// counts; the offsets compare in points, which absorbs the rounding of the frame.
|
||||
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
|
||||
if same {
|
||||
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
|
||||
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
|
||||
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
|
||||
// A coefficient the script left as the getter reports keeps the image's own value, so the
|
||||
// conversion back does not shift an untouched axis.
|
||||
let olds = old.as_coeffs();
|
||||
let [a0, b0, c0, d0, e0, f0] = olds;
|
||||
let reported = match h.dom.coords.get() {
|
||||
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
|
||||
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
|
||||
};
|
||||
let mut wanted = target.as_coeffs();
|
||||
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
|
||||
if r == v {
|
||||
*w = o;
|
||||
}
|
||||
}
|
||||
if wanted == olds {
|
||||
return Ok(None);
|
||||
}
|
||||
if !area_of(old) {
|
||||
return Err(HostError::Error("the image has no area to transform".into()));
|
||||
}
|
||||
Ok(Some((target * old.inverse()).as_coeffs()))
|
||||
let target = Affine::new(wanted);
|
||||
let [ta, tb, tc, td, te, tf] = wanted;
|
||||
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
|
||||
// A move alone: the offset difference, without the error an inverse adds.
|
||||
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
|
||||
}
|
||||
// A nearly singular image loses precision through the inverse; refuse a change that would
|
||||
// not land where the script asked rather than move the image somewhere else.
|
||||
let delta = target * old.inverse();
|
||||
let landed = delta * old;
|
||||
if landed.as_coeffs() == olds {
|
||||
return Ok(None);
|
||||
}
|
||||
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
|
||||
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
|
||||
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
|
||||
});
|
||||
if !close || !area_of(landed) {
|
||||
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
|
||||
}
|
||||
Ok(Some(delta.as_coeffs()))
|
||||
})?;
|
||||
if let Some(d) = delta {
|
||||
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
|
||||
@@ -653,7 +690,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
]);
|
||||
let mut placed = named(vec![
|
||||
("file", property(l, placed_file, placed_set_file), typed("File")),
|
||||
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
|
||||
("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])),
|
||||
("embed", method(l, placed_embed), returns("undefined", &[])),
|
||||
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
|
||||
("boundingBox", get(l, placed_box), typed("Array")),
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
//! - `locked` true means the layer is locked.
|
||||
//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or
|
||||
//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it.
|
||||
//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255.
|
||||
//! - A layer's `color` is an `RGBColor` object with values from 0 to 255.
|
||||
//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it
|
||||
//! gives it its paint, as Make Compound Path takes the paint of a path it joins.
|
||||
//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a
|
||||
@@ -42,8 +42,8 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
|
||||
use super::{
|
||||
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
|
||||
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, id_parts, item_of, item_ref,
|
||||
later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, typename, whole,
|
||||
with_doc,
|
||||
later, method, named, named_text, node_of, num, number, on_doc, on_doc_layer, page_items, placement_of, probing, property, reported_opacity,
|
||||
returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::script::{Host, Link};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
@@ -66,6 +66,8 @@ enum Kind {
|
||||
Group,
|
||||
/// Compound paths (`CompoundPathItem`).
|
||||
Compound,
|
||||
/// Paths (`PathItem`).
|
||||
Path,
|
||||
/// Type (`TextFrame`), whose collection's other members are in `text.rs`.
|
||||
Text,
|
||||
}
|
||||
@@ -76,6 +78,7 @@ impl Kind {
|
||||
Kind::Any => "PageItems",
|
||||
Kind::Group => "GroupItems",
|
||||
Kind::Compound => "CompoundPathItems",
|
||||
Kind::Path => "PathItems",
|
||||
Kind::Text => "TextFrames",
|
||||
}
|
||||
}
|
||||
@@ -85,6 +88,7 @@ impl Kind {
|
||||
Kind::Any => typename(n).is_some(),
|
||||
Kind::Group => typename(n) == Some("GroupItem"),
|
||||
Kind::Compound => typename(n) == Some("CompoundPathItem"),
|
||||
Kind::Path => typename(n) == Some("PathItem"),
|
||||
Kind::Text => typename(n) == Some("TextFrame"),
|
||||
}
|
||||
}
|
||||
@@ -102,16 +106,17 @@ fn result_id(v: &Value, key: &str) -> Option<u64> {
|
||||
|
||||
// ---- Layer ----
|
||||
|
||||
/// The layer `d` names, which must still be a layer of its document. A layer read before its
|
||||
/// document was reverted throws `Stale page item`, as page items do.
|
||||
/// The layer `d` names, which must still be a layer of its document.
|
||||
pub(super) fn layer_of(h: &Host, d: &Data) -> Result<(Doc, NodeId)> {
|
||||
let Some(handle) = handle_of(d, "Layer") else { return Err(type_error("Layer")) };
|
||||
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(type_error("Layer")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
if Some(with_doc(h, doc, |_, st| st.reverts)) != whole(*reverts) {
|
||||
return Err(HostError::Error(STALE_ITEM.into()));
|
||||
if handle.len() != 5 {
|
||||
return Err(type_error("Layer"));
|
||||
}
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
|
||||
// A layer read before File › Revert is stale like the page items read with it.
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| {
|
||||
let reverted = matches!(handle.as_slice(), [run, uid, ..] if find_doc(h, *run, *uid).is_some());
|
||||
HostError::Error(if reverted { STALE_ITEM } else { STALE_LAYER }.into())
|
||||
})?;
|
||||
let ok = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::doc::Node::is_layer));
|
||||
if !ok {
|
||||
return Err(HostError::Error(STALE_LAYER.into()));
|
||||
@@ -123,19 +128,16 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> {
|
||||
layer_of(h, arg(a, 0))
|
||||
}
|
||||
|
||||
/// The handle of layer `id` of the document `uid`, or of a collection of the layer, group or
|
||||
/// compound path `id`: the run, the document, the id and the document's revert count, as
|
||||
/// [`super`]'s page items have.
|
||||
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
[float(h.run), float(uid), high, low, float(reverts)]
|
||||
}
|
||||
|
||||
fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data {
|
||||
host_ref("Layer", &layer_handle(h, uid, id))
|
||||
}
|
||||
|
||||
/// The handle of layer `id` of the document with uid `uid`, as `item_ref` gives it.
|
||||
fn layer_handle(h: &Host, uid: u64, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
[float(h.run), float(uid), high, low, float(reverts_of(h, uid))]
|
||||
}
|
||||
|
||||
/// Reads the layer `this` names with `f`.
|
||||
fn read_layer(h: &Host, a: &[Data], f: impl FnOnce(&DocState, &crate::doc::Node) -> Answer) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
@@ -239,7 +241,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn layer_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
|
||||
read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
|
||||
}
|
||||
|
||||
fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -247,17 +249,15 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
}
|
||||
// The number the getter reports (rounded to 4 decimals), or one that stores as the opacity the
|
||||
// layer has, leaves the layer as it is.
|
||||
let same = |n: &crate::doc::Node| (f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4 == v || n.opacity == (v / 100.0) as f32;
|
||||
set_layer(h, a, "object.setProps", same, json!({"opacity": v}))
|
||||
// The number the getter reports, or one that stores as the opacity the layer has, leaves the
|
||||
// layer as it is.
|
||||
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v || n.opacity == (v / 100.0) as f32, json!({"opacity": v}))
|
||||
}
|
||||
|
||||
fn layer_color(h: &Host, a: &[Data]) -> Answer {
|
||||
read_layer(h, a, |_, n| {
|
||||
let [r, g, b] = layer_flags(n).3.rgb();
|
||||
let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v)));
|
||||
Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)]))
|
||||
Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))]))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -299,9 +299,13 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let at = with_doc(h, doc, |_, st| {
|
||||
let list = layer_list(&st.doc, st.doc.parent_of(id));
|
||||
list.iter().position(|l| *l == id).map(|i| list.len() - i)
|
||||
});
|
||||
let parent = st.doc.parent_of(id);
|
||||
let count = parent.map_or(st.doc.layers.len(), |p| st.doc.children(Some(p)).map_or(0, Vec::len));
|
||||
h.charge_call(count as u64)?;
|
||||
let list = layer_list(&st.doc, parent);
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
|
||||
})?;
|
||||
at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into()))
|
||||
}
|
||||
|
||||
@@ -310,40 +314,64 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
|
||||
}
|
||||
|
||||
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
|
||||
/// child visited, including skipped children.
|
||||
fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
|
||||
let mut count = 0;
|
||||
for child in n.children().into_iter().flatten() {
|
||||
count += 1;
|
||||
if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() {
|
||||
continue;
|
||||
}
|
||||
if child.is_layer() {
|
||||
count += collect_editable_art(child, out);
|
||||
} else {
|
||||
out.push(child.id);
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its
|
||||
/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays,
|
||||
/// and no command runs when there is nothing to deselect or add.
|
||||
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
|
||||
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
let (ids, total) = with_doc(h, doc, |_, st| {
|
||||
let (ids, over) = with_doc(h, doc, |_, st| {
|
||||
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
|
||||
let selected = &st.selection.objects;
|
||||
h.charge_call(selected.len() as u64)?;
|
||||
if !on {
|
||||
return (selected.iter().copied().filter(inside).collect::<Vec<_>>(), 0);
|
||||
return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::<Vec<_>>(), false));
|
||||
}
|
||||
let locks = st.doc.locked_artboards();
|
||||
let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default();
|
||||
let mut art = Vec::new();
|
||||
let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art));
|
||||
// The walk is charged by every node it looks at, hidden and locked ones included, whether
|
||||
// or not anything is added.
|
||||
h.charge_call(count)?;
|
||||
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
|
||||
let mut ids = Vec::new();
|
||||
for o in art {
|
||||
if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
|
||||
have.insert(o);
|
||||
ids.push(o);
|
||||
if selected.len() + ids.len() > MAX_LISTED {
|
||||
break;
|
||||
}
|
||||
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
|
||||
continue;
|
||||
}
|
||||
// Only art that would be added counts toward the limit.
|
||||
if selected.len() + ids.len() >= MAX_LISTED {
|
||||
return Ok((ids, true));
|
||||
}
|
||||
have.insert(o);
|
||||
ids.push(o);
|
||||
}
|
||||
let total = selected.len() + ids.len();
|
||||
(ids, total)
|
||||
});
|
||||
Ok((ids, false))
|
||||
})?;
|
||||
if over {
|
||||
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
|
||||
}
|
||||
if ids.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
if total > MAX_LISTED {
|
||||
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
|
||||
}
|
||||
let command_id = if on { "select.add" } else { "select.toggle" };
|
||||
on_doc(h, doc.uid, false, |h| command(h, command_id, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
Ok(Data::Undefined)
|
||||
@@ -495,9 +523,44 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
|
||||
None => Some(&d.layers),
|
||||
Some(p) => d.children(Some(p)),
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64)));
|
||||
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, the parent a `Layers` object lists (`None`: the top
|
||||
/// level) and the layers it listed then.
|
||||
pub(super) type LayerList = (u64, Arc<Document>, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The layers of `parent` as [`layer_list`] gives them. The last [`ART_LISTS`] lists are kept while
|
||||
/// their documents are unchanged, so a loop over `layers[i]` lists the layers once. Each new list
|
||||
/// is charged by the objects it looks at.
|
||||
fn layers_listed(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
{
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
let at = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent);
|
||||
if let Some(at) = at {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.3.clone();
|
||||
lists.push(list);
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let looked_at = match parent {
|
||||
None => st.doc.layers.len(),
|
||||
Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len),
|
||||
};
|
||||
h.charge_call(looked_at as u64)?;
|
||||
let ids = Rc::new(layer_list(&st.doc, parent));
|
||||
let mut lists = h.dom.layers.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= ART_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), parent, ids.clone()));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
fn layers_of(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id) = this_layer(h, a)?;
|
||||
Ok(host_ref("Layers", &layer_handle(h, doc.uid, id)))
|
||||
@@ -505,8 +568,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn layers_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
let n = with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
Ok(num(float(with_doc(h, doc, |_, st| layers_listed(h, st, parent).map(|l| l.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn layers_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -519,18 +581,30 @@ fn layers_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Layers"))
|
||||
}
|
||||
|
||||
/// `collection["name"]` as `getByName` reads it, or `undefined` for `"name" in collection` when
|
||||
/// nothing has the name, as the document's `pageItems` does.
|
||||
fn read_by_name(h: &Host, a: &[Data], by_name: fn(&Host, &[Data]) -> Answer) -> Answer {
|
||||
match by_name(h, a) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
}
|
||||
}
|
||||
|
||||
fn layers_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, layers_by_name);
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
with_doc(h, doc, |_, st| Ok(layers_listed(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id))))
|
||||
}
|
||||
|
||||
fn layers_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, parent) = layers_scope(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = layer_ids(h, st, parent)?;
|
||||
let ids = layers_listed(h, st, parent)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
@@ -573,7 +647,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
if parent.is_none() {
|
||||
return Err(HostError::Error("a document needs at least one layer".into()));
|
||||
}
|
||||
let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent));
|
||||
let ids = with_doc(h, doc, |_, st| layers_listed(h, st, parent))?;
|
||||
// `layer.delete` takes at most this many rows; more is refused before anything is deleted.
|
||||
if ids.len() > crate::cmd::layer::MAX_ROWS {
|
||||
return Err(HostError::Range(format!("removeAll deletes at most {} layers at once", crate::cmd::layer::MAX_ROWS)));
|
||||
@@ -592,12 +666,12 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
|
||||
let Some(handle) = handle_of(d, class) else { return Err(type_error(class)) };
|
||||
match handle.as_slice() {
|
||||
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
|
||||
// A container's collection goes stale with the container when its document is reverted.
|
||||
[run, uid, high, low, reverts] => {
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
// A collection read before File › Revert is stale like its container.
|
||||
let holds = with_doc(h, doc, |_, st| {
|
||||
Some(st.reverts) == whole(*reverts)
|
||||
whole(*reverts) == Some(st.reverts)
|
||||
&& st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }))
|
||||
});
|
||||
if !holds {
|
||||
@@ -609,8 +683,8 @@ fn art_scope(h: &Host, d: &Data, class: &str) -> Result<(Doc, Option<NodeId>)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's uid, the document as it was, the [`Kind`] (or [`LAYER_LIST`]) and the container of
|
||||
/// an art or layer collection, and the ids it listed then.
|
||||
/// A document's uid, the document as it was, the [`Kind`] and the container of an art collection,
|
||||
/// and the ids it listed then.
|
||||
pub(super) type ArtList = (u64, Arc<Document>, u8, Option<NodeId>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// How many lists of art [`super::State`] keeps at once.
|
||||
@@ -621,44 +695,9 @@ pub(super) const ART_LISTS: usize = 4;
|
||||
/// their documents are unchanged, so a loop over groups that reads each group's `pageItems` builds
|
||||
/// each list once. Each new list is charged by the objects it looks at.
|
||||
fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
kept_list(h, st, kind as u8, container, || {
|
||||
Ok(match container {
|
||||
None => {
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect()
|
||||
}
|
||||
Some(c) => {
|
||||
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
|
||||
h.charge_call(children.len() as u64)?;
|
||||
children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The tag of a list of layers among the kept lists of art.
|
||||
const LAYER_LIST: u8 = u8::MAX;
|
||||
|
||||
/// The layers of `parent` (`None`: the top level), top first, kept as [`art_list`] keeps its
|
||||
/// lists. Each new list is charged by the rows it looks at.
|
||||
fn layer_ids(h: &Host, st: &DocState, parent: Option<NodeId>) -> Result<Rc<Vec<NodeId>>> {
|
||||
kept_list(h, st, LAYER_LIST, parent, || {
|
||||
let rows = match parent {
|
||||
None => Some(&st.doc.layers),
|
||||
Some(p) => st.doc.children(Some(p)),
|
||||
};
|
||||
h.charge_call(rows.map_or(0, Vec::len) as u64)?;
|
||||
Ok(layer_list(&st.doc, parent))
|
||||
})
|
||||
}
|
||||
|
||||
/// The list kept for `tag` and `container` while the document is unchanged, else the one `build`
|
||||
/// makes, which is kept in place of the least recently used one.
|
||||
fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option<NodeId>, build: impl FnOnce() -> Result<Vec<NodeId>>) -> Result<Rc<Vec<NodeId>>> {
|
||||
{
|
||||
let mut lists = h.dom.art.borrow_mut();
|
||||
let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == tag && *c == container);
|
||||
let at = lists.iter().position(|(uid, doc, k, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *k == kind as u8 && *c == container);
|
||||
if let Some(at) = at {
|
||||
let list = lists.remove(at);
|
||||
let ids = list.4.clone();
|
||||
@@ -666,25 +705,47 @@ fn kept_list(h: &Host, st: &DocState, tag: u8, container: Option<NodeId>, build:
|
||||
return Ok(ids);
|
||||
}
|
||||
}
|
||||
let ids = Rc::new(build()?);
|
||||
#[cfg(test)]
|
||||
super::ART_SCANS.with(|c| c.set(c.get() + 1));
|
||||
let ids: Vec<NodeId> = match container {
|
||||
None => {
|
||||
let all = page_items(h, st)?;
|
||||
h.charge_call(all.len() as u64)?;
|
||||
all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| kind.holds(n))).collect()
|
||||
}
|
||||
Some(c) => {
|
||||
let children: &[Arc<crate::doc::Node>] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice);
|
||||
h.charge_call(children.len() as u64)?;
|
||||
children.iter().rev().filter(|n| kind.holds(n)).map(|n| n.id).collect()
|
||||
}
|
||||
};
|
||||
let ids = Rc::new(ids);
|
||||
let mut lists = h.dom.art.borrow_mut();
|
||||
lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc));
|
||||
if lists.len() >= ART_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), tag, container, ids.clone()));
|
||||
lists.push((st.uid, st.doc.clone(), kind as u8, container, ids.clone()));
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// The `PageItems` of a layer, group or compound path: a [`super`] `PageItems` object whose handle
|
||||
/// names the container.
|
||||
pub(super) fn is_scoped(a: &[Data]) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == "PageItems" && handle.len() == 5)
|
||||
/// Whether a `PageItems` or `PathItems` object's handle names its container.
|
||||
pub(super) fn is_scoped(a: &[Data], class: &str) -> bool {
|
||||
host_ref_parts(arg(a, 0)).is_some_and(|(c, handle)| c == class && handle.len() == 5)
|
||||
}
|
||||
|
||||
fn scoped_kind(a: &[Data]) -> Kind {
|
||||
if host_ref_parts(arg(a, 0)).is_some_and(|(c, _)| c == "PathItems") { Kind::Path } else { Kind::Any }
|
||||
}
|
||||
|
||||
/// How many times File › Revert has reloaded the document with uid `uid`.
|
||||
fn reverts_of(h: &Host, uid: u64) -> u64 {
|
||||
h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts)
|
||||
}
|
||||
|
||||
fn collection(h: &Host, kind: Kind, container: Option<NodeId>, uid: u64) -> Data {
|
||||
match container {
|
||||
Some(c) => host_ref(kind.class(), &layer_handle(h, uid, c)),
|
||||
Some(c) => host_ref(kind.class(), &[float(h.run), float(uid), id_parts(c)[0], id_parts(c)[1], float(reverts_of(h, uid))]),
|
||||
None => host_ref(kind.class(), &[float(h.run), float(uid)]),
|
||||
}
|
||||
}
|
||||
@@ -700,40 +761,35 @@ fn art_parent(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
|
||||
}
|
||||
|
||||
/// `collection[i]`, and `collection["name"]` as `getByName` reads it, as the document's
|
||||
/// `pageItems` reads them: a name nothing has throws `Not found` (gives `undefined` for `in`), and
|
||||
/// the text of a number that is not an array index is looked up as a name, giving `undefined`
|
||||
/// when nothing has it.
|
||||
fn art_at(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
match arg(a, 1) {
|
||||
Data::String(name) => match art_named(h, doc, c, kind, name) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && matches!(arg(a, 2), Data::Bool(true)) => Ok(Data::Undefined),
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return match art_by_name(h, a, kind) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
Data::Number(n) => match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
|
||||
None => match art_named(h, doc, c, kind, &vectorcraft_js::number_to_string(*n)) {
|
||||
Err(HostError::Error(e)) if e == NOT_FOUND => Ok(Data::Undefined),
|
||||
r => r,
|
||||
},
|
||||
},
|
||||
_ => Ok(Data::Undefined),
|
||||
};
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
match whole(*n).filter(|i| *i < u64::from(u32::MAX)).and_then(|i| usize::try_from(i).ok()) {
|
||||
Some(i) => with_doc(h, doc, |_, st| Ok(art_list(h, st, kind, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id)))),
|
||||
// The text of a number that is not an array index is looked up as a name.
|
||||
None => with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let name = vectorcraft_js::number_to_string(*n);
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
Ok(id.map_or(Data::Undefined, |id| item_ref(h, st, *id)))
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
art_named(h, doc, c, kind, name)
|
||||
}
|
||||
|
||||
/// The first object named `name` in the art collection of `kind` in `c`.
|
||||
fn art_named(h: &Host, doc: Doc, c: Option<NodeId>, kind: Kind, name: &str) -> Answer {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let ids = art_list(h, st, kind, c)?;
|
||||
h.charge_call(ids.len() as u64)?;
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name));
|
||||
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
|
||||
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
})
|
||||
}
|
||||
@@ -760,7 +816,7 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
/// `pageItems.removeAll()` is stopped.
|
||||
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
|
||||
let all = art_list(h, st, kind, c)?;
|
||||
let d = &st.doc;
|
||||
let listed: std::collections::HashSet<NodeId> = all.iter().copied().collect();
|
||||
@@ -770,7 +826,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
|
||||
let locks = d.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked))
|
||||
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
|
||||
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
|
||||
let masks: Vec<u64> = ids
|
||||
.iter()
|
||||
.filter(|i| {
|
||||
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
|
||||
let kids = p.children().map_or(&[][..], Vec::as_slice);
|
||||
p.clips()
|
||||
&& kids.first().is_some_and(|f| f.id == **i)
|
||||
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
|
||||
})
|
||||
})
|
||||
.map(|i| i.0)
|
||||
.take(20)
|
||||
.collect();
|
||||
Ok::<_, HostError>((ids, refused, on_locked, masks))
|
||||
})?;
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
@@ -780,42 +851,41 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
|
||||
}
|
||||
if !masks.is_empty() {
|
||||
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!(
|
||||
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
|
||||
)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
// The container stays, empty, as a compound path whose last path `remove()` takes out does.
|
||||
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": c.is_some()});
|
||||
// A deletion that takes a clipping path releases its clip group's or clipping layer's mask,
|
||||
// so neither the object above it nor one added later is made the clipping path. A deletion
|
||||
// that leaves the clipping path keeps the mask.
|
||||
let released = with_doc(h, doc, |_, st| super::masks_cleared_by(&st.doc, &ids));
|
||||
on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, ¶ms))?;
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The scoped `PageItems` of a container, which `PageItems`' members hand over to when their
|
||||
/// handle names one ([`is_scoped`]).
|
||||
/// The scoped art of a container, read by `PageItems` and `PathItems` ([`is_scoped`]).
|
||||
pub(super) fn scoped_length(h: &Host, a: &[Data]) -> Answer {
|
||||
art_length(h, a, Kind::Any)
|
||||
art_length(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
pub(super) fn scoped_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
art_parent(h, a, Kind::Any)
|
||||
art_parent(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
pub(super) fn scoped_at(h: &Host, a: &[Data]) -> Answer {
|
||||
art_at(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
|
||||
art_index(h, a, Kind::Any)
|
||||
art_at(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
pub(super) fn scoped_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
art_by_name(h, a, Kind::Any)
|
||||
art_by_name(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
pub(super) fn scoped_index(h: &Host, a: &[Data]) -> Answer {
|
||||
art_index(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
pub(super) fn scoped_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
art_remove_all(h, a, Kind::Any)
|
||||
art_remove_all(h, a, scoped_kind(a))
|
||||
}
|
||||
|
||||
fn groups_length(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -861,7 +931,7 @@ fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer {
|
||||
}
|
||||
|
||||
pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, Kind::Any)
|
||||
art_typename(h, a, scoped_kind(a))
|
||||
}
|
||||
fn groups_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
art_typename(h, a, Kind::Group)
|
||||
@@ -924,6 +994,10 @@ fn held_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Any)
|
||||
}
|
||||
|
||||
fn held_paths(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Path)
|
||||
}
|
||||
|
||||
fn held_groups(h: &Host, a: &[Data]) -> Answer {
|
||||
held(h, a, Kind::Group)
|
||||
}
|
||||
@@ -977,11 +1051,10 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
|
||||
if now == on {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
super::refuse_protected_edit(h, item)?;
|
||||
if !ok {
|
||||
return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0)));
|
||||
}
|
||||
// A group on a locked artboard keeps its mask, as its other properties do.
|
||||
super::refuse_protected_edit(h, item)?;
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, "layer.clippingMask.toggle", &json!({"id": item.id.0})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
@@ -991,11 +1064,6 @@ pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![("layer", get(l, item_layer), typed("Layer"))])
|
||||
}
|
||||
|
||||
/// A collection's type for `reflect`.
|
||||
fn listed(data_type: &str) -> MemberInfo {
|
||||
MemberInfo { collection: true, ..typed(data_type) }
|
||||
}
|
||||
|
||||
/// The members a page item class adds to `PageItem`'s.
|
||||
pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
|
||||
match class {
|
||||
@@ -1010,11 +1078,16 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
|
||||
m.extend(["pathItems", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m)));
|
||||
m
|
||||
}
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items), listed("PageItems"))]),
|
||||
"CompoundPathItem" => named(vec![("pathItems", get(l, held_paths), listed("PathItems"))]),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// What `reflect` tells of a member whose value is a collection of class `data_type`.
|
||||
fn listed(data_type: &str) -> MemberInfo {
|
||||
MemberInfo { collection: true, ..typed(data_type) }
|
||||
}
|
||||
|
||||
// ---- Document ----
|
||||
|
||||
fn doc_layers(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1074,15 +1147,14 @@ fn board_of(h: &Host, d: &Data) -> Result<(Board, usize)> {
|
||||
let [run, uid, id, reverts] = handle.as_slice() else { return Err(type_error("Artboard")) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
let id = whole(*id).and_then(|i| u32::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
// An artboard read before its document was reverted is stale, as its layers are.
|
||||
let index = with_doc(h, doc, |_, st| (Some(st.reverts) == whole(*reverts)).then(|| board_index(st, id)).flatten())
|
||||
// An artboard read before File › Revert is stale, as the page items read with it are.
|
||||
let index = with_doc(h, doc, |_, st| board_index(st, id).filter(|_| whole(*reverts) == Some(st.reverts)))
|
||||
.ok_or_else(|| HostError::Error(STALE_ARTBOARD.into()))?;
|
||||
Ok((Board { doc }, index))
|
||||
}
|
||||
|
||||
fn board_ref(h: &Host, uid: u64, id: u32) -> Data {
|
||||
let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts);
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts)])
|
||||
host_ref("Artboard", &[float(h.run), float(uid), f64::from(id), float(reverts_of(h, uid))])
|
||||
}
|
||||
|
||||
fn this_board(h: &Host, a: &[Data]) -> Result<(Board, usize)> {
|
||||
@@ -1188,6 +1260,10 @@ fn board_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Artboard"))
|
||||
}
|
||||
|
||||
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
named_text("Artboard", board_name(h, a))
|
||||
}
|
||||
|
||||
/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner
|
||||
/// with Y down.
|
||||
fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1274,6 +1350,24 @@ fn boards_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("Artboards"))
|
||||
}
|
||||
|
||||
/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`.
|
||||
fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
layers_scope(h, arg(a, 0))?;
|
||||
Ok(text("[Layers]"))
|
||||
}
|
||||
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
art_scope(h, arg(a, 0), Kind::Group.class())?;
|
||||
Ok(text("[GroupItems]"))
|
||||
}
|
||||
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
art_scope(h, arg(a, 0), Kind::Compound.class())?;
|
||||
Ok(text("[CompoundPathItems]"))
|
||||
}
|
||||
fn boards_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
boards_doc(h, a)?;
|
||||
Ok(text("[Artboards]"))
|
||||
}
|
||||
|
||||
/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`).
|
||||
fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
|
||||
let n = number(d, what)?;
|
||||
@@ -1285,6 +1379,9 @@ fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
|
||||
|
||||
fn boards_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
if let Data::String(_) = arg(a, 1) {
|
||||
return read_by_name(h, a, boards_by_name);
|
||||
}
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) };
|
||||
Ok(with_doc(h, doc, |_, st| st.doc.artboards.get(i).map_or(Data::Undefined, |ab| board_ref(h, st.uid, ab.id))))
|
||||
@@ -1351,7 +1448,7 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer {
|
||||
add_board(h, a, None)
|
||||
}
|
||||
|
||||
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → `undefined`.
|
||||
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing.
|
||||
fn boards_insert(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(arg(a, 2), Data::Undefined) {
|
||||
return Err(HostError::Type("insert needs an index".into()));
|
||||
@@ -1374,22 +1471,36 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the
|
||||
/// document changes, and no command runs.
|
||||
/// document changes, and no command runs. The artboard is kept by its id even when it is already
|
||||
/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later
|
||||
/// in the run moves it to the next index instead of taking its place.
|
||||
fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = boards_doc(h, a)?;
|
||||
let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st)));
|
||||
let i = board_index_arg(arg(a, 1), len, "index")?;
|
||||
// The artboard's id is stored on every call, so an artboard inserted before it later does not
|
||||
// change which artboard is active.
|
||||
{
|
||||
let mut s = h.session.borrow_mut();
|
||||
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
|
||||
}
|
||||
// A document the run opened is reported whenever an artboard is chosen in it, since the report
|
||||
// has no start index for it to compare with.
|
||||
let new_doc = !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid);
|
||||
if i != now || new_doc {
|
||||
{
|
||||
let mut chosen = h.dom.chosen_artboards.borrow_mut();
|
||||
let reverts = reverts_of(h, doc.uid);
|
||||
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
|
||||
*generation = reverts;
|
||||
} else {
|
||||
chosen.push((doc.uid, reverts));
|
||||
}
|
||||
}
|
||||
// A document made during the run has no index from the start of the run, so the first choice
|
||||
// records one; an artboard inserted before it later still puts it in the report.
|
||||
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
|
||||
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
|
||||
if !made.iter().any(|(uid, _)| *uid == doc.uid) {
|
||||
made.push((doc.uid, i));
|
||||
}
|
||||
}
|
||||
if i != now {
|
||||
let mut moved = h.dom.active_artboards.borrow_mut();
|
||||
if !moved.contains(&doc.uid) {
|
||||
moved.push(doc.uid);
|
||||
@@ -1432,8 +1543,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("printable", property(l, layer_printable, layer_set_printable), typed("boolean")),
|
||||
("preview", property(l, layer_preview, layer_set_preview), typed("boolean")),
|
||||
("dimPlacedImages", property(l, layer_dim, layer_set_dim), typed("boolean")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("color", property(l, layer_color, layer_set_color), typed("*")),
|
||||
("opacity", property(l, layer_opacity, layer_set_opacity), typed("number")),
|
||||
("color", property(l, layer_color, layer_set_color), typed("RGBColor")),
|
||||
("parent", get(l, layer_parent), typed("*")),
|
||||
("layers", get(l, layers_of), listed("Layers")),
|
||||
("pageItems", get(l, held_page_items), listed("PageItems")),
|
||||
@@ -1464,6 +1575,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])),
|
||||
("add", method(l, layers_add), returns("Layer", &[])),
|
||||
("removeAll", method(l, layers_remove_all), returns("undefined", &[])),
|
||||
("toString", method(l, layers_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(super::function(l, layers_at)),
|
||||
),
|
||||
@@ -1479,6 +1591,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])),
|
||||
("add", method(l, groups_add), returns("GroupItem", &[])),
|
||||
("removeAll", method(l, groups_remove_all), returns("undefined", &[])),
|
||||
("toString", method(l, groups_to_string), returns("string", &[])),
|
||||
]);
|
||||
m.push(later(l, "GroupItems", "createFromFile"));
|
||||
m
|
||||
@@ -1496,6 +1609,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])),
|
||||
("add", method(l, compounds_add), returns("CompoundPathItem", &[])),
|
||||
("removeAll", method(l, compounds_remove_all), returns("undefined", &[])),
|
||||
("toString", method(l, compounds_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(super::function(l, compounds_at)),
|
||||
),
|
||||
@@ -1513,6 +1627,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("showCrossHairs", property(l, board_cross_hairs, board_set_cross_hairs), typed("boolean")),
|
||||
("showSafeAreas", property(l, board_safe_areas, board_set_safe_areas), typed("boolean")),
|
||||
("remove", method(l, board_remove), returns("undefined", &[])),
|
||||
("toString", method(l, board_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
@@ -1530,6 +1645,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])),
|
||||
("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])),
|
||||
("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])),
|
||||
("toString", method(l, boards_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(super::function(l, boards_at)),
|
||||
),
|
||||
|
||||
@@ -397,21 +397,33 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
|
||||
}
|
||||
doc_of(h, arg(a, 0), "PathItems")
|
||||
}
|
||||
|
||||
/// `typename` of the paths of a document that is still open.
|
||||
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_typename(h, a);
|
||||
}
|
||||
items_doc(h, a)?;
|
||||
Ok(Data::String("PathItems".into()))
|
||||
}
|
||||
|
||||
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_length(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
|
||||
}
|
||||
|
||||
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_parent(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
@@ -420,6 +432,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
|
||||
/// looked up as that name, giving `undefined` when no path has it.
|
||||
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_at(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => match items_by_name(h, a) {
|
||||
@@ -443,6 +458,9 @@ fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
|
||||
}
|
||||
|
||||
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_by_name(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
items_named(h, doc, name)
|
||||
@@ -459,6 +477,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
|
||||
}
|
||||
|
||||
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_index(h, a);
|
||||
}
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => items_by_name(h, a),
|
||||
Data::Number(n) => {
|
||||
@@ -476,6 +497,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
|
||||
if super::layers::is_scoped(a, "PathItems") {
|
||||
return super::layers::scoped_remove_all(h, a);
|
||||
}
|
||||
let doc = items_doc(h, a)?;
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
@@ -1813,8 +1837,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, items_typename), typed("string")),
|
||||
("toString", super::class_text("PathItems"), returns("string", &[])),
|
||||
("length", get(l, items_length), typed("number")),
|
||||
("parent", get(l, items_parent), typed("Document")),
|
||||
("parent", get(l, items_parent), typed("*")),
|
||||
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
|
||||
@@ -2431,7 +2431,7 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::new(heap_bytes, self.documents()),
|
||||
dom: dom::State::new(self.documents(), heap_bytes),
|
||||
actions: request.actions,
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
@@ -2748,7 +2748,8 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) {
|
||||
let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect();
|
||||
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
|
||||
report["activeArtboards"] = boards;
|
||||
}
|
||||
// The run ran a Copy or Cut, and the clipboard still holds what one put there.
|
||||
|
||||
Reference in new issue
Block a user