mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into feat/scripts-scriptui-resources
This commit is contained in:
commit
ab6a0d44aa
345 files changed
+23508
-1980
No files matched your search
+396
-107
@@ -6,9 +6,10 @@
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describe them.
|
||||
//!
|
||||
//! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the
|
||||
//! document's [`crate::DocState::uid`] and, for art, the object's id, and every read looks the
|
||||
//! document and the object up again. An object that was deleted, a document that was closed and an
|
||||
//! object from an earlier run of a named engine throw an error on every member. Every change runs
|
||||
//! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's
|
||||
//! [`crate::DocState::reverts`], and every read looks the document and the
|
||||
//! object up again. An object that was deleted, a document that was closed, an object from before
|
||||
//! File › Revert and an object from an earlier run of a named engine throw an error on every member. Every change runs
|
||||
//! a command, as `vc.run` does, so it joins the run's transaction and its one undo step for each
|
||||
//! changed document; a change that changes nothing runs no command. A change to a document that is
|
||||
//! not the active one makes it active for the command and makes the other one active again after.
|
||||
@@ -29,7 +30,8 @@
|
||||
//! false then. Assigning to such a name throws the same error.
|
||||
//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the
|
||||
//! active document's selection. A top-level `var selection = ...` does the same and does
|
||||
//! not make a variable of the script. Assigning `documents` keeps its value.
|
||||
//! not make a variable of the script. An assignment to `documents` is ignored outside strict
|
||||
//! mode and throws a `TypeError` in strict mode code or with `#strict on`.
|
||||
//! - 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
|
||||
@@ -41,8 +43,11 @@
|
||||
//! - Enumerated values are strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
//! - `app.activeDocument` with no document open throws `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so.
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
//! object in a hidden or locked layer, and `zOrder()` on one, throw `Cannot edit` and change
|
||||
//! nothing, even for the value the object has. The exception is `opacity` given the value the
|
||||
@@ -54,6 +59,10 @@
|
||||
//! - A compound path whose last path `move` or `remove()` takes out stays, empty.
|
||||
//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out,
|
||||
//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing.
|
||||
//! - `reflect` on an object or a class gives each member's type from the declaration that installs
|
||||
//! the member ([`classes`]): a class name, `boolean`, `number`, `string`, `Array` for a list of
|
||||
//! numbers, the enumeration's name for an enumerated value, and `*` where the value can be of
|
||||
//! more than one type.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
@@ -62,12 +71,28 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts};
|
||||
use vectorcraft_js::{
|
||||
ArgInfo, Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref, host_ref_parts,
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
|
||||
mod tags;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
|
||||
/// What [`after_command`] compares with, taken before each command a script runs
|
||||
/// ([`variables::before_command`]).
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<crate::doc::DataSet>)> {
|
||||
variables::before_command(h, id)
|
||||
}
|
||||
|
||||
/// After each command a script runs ([`variables::after_command`]).
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataSet>)>) {
|
||||
variables::after_command(h, before);
|
||||
}
|
||||
|
||||
/// The error for a member read or called with no document open.
|
||||
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
|
||||
@@ -118,7 +143,9 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
/// 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, whether a call's own savepoint ([`atomically`]) is
|
||||
/// open, and the settings of each `DocumentPreset` the run made.
|
||||
/// open, the settings of each `DocumentPreset` the run made, with the size of the values they hold
|
||||
/// now and the most they may hold (the run's heap), and the `Variable` and `Dataset` objects it
|
||||
/// gave out.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
@@ -126,9 +153,17 @@ pub(super) struct State {
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// The state of a run whose heap is `heap_bytes`.
|
||||
pub(super) fn new(heap_bytes: usize) -> Self {
|
||||
Self { preset_limit: heap_bytes as u64, ..Self::default() }
|
||||
}
|
||||
|
||||
/// Whether a call's own savepoint is open: its commands take none of their own.
|
||||
pub(super) fn saving(&self) -> bool {
|
||||
self.saving.get()
|
||||
@@ -137,20 +172,25 @@ impl State {
|
||||
|
||||
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
|
||||
/// document, the selection and the undo histories are as they were before it, with no undo step
|
||||
/// and no change to the document's saved state.
|
||||
/// and no change to the document's saved state, and the growth its commands were charged is not
|
||||
/// counted.
|
||||
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
|
||||
if h.dom.saving.get() {
|
||||
return f(h);
|
||||
}
|
||||
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
|
||||
let mark = h.growth_mark();
|
||||
h.dom.saving.set(true);
|
||||
let r = f(h);
|
||||
h.dom.saving.set(false);
|
||||
let mut s = h.session.borrow_mut();
|
||||
if r.is_ok() {
|
||||
save.keep(&mut s);
|
||||
} else if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
} else {
|
||||
h.put_growth_back(mark);
|
||||
if !save.restore(&mut s) {
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
r
|
||||
}
|
||||
@@ -235,10 +275,24 @@ fn method(link: &Link, f: Member) -> HostMember {
|
||||
HostMember::Method(function(link, f))
|
||||
}
|
||||
|
||||
/// A member of a class with what `reflect` tells of it.
|
||||
type Described = (String, HostMember, MemberInfo);
|
||||
|
||||
/// A property's or a method's result's type for `reflect`.
|
||||
fn typed(data_type: &str) -> MemberInfo {
|
||||
MemberInfo { data_type: data_type.into(), ..MemberInfo::default() }
|
||||
}
|
||||
|
||||
/// A method's result's type and its arguments' names and types, for `reflect`.
|
||||
fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo {
|
||||
let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect();
|
||||
MemberInfo { arguments, ..typed(data_type) }
|
||||
}
|
||||
|
||||
/// A member the help pages list that is not available yet: reading or assigning it throws, after
|
||||
/// the check that a document or page item `this` is still there. `hasOwnProperty` is false for it,
|
||||
/// so a script that checks for the member first skips it.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) {
|
||||
/// so a script that checks for the member first skips it, and `reflect` leaves it out.
|
||||
fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
|
||||
let message = format!("{class}.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
@@ -255,7 +309,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM
|
||||
}
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f))
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
fn text(s: impl Into<String>) -> Data {
|
||||
@@ -368,12 +422,27 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result<Doc, HostError
|
||||
}
|
||||
}
|
||||
|
||||
fn node_handle(h: &Host, st: &DocState, id: NodeId) -> [f64; 5] {
|
||||
let [high, low] = id_parts(id);
|
||||
[float(h.run), float(st.uid), high, low, float(st.reverts)]
|
||||
}
|
||||
|
||||
fn node_of(h: &Host, handle: &[f64]) -> Option<(Doc, NodeId)> {
|
||||
let &[run, uid, high, low, reverts] = handle else { return None };
|
||||
let doc = find_doc(h, run, uid)?;
|
||||
if h.session.borrow().documents().get(doc.index)?.reverts != whole(reverts)? {
|
||||
return None;
|
||||
}
|
||||
Some((doc, id_of(high, low)?))
|
||||
}
|
||||
|
||||
/// The page item `d` names, which must still be in its document.
|
||||
fn item_of(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) };
|
||||
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()))?;
|
||||
if handle.len() != 5 {
|
||||
return Err(HostError::Type("this is not a page item".into()));
|
||||
}
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let s = h.session.borrow();
|
||||
let st = &s.documents()[doc.index];
|
||||
if st.doc.node(id).is_none_or(|n| typename(n).is_none()) {
|
||||
@@ -410,8 +479,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data {
|
||||
fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
match st.doc.node(id) {
|
||||
Some(n) => match typename(n) {
|
||||
Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
|
||||
None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]),
|
||||
Some(t) => host_ref(t, &node_handle(h, st, id)),
|
||||
None => host_ref("Layer", &node_handle(h, st, id)),
|
||||
},
|
||||
None => Data::Null,
|
||||
}
|
||||
@@ -572,6 +641,8 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) -
|
||||
.map(|i| {
|
||||
let anchors: Vec<[usize; 2]> = match before.anchors.get(i) {
|
||||
Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(),
|
||||
// A path with only segments selected gets them back below, with no anchors.
|
||||
None if before.segments.contains_key(i) => Vec::new(),
|
||||
None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(),
|
||||
};
|
||||
json!({"id": i.0, "anchors": anchors})
|
||||
@@ -1150,17 +1221,42 @@ fn new_preset(h: &Host) -> Answer {
|
||||
return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets")));
|
||||
}
|
||||
let item = |k: &str, v: Data| (k.to_string(), v);
|
||||
presets.push(vec![
|
||||
let fields = vec![
|
||||
item("artboardLayout", text("DocumentArtboardLayout.GridByRow")),
|
||||
item("artboardRowsOrCols", num(1.0)),
|
||||
item("artboardSpacing", num(20.0)),
|
||||
item("height", num(792.0)),
|
||||
item("numArtboards", num(1.0)),
|
||||
item("width", num(612.0)),
|
||||
]);
|
||||
];
|
||||
hold_preset_bytes(h, 0, fields.iter().map(|(_, v)| held_bytes(v)).sum())?;
|
||||
presets.push(fields);
|
||||
Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)]))
|
||||
}
|
||||
|
||||
/// Counts that the run's presets now hold `added` bytes of values in place of `replaced`, and
|
||||
/// refuses when they would hold more than the run's heap.
|
||||
fn hold_preset_bytes(h: &Host, replaced: u64, added: u64) -> std::result::Result<(), HostError> {
|
||||
let total = h.dom.preset_bytes.get().saturating_sub(replaced).saturating_add(added);
|
||||
if total > h.dom.preset_limit {
|
||||
return Err(HostError::Range(format!("the DocumentPreset settings would hold more than {} bytes", h.dom.preset_limit)));
|
||||
}
|
||||
h.dom.preset_bytes.set(total);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The bytes the host's copy of `d` takes: a `Data` for the value and each element or property
|
||||
/// in it, plus the text of its strings and property names.
|
||||
fn held_bytes(d: &Data) -> u64 {
|
||||
let owned = match d {
|
||||
Data::String(s) => s.len() as u64,
|
||||
Data::Array(a) => a.iter().map(held_bytes).sum(),
|
||||
Data::Object(o) => o.iter().map(|(k, v)| (size_of::<String>() + k.len()) as u64 + held_bytes(v)).sum(),
|
||||
Data::Undefined | Data::Null | Data::Bool(_) | Data::Number(_) => 0,
|
||||
};
|
||||
size_of::<Data>() as u64 + owned
|
||||
}
|
||||
|
||||
/// The most `DocumentPreset` objects one run can make.
|
||||
const MAX_PRESETS: usize = 10_000;
|
||||
|
||||
@@ -1267,8 +1363,12 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
check_preset_value(key, &value)?;
|
||||
let mut presets = h.dom.presets.borrow_mut();
|
||||
let fields = &mut presets[i];
|
||||
match fields.iter_mut().find(|(k, _)| k == key) {
|
||||
Some((_, v)) => *v = value,
|
||||
// The values the presets hold now count against the run's heap: a value assigned again
|
||||
// replaces the one before it.
|
||||
let at = fields.iter().position(|(k, _)| k == key);
|
||||
hold_preset_bytes(&h, at.map_or(0, |n| held_bytes(&fields[n].1)), held_bytes(&value))?;
|
||||
match at {
|
||||
Some(n) => fields[n].1 = value,
|
||||
None => fields.push((key.to_string(), value)),
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
@@ -1416,10 +1516,12 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
}
|
||||
|
||||
/// The ids an assignment to a document's selection gives: one page item, a list of them, `null` or
|
||||
/// `[]`. Every one must be an object of that document that can be selected.
|
||||
/// `[]`. Every one must be an object of that document that can be selected. `undefined`, such as
|
||||
/// an index past the end of `pageItems`, is refused and clears nothing.
|
||||
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
let list: Vec<&Data> = match v {
|
||||
Data::Null => Vec::new(),
|
||||
Data::Undefined => return Err(HostError::Type("a selection is a page item, a list of them, null or []".into())),
|
||||
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
|
||||
Data::Array(a) => a.iter().collect(),
|
||||
d => vec![d],
|
||||
@@ -1440,6 +1542,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item"));
|
||||
return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0)));
|
||||
}
|
||||
// Repeated objects are kept once.
|
||||
if seen.insert(item.id) {
|
||||
ids.push(item.id);
|
||||
}
|
||||
@@ -1778,6 +1881,26 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
|
||||
bounds(h, a, true)
|
||||
}
|
||||
|
||||
/// `controlBounds`: the visible bounds, widened to take in the direction points of every path in
|
||||
/// the object.
|
||||
fn item_control(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
// An object with nothing in it reads zeros, as its other bounds do.
|
||||
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
|
||||
let r = with_doc(h, item.doc, |_, st| {
|
||||
let mut r = r;
|
||||
if let Some(n) = st.doc.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
if let Some(handles) = c.path_data().and_then(vectorcraft_geom::PathData::control_bounds) {
|
||||
r = r.union(handles);
|
||||
}
|
||||
});
|
||||
}
|
||||
r
|
||||
});
|
||||
Ok(f.bounds(h.dom.coords.get(), r))
|
||||
}
|
||||
|
||||
fn item_position(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
match item_rect(h, item, false)? {
|
||||
@@ -1958,17 +2081,16 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::
|
||||
let how = placement_of(how)?;
|
||||
let beside = matches!(how, Placement::Above | Placement::Below);
|
||||
let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer"));
|
||||
let Some(&[run, uid, high, low]) = handle.as_deref() else {
|
||||
let Some(handle) = handle.filter(|parts| parts.len() == 5) else {
|
||||
if handle_of(target, "Document").is_some() {
|
||||
return Err(HostError::Error("a document as the relative object is not available yet".into()));
|
||||
}
|
||||
return Err(HostError::Type("the relative object must be a page item or a layer".into()));
|
||||
};
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let (doc, target) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
if doc.uid != item.doc.uid {
|
||||
return Err(HostError::Error(CROSS_DOCUMENT.into()));
|
||||
}
|
||||
let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
with_doc(h, doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
@@ -2134,9 +2256,9 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn layer_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX));
|
||||
let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
|
||||
find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
|
||||
}
|
||||
|
||||
@@ -2174,12 +2296,30 @@ fn typename_of(name: &'static str) -> HostMember {
|
||||
HostMember::Get(Rc::new(move |_| Ok(text(name))))
|
||||
}
|
||||
|
||||
fn class(name: &str, parent: Option<&str>, members: Vec<(String, HostMember)>, index: Option<HostFunction>) -> HostClass {
|
||||
HostClass { name: name.into(), parent: parent.map(Into::into), members, index, construct: None }
|
||||
fn class(name: &str, parent: Option<&str>, members: Vec<Described>, index: Option<HostFunction>) -> HostClass {
|
||||
let info = members.iter().map(|(n, _, i)| (n.clone(), i.clone())).collect();
|
||||
let members = members.into_iter().map(|(n, m, _)| (n, m)).collect();
|
||||
HostClass { name: name.into(), parent: parent.map(Into::into), members, info, index, construct: None }
|
||||
}
|
||||
|
||||
fn named(items: Vec<(&str, HostMember)>) -> Vec<(String, HostMember)> {
|
||||
items.into_iter().map(|(n, m)| (n.to_string(), m)).collect()
|
||||
fn named(items: Vec<(&str, HostMember, MemberInfo)>) -> Vec<Described> {
|
||||
items.into_iter().map(|(n, m, i)| (n.to_string(), m, i)).collect()
|
||||
}
|
||||
|
||||
/// The type of a `DocumentPreset` field's value.
|
||||
fn preset_type(field: &str) -> &'static str {
|
||||
match field {
|
||||
"artboardLayout" => "DocumentArtboardLayout",
|
||||
"colorMode" => "DocumentColorSpace",
|
||||
"documentBleedLink" => "boolean",
|
||||
"documentBleedOffsetRect" => "Array",
|
||||
"previewMode" => "DocumentPreviewMode",
|
||||
"rasterResolution" => "DocumentRasterResolution",
|
||||
"title" => "string",
|
||||
"transparencyGrid" => "DocumentTransparencyGrid",
|
||||
"units" => "RulerUnits",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
/// The enumerations, as frozen objects whose members are `"Name.MEMBER"` strings.
|
||||
@@ -2216,16 +2356,30 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
variables::define_enums(realm)?;
|
||||
realm.define_host_classes(classes(link), vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
let l = link;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
realm.define_host_globals(vec![
|
||||
("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))),
|
||||
("documents".into(), function(l, app_documents), None),
|
||||
("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))),
|
||||
])
|
||||
}
|
||||
|
||||
/// The classes of the object model, each member with the type `reflect` gives for it.
|
||||
fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let l = link;
|
||||
let placement = [("relativeObject", "*"), ("insertionLocation", "ElementPlacement")];
|
||||
let mut application = named(vec![
|
||||
("typename", typename_of("Application")),
|
||||
("documents", get(l, app_documents)),
|
||||
("activeDocument", property(l, app_active, app_set_active)),
|
||||
("selection", property(l, app_selection, app_set_selection)),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords)),
|
||||
("getIsFileOpen", method(l, app_is_open)),
|
||||
("executeMenuCommand", method(l, app_menu_command)),
|
||||
("toString", class_text("Application")),
|
||||
("typename", typename_of("Application"), typed("string")),
|
||||
("documents", get(l, app_documents), MemberInfo { collection: true, ..typed("Documents") }),
|
||||
("activeDocument", property(l, app_active, app_set_active), typed("Document")),
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
let preset = {
|
||||
@@ -2235,9 +2389,12 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
h.charge_call(64)?;
|
||||
new_preset(&h)
|
||||
});
|
||||
let mut members = vec![("typename".to_string(), typename_of("DocumentPreset")), ("toString".to_string(), class_text("DocumentPreset"))];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k))));
|
||||
HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) }
|
||||
let mut members = vec![
|
||||
("typename".to_string(), typename_of("DocumentPreset"), typed("string")),
|
||||
("toString".to_string(), class_text("DocumentPreset"), returns("string", &[])),
|
||||
];
|
||||
members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k), typed(preset_type(k)))));
|
||||
HostClass { construct: Some(f), ..class("DocumentPreset", None, members, None) }
|
||||
};
|
||||
let mut classes = vec![
|
||||
class("Application", None, application, None),
|
||||
@@ -2246,78 +2403,108 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
"Documents",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of("Documents")),
|
||||
("length", get(l, docs_length)),
|
||||
("parent", get(l, app_ref)),
|
||||
("index", method(l, docs_index)),
|
||||
("getByName", method(l, docs_by_name)),
|
||||
("add", method(l, docs_add)),
|
||||
("addDocument", method(l, docs_add_document)),
|
||||
("toString", class_text("Documents")),
|
||||
("typename", typename_of("Documents"), typed("string")),
|
||||
("length", get(l, docs_length), typed("number")),
|
||||
("parent", get(l, app_ref), typed("Application")),
|
||||
("index", method(l, docs_index), returns("Document", &[("itemKey", "*")])),
|
||||
("getByName", method(l, docs_by_name), returns("Document", &[("name", "string")])),
|
||||
(
|
||||
"add",
|
||||
method(l, docs_add),
|
||||
returns(
|
||||
"Document",
|
||||
&[
|
||||
("colorSpace", "DocumentColorSpace"),
|
||||
("width", "number"),
|
||||
("height", "number"),
|
||||
("numArtBoards", "number"),
|
||||
("artboardLayout", "DocumentArtboardLayout"),
|
||||
("artboardSpacing", "number"),
|
||||
("artboardRowsOrCols", "number"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"addDocument",
|
||||
method(l, docs_add_document),
|
||||
returns("Document", &[("startupPreset", "string"), ("presetSettings", "DocumentPreset"), ("showOptionsDialog", "boolean")]),
|
||||
),
|
||||
("toString", class_text("Documents"), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, docs_at)),
|
||||
),
|
||||
];
|
||||
let mut document = named(vec![
|
||||
("typename", get(l, doc_typename)),
|
||||
("parent", get(l, doc_parent)),
|
||||
("name", get(l, doc_name)),
|
||||
("width", get(l, doc_width)),
|
||||
("height", get(l, doc_height)),
|
||||
("rulerUnits", get(l, doc_units)),
|
||||
("documentColorSpace", get(l, doc_color_space)),
|
||||
("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin)),
|
||||
("convertCoordinate", method(l, doc_convert)),
|
||||
("pageItems", get(l, doc_page_items)),
|
||||
("selection", property(l, doc_selection, doc_set_selection)),
|
||||
("toString", method(l, doc_to_string)),
|
||||
("typename", get(l, doc_typename), typed("string")),
|
||||
("parent", get(l, doc_parent), typed("Application")),
|
||||
("name", get(l, doc_name), typed("string")),
|
||||
("width", get(l, doc_width), typed("number")),
|
||||
("height", get(l, doc_height), typed("number")),
|
||||
("rulerUnits", get(l, doc_units), typed("RulerUnits")),
|
||||
("documentColorSpace", get(l, doc_color_space), typed("DocumentColorSpace")),
|
||||
("rulerOrigin", property(l, doc_ruler_origin, doc_set_ruler_origin), typed("Array")),
|
||||
(
|
||||
"convertCoordinate",
|
||||
method(l, doc_convert),
|
||||
returns("Array", &[("point", "Array"), ("source", "CoordinateSystem"), ("destination", "CoordinateSystem")]),
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.push(("tags".into(), get(l, tags::doc_tags)));
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, items_typename)),
|
||||
("length", get(l, items_length)),
|
||||
("parent", get(l, items_parent)),
|
||||
("index", method(l, items_index)),
|
||||
("getByName", method(l, items_by_name)),
|
||||
("removeAll", method(l, items_remove_all)),
|
||||
("toString", method(l, items_to_string)),
|
||||
("typename", get(l, items_typename), typed("string")),
|
||||
("length", get(l, items_length), typed("number")),
|
||||
("parent", get(l, items_parent), typed("Document")),
|
||||
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
("toString", method(l, items_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
let mut page_item = named(vec![
|
||||
("typename", get(l, item_typename)),
|
||||
("parent", get(l, item_parent)),
|
||||
("name", property(l, item_name, item_set_name)),
|
||||
("note", property(l, item_note, item_set_note)),
|
||||
("tags", get(l, tags::item_tags)),
|
||||
("hidden", property(l, item_hidden, item_set_hidden)),
|
||||
("locked", property(l, item_locked, item_set_locked)),
|
||||
("selected", property(l, item_selected, item_set_selected)),
|
||||
("opacity", property(l, item_opacity, item_set_opacity)),
|
||||
("position", property(l, item_position, item_set_position)),
|
||||
("left", property(l, item_left, item_set_left)),
|
||||
("top", property(l, item_top, item_set_top)),
|
||||
("width", property(l, item_width, item_set_width)),
|
||||
("height", property(l, item_height, item_set_height)),
|
||||
("geometricBounds", get(l, item_geometric)),
|
||||
("visibleBounds", get(l, item_visible)),
|
||||
("controlBounds", get(l, item_visible)),
|
||||
("editable", get(l, item_editable)),
|
||||
("zOrderPosition", get(l, item_z_order_position)),
|
||||
("duplicate", method(l, item_duplicate)),
|
||||
("move", method(l, item_move)),
|
||||
("remove", method(l, item_remove)),
|
||||
("zOrder", method(l, item_z_order)),
|
||||
("toString", method(l, item_to_string)),
|
||||
("typename", get(l, item_typename), typed("string")),
|
||||
("parent", get(l, item_parent), typed("*")),
|
||||
("name", property(l, item_name, item_set_name), typed("string")),
|
||||
("note", property(l, item_note, item_set_note), typed("string")),
|
||||
("tags", get(l, tags::item_tags), MemberInfo { collection: true, ..typed("Tags") }),
|
||||
("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")),
|
||||
("locked", property(l, item_locked, item_set_locked), typed("boolean")),
|
||||
("selected", property(l, item_selected, item_set_selected), typed("boolean")),
|
||||
("opacity", property(l, item_opacity, item_set_opacity), MemberInfo { min: Some(0.0), max: Some(100.0), ..typed("number") }),
|
||||
("position", property(l, item_position, item_set_position), typed("Array")),
|
||||
("left", property(l, item_left, item_set_left), typed("number")),
|
||||
("top", property(l, item_top, item_set_top), typed("number")),
|
||||
("width", property(l, item_width, item_set_width), typed("number")),
|
||||
("height", property(l, item_height, item_set_height), typed("number")),
|
||||
("geometricBounds", get(l, item_geometric), typed("Array")),
|
||||
("visibleBounds", get(l, item_visible), typed("Array")),
|
||||
("controlBounds", get(l, item_control), typed("Array")),
|
||||
("editable", get(l, item_editable), typed("boolean")),
|
||||
("zOrderPosition", get(l, item_z_order_position), typed("number")),
|
||||
("duplicate", method(l, item_duplicate), returns("PageItem", &placement)),
|
||||
("move", method(l, item_move), {
|
||||
let mut info = returns("PageItem", &placement);
|
||||
if let Some(at) = info.arguments.get_mut(1) {
|
||||
at.default = Some(text("ElementPlacement.PLACEATBEGINNING"));
|
||||
}
|
||||
info
|
||||
}),
|
||||
("remove", method(l, item_remove), returns("undefined", &[])),
|
||||
("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, item_to_string), returns("string", &[])),
|
||||
]);
|
||||
page_item.extend(
|
||||
[
|
||||
@@ -2329,7 +2516,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
"sliced",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"visibilityVariable",
|
||||
"wrapInside",
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
@@ -2342,22 +2528,22 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
);
|
||||
page_item.extend(variables::page_item_members(l));
|
||||
classes.push(class("PageItem", None, page_item, None));
|
||||
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None)));
|
||||
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), variables::item_members(l, c), None)));
|
||||
classes.extend(variables::classes(l));
|
||||
classes.push(class(
|
||||
"Layer",
|
||||
None,
|
||||
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
|
||||
named(vec![
|
||||
("typename", get(l, layer_typename), typed("string")),
|
||||
("name", get(l, layer_name), typed("string")),
|
||||
("toString", method(l, layer_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
|
||||
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
|
||||
realm.define_host_globals(vec![
|
||||
("activeDocument".into(), function(l, app_active), Some(function(l, app_set_active))),
|
||||
("documents".into(), function(l, app_documents), None),
|
||||
("selection".into(), function(l, app_selection), Some(function(l, app_set_selection))),
|
||||
])
|
||||
classes
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2397,4 +2583,107 @@ mod tests {
|
||||
assert_eq!(kept_items(&lists, 2, &docs[1]), None);
|
||||
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
|
||||
}
|
||||
|
||||
/// A script function that writes a reflection as one line, in the form [`expected_line`] gives.
|
||||
const LINE: &str = "function line(r) {\
|
||||
function args(a) { var s = []; for (var i = 0; i < a.length; i++) s.push([a[i].name, a[i].type, a[i].dataType, a[i].defaultValue].join('=')); return s.join(','); }\
|
||||
function list(a) { var s = []; for (var i = 0; i < a.length; i++) { var e = a[i];\
|
||||
s.push([e.name, e.type, e.dataType, e.isCollection, e.min, e.max, e.defaultValue, args(e.arguments)].join(':')); } return s.join(' '); }\
|
||||
return r.name + '|' + list(r.properties) + '|' + list(r.methods); }";
|
||||
|
||||
fn shown(d: Option<&Data>) -> String {
|
||||
match d {
|
||||
None | Some(Data::Undefined) => String::new(),
|
||||
Some(Data::String(s)) => s.clone(),
|
||||
Some(Data::Number(n)) => n.to_string(),
|
||||
Some(other) => panic!("no form for {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The line [`LINE`] should write for `class`: its parents' members, then its own, a member it
|
||||
/// declares again in its parent's place, without the members that are not available.
|
||||
fn expected_line(classes: &[HostClass], class: &HostClass) -> String {
|
||||
let mut chain = vec![class];
|
||||
while let Some(p) = chain.last().and_then(|c| c.parent.as_ref()) {
|
||||
chain.push(classes.iter().find(|c| &c.name == p).unwrap_or_else(|| panic!("no class {p}")));
|
||||
}
|
||||
let mut members: Vec<(String, &'static str, MemberInfo)> = Vec::new();
|
||||
for c in chain.iter().rev() {
|
||||
for (name, member) in &c.members {
|
||||
let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i.clone()).unwrap_or_default();
|
||||
let kind = match member {
|
||||
HostMember::Get(_) => "readonly",
|
||||
HostMember::Property { .. } | HostMember::Unavailable(_) => "readwrite",
|
||||
HostMember::Method(_) => "method",
|
||||
};
|
||||
match members.iter_mut().find(|(n, ..)| n == name) {
|
||||
Some(slot) => *slot = (name.clone(), kind, info),
|
||||
None => members.push((name.clone(), kind, info)),
|
||||
}
|
||||
}
|
||||
}
|
||||
members.retain(|(.., i)| !i.unavailable);
|
||||
let one = |(name, kind, i): &(String, &str, MemberInfo)| {
|
||||
let args: Vec<String> =
|
||||
i.arguments.iter().map(|a| format!("{}=parameter={}={}", a.name, a.data_type, shown(a.default.as_ref()))).collect();
|
||||
let number = |n: Option<f64>| n.map(|n| n.to_string()).unwrap_or_default();
|
||||
format!(
|
||||
"{name}:{kind}:{}:{}:{}:{}:{}:{}",
|
||||
i.data_type,
|
||||
i.collection,
|
||||
number(i.min),
|
||||
number(i.max),
|
||||
shown(i.default.as_ref()),
|
||||
args.join(",")
|
||||
)
|
||||
};
|
||||
let properties: Vec<String> = members.iter().filter(|m| m.1 != "method").map(one).collect();
|
||||
let methods: Vec<String> = members.iter().filter(|m| m.1 == "method").map(one).collect();
|
||||
format!("{}|{}|{}", class.name, properties.join(" "), methods.join(" "))
|
||||
}
|
||||
|
||||
fn logged(s: &mut Session, source: &str) -> Vec<String> {
|
||||
let r = s.execute("script.run", &json!({"source": source, "name": "t.js"})).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().unwrap_or_else(|| panic!("{r}")).iter().map(|v| v.as_str().unwrap_or_default().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_of_every_class_equals_its_declaration() {
|
||||
let link = Link::default();
|
||||
let classes = classes(&link);
|
||||
// Every member that is available declares its type, so `reflect` never answers `unknown`.
|
||||
for c in &classes {
|
||||
for (name, _) in &c.members {
|
||||
let info = c.info.iter().find(|(n, _)| n == name).map(|(_, i)| i);
|
||||
assert!(info.is_some_and(|i| i.unavailable || !i.data_type.is_empty()), "{}.{name} declares no type", c.name);
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
let logs: Vec<String> = classes.iter().map(|c| format!("vc.log(line({}.reflect));", c.name)).collect();
|
||||
let script = format!("{LINE} {}", logs.join(" "));
|
||||
let got = logged(&mut s, &script);
|
||||
let want: Vec<String> = classes.iter().map(|c| expected_line(&classes, c)).collect();
|
||||
assert_eq!(got, want);
|
||||
assert!(want.iter().any(|w| w.contains("insertionLocation=parameter=ElementPlacement=ElementPlacement.PLACEATBEGINNING")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflect_of_an_object_equals_its_class_and_calls_no_member() {
|
||||
let link = Link::default();
|
||||
let classes = classes(&link);
|
||||
let want = |name: &str| expected_line(&classes, classes.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no class {name}")));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap_or_else(|e| panic!("{e}"));
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 20, "width": 30, "height": 40})).unwrap_or_else(|e| panic!("{e}"));
|
||||
let script = format!(
|
||||
"{LINE} var d = app.activeDocument, p = d.pageItems[0]; vc.log(line(app.reflect)); vc.log(line(app.documents.reflect));\
|
||||
vc.log(line(d.reflect)); vc.log(line(d.pageItems.reflect)); vc.log(line(p.reflect)); vc.log(line(new DocumentPreset().reflect));\
|
||||
p.remove(); vc.log(line(p.reflect)); vc.log(String(p.reflect.find('opacity').max));"
|
||||
);
|
||||
let got = logged(&mut s, &script);
|
||||
let path = want("PathItem");
|
||||
let expected =
|
||||
[want("Application"), want("Documents"), want("Document"), want("PageItems"), path.clone(), want("DocumentPreset"), path, "100".into()];
|
||||
assert_eq!(got, expected);
|
||||
}
|
||||
}
|
||||
@@ -18,11 +18,11 @@ use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
|
||||
|
||||
use super::{
|
||||
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
|
||||
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::NodeId;
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
|
||||
use vectorcraft_js::{Data, HostClass, HostError, host_ref};
|
||||
|
||||
/// The error for a tag that was deleted, or that came from an earlier run.
|
||||
pub const STALE_TAG: &str = "Stale tag";
|
||||
@@ -286,21 +286,21 @@ fn tag_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
/// The `Tags` and `Tag` classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let tags: Vec<(String, HostMember)> = named(vec![
|
||||
("typename", get(l, tags_typename)),
|
||||
("length", get(l, tags_length)),
|
||||
("parent", get(l, tags_parent)),
|
||||
("index", method(l, tags_index)),
|
||||
("getByName", method(l, tags_by_name)),
|
||||
("add", method(l, tags_add)),
|
||||
("removeAll", method(l, tags_remove_all)),
|
||||
let tags = named(vec![
|
||||
("typename", get(l, tags_typename), typed("string")),
|
||||
("length", get(l, tags_length), typed("number")),
|
||||
("parent", get(l, tags_parent), typed("*")),
|
||||
("index", method(l, tags_index), returns("Tag", &[("itemKey", "*")])),
|
||||
("getByName", method(l, tags_by_name), returns("Tag", &[("name", "string")])),
|
||||
("add", method(l, tags_add), returns("Tag", &[])),
|
||||
("removeAll", method(l, tags_remove_all), returns("undefined", &[])),
|
||||
]);
|
||||
let tag = named(vec![
|
||||
("typename", get(l, tag_typename)),
|
||||
("name", property(l, tag_name, tag_set_name)),
|
||||
("value", property(l, tag_value, tag_set_value)),
|
||||
("parent", get(l, tag_parent)),
|
||||
("remove", method(l, tag_remove)),
|
||||
("typename", get(l, tag_typename), typed("string")),
|
||||
("name", property(l, tag_name, tag_set_name), typed("string")),
|
||||
("value", property(l, tag_value, tag_set_value), typed("string")),
|
||||
("parent", get(l, tag_parent), typed("PageItem")),
|
||||
("remove", method(l, tag_remove), returns("undefined", &[])),
|
||||
]);
|
||||
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
//! Variables and data sets in the script object model: `Document.variables`, `dataSets`,
|
||||
//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`,
|
||||
//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the
|
||||
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Variables/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Variable/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/> describe them. Every change runs
|
||||
//! one of the `variable.*` and `dataset.*` commands.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change
|
||||
//! made through the object keeps the object working; once the name leaves the document any other
|
||||
//! way (a delete, a rename by another command, an undo, a kind change by another command, or an
|
||||
//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or
|
||||
//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most
|
||||
//! [`MAX_HANDLES`] of each.
|
||||
//! - Collections list variables and data sets in the order the document holds them, counted from
|
||||
//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`.
|
||||
//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first
|
||||
//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data
|
||||
//! set named `Data Set 1` and so on, which becomes the active one.
|
||||
//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`,
|
||||
//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file
|
||||
//! declared without one VectorCraft knows, and cannot be given.
|
||||
//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order.
|
||||
//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows
|
||||
//! its values in the art, as `display()` does.
|
||||
//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the
|
||||
//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the
|
||||
//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all.
|
||||
//! An embedded image (`RasterItem`) cannot take an image variable.
|
||||
//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the
|
||||
//! script may read, or write, as its `File` objects may: the files of the open documents do not
|
||||
//! count.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostItem, MemberInfo, Realm, RunError, file_ref_path, host_ref};
|
||||
|
||||
use super::{
|
||||
Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float,
|
||||
function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::doc::{DataSet, Node, Variable, VariableKind};
|
||||
use crate::file_access::Access;
|
||||
|
||||
/// The error for a `Variable` whose variable left the document, or that came from an earlier run.
|
||||
pub const STALE_VARIABLE: &str = "Stale variable";
|
||||
/// The error for a `Dataset` whose data set left the document, or that came from an earlier run.
|
||||
pub const STALE_DATASET: &str = "Stale data set";
|
||||
/// The most `Variable` objects, and the most `Dataset` objects, one run gives out.
|
||||
pub const MAX_HANDLES: usize = 10_000;
|
||||
|
||||
/// The kinds, each with the name of its `VariableKind` member.
|
||||
const KINDS: [(VariableKind, &str); 5] = [
|
||||
(VariableKind::Text, "TEXTUAL"),
|
||||
(VariableKind::Visibility, "VISIBILITY"),
|
||||
(VariableKind::Image, "IMAGE"),
|
||||
(VariableKind::Graph, "GRAPH"),
|
||||
(VariableKind::Unknown, "Unknown"),
|
||||
];
|
||||
|
||||
/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a
|
||||
/// variable (`None` for a data set) and whether it still names it.
|
||||
struct Entry {
|
||||
uid: u64,
|
||||
name: String,
|
||||
kind: Option<VariableKind>,
|
||||
alive: bool,
|
||||
}
|
||||
|
||||
/// The objects of one class a run gave out: each one's handle is its index here.
|
||||
#[derive(Default)]
|
||||
struct Table {
|
||||
entries: Vec<Entry>,
|
||||
/// The entry that names each document's name, while it does.
|
||||
live: HashMap<(u64, String), usize>,
|
||||
}
|
||||
|
||||
impl Table {
|
||||
/// The entry for `name` of the document `uid`, made when there is none.
|
||||
fn slot(&mut self, uid: u64, name: &str, kind: Option<VariableKind>, what: &str) -> std::result::Result<usize, HostError> {
|
||||
if let Some(&at) = self.live.get(&(uid, name.to_string()))
|
||||
&& self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind)
|
||||
{
|
||||
return Ok(at);
|
||||
}
|
||||
if self.entries.len() >= MAX_HANDLES {
|
||||
return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run")));
|
||||
}
|
||||
self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true });
|
||||
let at = self.entries.len() - 1;
|
||||
self.live.insert((uid, name.to_string()), at);
|
||||
Ok(at)
|
||||
}
|
||||
|
||||
/// The entry `at` no longer names anything.
|
||||
fn kill(&mut self, at: usize) {
|
||||
if let Some(e) = self.entries.get_mut(at) {
|
||||
e.alive = false;
|
||||
let k = (e.uid, std::mem::take(&mut e.name));
|
||||
if self.live.get(&k) == Some(&at) {
|
||||
self.live.remove(&k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry `at` names `name`, of `kind`, from now on: a rename made through it.
|
||||
fn rename(&mut self, at: usize, name: &str, kind: Option<VariableKind>) {
|
||||
let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return };
|
||||
self.kill(at);
|
||||
if let Some(e) = self.entries.get_mut(at) {
|
||||
*e = Entry { uid, name: name.to_string(), kind, alive: true };
|
||||
}
|
||||
self.live.insert((uid, name.to_string()), at);
|
||||
}
|
||||
|
||||
/// Kills each live entry `keep` refuses.
|
||||
fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) {
|
||||
let gone: Vec<usize> = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect();
|
||||
for at in gone {
|
||||
self.kill(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last
|
||||
/// checked against it.
|
||||
#[derive(Default)]
|
||||
pub(super) struct Handles {
|
||||
vars: RefCell<Table>,
|
||||
sets: RefCell<Table>,
|
||||
seen: RefCell<Vec<(u64, u64)>>,
|
||||
}
|
||||
|
||||
/// The data sets of the active document before a command that may replace them (an import), while
|
||||
/// the run holds a `Dataset`; `None` for any other command.
|
||||
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<DataSet>)> {
|
||||
if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let s = h.session.try_borrow().ok()?;
|
||||
s.active().map(|st| (st.uid, st.doc.variables.datasets.clone()))
|
||||
}
|
||||
|
||||
/// After each command a script runs: the objects whose variable or data set it removed stop
|
||||
/// working, so one made again under the same name does not bring them back. An import that leaves
|
||||
/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset`
|
||||
/// of that document, also when the new data sets reuse the names; an import that failed, was put
|
||||
/// back or left the data sets as they were stops none.
|
||||
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<DataSet>)>) {
|
||||
let hs = &h.dom.vars;
|
||||
if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Ok(s) = h.session.try_borrow() else { return };
|
||||
let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid));
|
||||
let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect();
|
||||
let changed: HashSet<u64> = {
|
||||
let seen = hs.seen.borrow();
|
||||
now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect()
|
||||
};
|
||||
*hs.seen.borrow_mut() = now;
|
||||
if changed.is_empty() && replaced.is_none() {
|
||||
return;
|
||||
}
|
||||
let mut kinds: HashMap<u64, HashMap<&str, VariableKind>> = HashMap::new();
|
||||
let mut sets: HashMap<u64, HashSet<&str>> = HashMap::new();
|
||||
for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) {
|
||||
let vars = &st.doc.variables;
|
||||
kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect());
|
||||
sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect());
|
||||
}
|
||||
hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind);
|
||||
hs.sets
|
||||
.borrow_mut()
|
||||
.sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str()))));
|
||||
}
|
||||
|
||||
fn kind_text(k: VariableKind) -> Data {
|
||||
let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n);
|
||||
text(format!("VariableKind.{name}"))
|
||||
}
|
||||
|
||||
fn kind_of(d: &Data) -> std::result::Result<VariableKind, HostError> {
|
||||
let found = match d {
|
||||
Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k),
|
||||
_ => None,
|
||||
};
|
||||
match found {
|
||||
Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())),
|
||||
Some(k) => Ok(k),
|
||||
None => Err(HostError::Type("kind must be a VariableKind value".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes.
|
||||
fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> {
|
||||
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
|
||||
if s.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range(format!("the {what} is too long")));
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// The `name` field of a command's result.
|
||||
fn result_name(d: &Data) -> Option<String> {
|
||||
let Data::Object(o) = d else { return None };
|
||||
o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None })
|
||||
}
|
||||
|
||||
fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer {
|
||||
let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?;
|
||||
Ok(host_ref("Variable", &[float(h.run), float(at as u64)]))
|
||||
}
|
||||
|
||||
fn set_ref(h: &Host, uid: u64, name: &str) -> Answer {
|
||||
let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?;
|
||||
Ok(host_ref("Dataset", &[float(h.run), float(at as u64)]))
|
||||
}
|
||||
|
||||
/// A variable or data set an object names: its document, its handle's index and its name.
|
||||
struct Named {
|
||||
doc: Doc,
|
||||
at: usize,
|
||||
name: String,
|
||||
kind: Option<VariableKind>,
|
||||
}
|
||||
|
||||
/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its
|
||||
/// document.
|
||||
fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result<Named, HostError> {
|
||||
let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) };
|
||||
let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) };
|
||||
let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) };
|
||||
let stale = || HostError::Error(stale.into());
|
||||
if whole(run) != Some(h.run) {
|
||||
return Err(stale());
|
||||
}
|
||||
let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?;
|
||||
let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets };
|
||||
let (uid, name, kind) = {
|
||||
let t = table.borrow();
|
||||
let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?;
|
||||
(e.uid, e.name.clone(), e.kind)
|
||||
};
|
||||
let doc = find_doc(h, float(h.run), float(uid));
|
||||
let there = doc.is_some_and(|doc| {
|
||||
with_doc(h, doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() }
|
||||
})
|
||||
});
|
||||
match doc {
|
||||
Some(doc) if there => Ok(Named { doc, at, name, kind }),
|
||||
_ => {
|
||||
table.borrow_mut().kill(at);
|
||||
Err(stale())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn this_var(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
|
||||
named_of(h, arg(a, 0), true)
|
||||
}
|
||||
|
||||
fn this_set(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
|
||||
named_of(h, arg(a, 0), false)
|
||||
}
|
||||
|
||||
/// The index argument of a collection's indexer: a whole number, or `None`.
|
||||
fn index_arg(d: &Data) -> Option<usize> {
|
||||
match d {
|
||||
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Document ----
|
||||
|
||||
fn this_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Document")
|
||||
}
|
||||
|
||||
fn doc_variables(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Variables", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_datasets(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked)))
|
||||
}
|
||||
|
||||
/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so.
|
||||
fn doc_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) };
|
||||
if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) {
|
||||
Some(name) => set_ref(h, doc.uid, &name),
|
||||
None => Ok(Data::Null),
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active
|
||||
/// one and the art already shows it.
|
||||
fn display(h: &Host, set: &Named) -> Answer {
|
||||
let shown = with_doc(h, set.doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values()))
|
||||
});
|
||||
if !shown {
|
||||
on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
if handle_of(arg(a, 1), "Dataset").is_none() {
|
||||
return Err(HostError::Type("activeDataset must be a Dataset".into()));
|
||||
}
|
||||
let set = named_of(h, arg(a, 1), false)?;
|
||||
if set.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("the data set is in another document".into()));
|
||||
}
|
||||
display(h, &set)
|
||||
}
|
||||
|
||||
/// The path of the `File` argument of `what`, which must be a file the script may reach for
|
||||
/// `access` through its own `File` objects.
|
||||
fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result<String, HostError> {
|
||||
let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) };
|
||||
if path.chars().count() > super::super::files::MAX_PATH_CHARS {
|
||||
return Err(HostError::Range(format!("{what}: the path is too long")));
|
||||
}
|
||||
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
|
||||
gate.check(path, access).map_err(HostError::Error)?;
|
||||
Ok(path.to_string())
|
||||
}
|
||||
|
||||
/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's
|
||||
/// variables and data sets with the library's.
|
||||
fn doc_import(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_arg(h, a, "importVariables", Access::Read)?;
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `exportVariables(file)`: `variable.saveLibrary` into the file.
|
||||
fn doc_export(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
let path = file_arg(h, a, "exportVariables", Access::Write)?;
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Variables ----
|
||||
|
||||
fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Variables")
|
||||
}
|
||||
|
||||
fn vars_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
vars_doc(h, a)?;
|
||||
Ok(text("Variables"))
|
||||
}
|
||||
|
||||
fn vars_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64)))
|
||||
}
|
||||
|
||||
fn vars_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn vars_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) {
|
||||
Some(v) => var_ref(h, doc.uid, &v),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn vars_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let name = name_arg(arg(a, 1), "name")?;
|
||||
let found = with_doc(h, doc, |_, st| {
|
||||
h.charge_call(st.doc.variables.variables.len() as u64)?;
|
||||
Ok::<_, HostError>(st.doc.variables.variable(name).cloned())
|
||||
})?;
|
||||
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v))
|
||||
}
|
||||
|
||||
fn vars_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => vars_by_name(h, a),
|
||||
Data::Number(_) => match vars_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the
|
||||
/// first free name). → the new variable.
|
||||
fn vars_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let name = with_doc(h, doc, |_, st| {
|
||||
let vars = &st.doc.variables;
|
||||
(1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default()
|
||||
});
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?;
|
||||
var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text })
|
||||
}
|
||||
|
||||
/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is
|
||||
/// none.
|
||||
fn vars_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = vars_doc(h, a)?;
|
||||
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect());
|
||||
if !names.is_empty() {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Variable ----
|
||||
|
||||
fn var_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_var(h, a)?;
|
||||
Ok(text("Variable"))
|
||||
}
|
||||
|
||||
fn var_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
Ok(doc_ref(h, v.doc.uid))
|
||||
}
|
||||
|
||||
fn var_name(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_var(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = text`: `variable.rename`, which trims it, with no command when the name stays.
|
||||
fn var_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
let to = name_arg(arg(a, 1), "name")?;
|
||||
if to.trim() == v.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?;
|
||||
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
|
||||
h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn var_kind(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown)))
|
||||
}
|
||||
|
||||
/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot
|
||||
/// hold it and drops the variable's values, with no command when the kind stays.
|
||||
fn var_set_kind(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
let kind = kind_of(arg(a, 1))?;
|
||||
if Some(kind) == v.kind {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?;
|
||||
h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn var_page_items(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
with_doc(h, v.doc, |_, st| {
|
||||
let ids: Vec<crate::NodeId> =
|
||||
st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
|
||||
if ids.len() > MAX_LISTED {
|
||||
return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects")));
|
||||
}
|
||||
h.charge_call(16 * ids.len() as u64)?;
|
||||
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
|
||||
})
|
||||
}
|
||||
|
||||
/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values.
|
||||
fn var_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let v = this_var(h, a)?;
|
||||
on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?;
|
||||
h.dom.vars.vars.borrow_mut().kill(v.at);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Datasets ----
|
||||
|
||||
fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Datasets")
|
||||
}
|
||||
|
||||
fn sets_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
sets_doc(h, a)?;
|
||||
Ok(text("Datasets"))
|
||||
}
|
||||
|
||||
fn sets_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64)))
|
||||
}
|
||||
|
||||
fn sets_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn sets_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
|
||||
match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) {
|
||||
Some(name) => set_ref(h, doc.uid, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn sets_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let name = name_arg(arg(a, 1), "name")?;
|
||||
let found = with_doc(h, doc, |_, st| {
|
||||
h.charge_call(st.doc.variables.datasets.len() as u64)?;
|
||||
Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone()))
|
||||
})?;
|
||||
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n))
|
||||
}
|
||||
|
||||
fn sets_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => sets_by_name(h, a),
|
||||
Data::Number(_) => match sets_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new
|
||||
/// data set and makes it the active one. → the new data set.
|
||||
fn sets_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?;
|
||||
let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?;
|
||||
set_ref(h, doc.uid, &name)
|
||||
}
|
||||
|
||||
/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is
|
||||
/// none.
|
||||
fn sets_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = sets_doc(h, a)?;
|
||||
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect());
|
||||
if !names.is_empty() {
|
||||
on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Dataset ----
|
||||
|
||||
fn set_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_set(h, a)?;
|
||||
Ok(text("Dataset"))
|
||||
}
|
||||
|
||||
fn set_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
Ok(doc_ref(h, d.doc.uid))
|
||||
}
|
||||
|
||||
fn set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text(this_set(h, a)?.name))
|
||||
}
|
||||
|
||||
/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays.
|
||||
fn set_set_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
let to = name_arg(arg(a, 1), "name")?;
|
||||
if to.trim() == d.name {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?;
|
||||
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
|
||||
h.dom.vars.sets.borrow_mut().rename(d.at, &name, None);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_display(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
display(h, &d)
|
||||
}
|
||||
|
||||
/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no
|
||||
/// command when it already holds what the bound objects hold.
|
||||
fn set_update(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
let same = with_doc(h, d.doc, |_, st| {
|
||||
let doc = &st.doc;
|
||||
let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some());
|
||||
bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values()))
|
||||
});
|
||||
if !same {
|
||||
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `dataset.remove()`: `dataset.delete` of this data set.
|
||||
fn set_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
let d = this_set(h, a)?;
|
||||
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?;
|
||||
h.dom.vars.sets.borrow_mut().kill(d.at);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Page items ----
|
||||
|
||||
/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its
|
||||
/// content.
|
||||
fn slot_kind(n: &Node, content: bool) -> std::result::Result<VariableKind, HostError> {
|
||||
if !content {
|
||||
return Ok(VariableKind::Visibility);
|
||||
}
|
||||
crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into()))
|
||||
}
|
||||
|
||||
/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's
|
||||
/// kind bound to the object, in the order the variables are defined, or `null`.
|
||||
fn binding(h: &Host, a: &[Data], content: bool) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let found = with_doc(h, item.doc, |_, st| {
|
||||
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let kind = slot_kind(n, content)?;
|
||||
let vars = &st.doc.variables;
|
||||
let bound = vars.bindings.get(&item.id);
|
||||
Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned())
|
||||
})?;
|
||||
match found {
|
||||
Some(v) => var_ref(h, item.doc.uid, &v),
|
||||
None => Ok(Data::Null),
|
||||
}
|
||||
}
|
||||
|
||||
/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of
|
||||
/// the object's document, or with none for `null`. No command runs when the object already has just
|
||||
/// that binding of the slot's kind.
|
||||
fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer {
|
||||
let item = item_of(h, arg(a, 0))?;
|
||||
let variable = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "Variable").is_some() => {
|
||||
let v = named_of(h, d, true)?;
|
||||
if v.doc.uid != item.doc.uid {
|
||||
return Err(HostError::Error("the variable is in another document".into()));
|
||||
}
|
||||
Some(v.name)
|
||||
}
|
||||
_ => return Err(HostError::Type("give a Variable or null".into())),
|
||||
};
|
||||
let same = with_doc(h, item.doc, |_, st| {
|
||||
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
|
||||
let kind = slot_kind(n, content)?;
|
||||
let vars = &st.doc.variables;
|
||||
let bound = vars.bindings.get(&item.id);
|
||||
let held: Vec<&str> =
|
||||
vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect();
|
||||
Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::<Vec<_>>())
|
||||
})?;
|
||||
if !same {
|
||||
let slot = if content { "content" } else { "visibility" };
|
||||
edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn item_visibility(h: &Host, a: &[Data]) -> Answer {
|
||||
binding(h, a, false)
|
||||
}
|
||||
|
||||
fn item_set_visibility(h: &Host, a: &[Data]) -> Answer {
|
||||
set_binding(h, a, false)
|
||||
}
|
||||
|
||||
fn item_content(h: &Host, a: &[Data]) -> Answer {
|
||||
binding(h, a, true)
|
||||
}
|
||||
|
||||
fn item_set_content(h: &Host, a: &[Data]) -> Answer {
|
||||
set_binding(h, a, true)
|
||||
}
|
||||
|
||||
// ---- Registration ----
|
||||
|
||||
/// The members this module adds to `Document`.
|
||||
pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("variables", get(l, doc_variables), MemberInfo { collection: true, ..typed("Variables") }),
|
||||
("dataSets", get(l, doc_datasets), MemberInfo { collection: true, ..typed("Datasets") }),
|
||||
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset), typed("Dataset")),
|
||||
("variablesLocked", property(l, doc_locked, doc_set_locked), typed("boolean")),
|
||||
("importVariables", method(l, doc_import), returns("undefined", &[("fileSpec", "File")])),
|
||||
("exportVariables", method(l, doc_export), returns("undefined", &[("fileSpec", "File")])),
|
||||
])
|
||||
}
|
||||
|
||||
/// The members this module adds to `PageItem`.
|
||||
pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility), typed("Variable"))])
|
||||
}
|
||||
|
||||
/// The members this module adds to the page item class `class`.
|
||||
pub(super) fn item_members(l: &Link, class: &str) -> Vec<Described> {
|
||||
match class {
|
||||
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => {
|
||||
named(vec![("contentVariable", property(l, item_content, item_set_content), typed("Variable"))])
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The classes this module adds.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
vec![
|
||||
class(
|
||||
"Variables",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, vars_typename), typed("string")),
|
||||
("length", get(l, vars_length), typed("number")),
|
||||
("parent", get(l, vars_parent), typed("Document")),
|
||||
("index", method(l, vars_index), returns("Variable", &[("itemKey", "*")])),
|
||||
("getByName", method(l, vars_by_name), returns("Variable", &[("name", "string")])),
|
||||
("add", method(l, vars_add), returns("Variable", &[])),
|
||||
("removeAll", method(l, vars_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, vars_at)),
|
||||
),
|
||||
class(
|
||||
"Variable",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, var_typename), typed("string")),
|
||||
("parent", get(l, var_parent), typed("Document")),
|
||||
("name", property(l, var_name, var_set_name), typed("string")),
|
||||
("kind", property(l, var_kind, var_set_kind), typed("VariableKind")),
|
||||
("pageItems", get(l, var_page_items), typed("Array")),
|
||||
("remove", method(l, var_remove), returns("undefined", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
class(
|
||||
"Datasets",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, sets_typename), typed("string")),
|
||||
("length", get(l, sets_length), typed("number")),
|
||||
("parent", get(l, sets_parent), typed("Document")),
|
||||
("index", method(l, sets_index), returns("Dataset", &[("itemKey", "*")])),
|
||||
("getByName", method(l, sets_by_name), returns("Dataset", &[("name", "string")])),
|
||||
("add", method(l, sets_add), returns("Dataset", &[])),
|
||||
("removeAll", method(l, sets_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, sets_at)),
|
||||
),
|
||||
class(
|
||||
"Dataset",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, set_typename), typed("string")),
|
||||
("parent", get(l, set_parent), typed("Document")),
|
||||
("name", property(l, set_name, set_set_name), typed("string")),
|
||||
("display", method(l, set_display), returns("undefined", &[])),
|
||||
("update", method(l, set_update), returns("undefined", &[])),
|
||||
("remove", method(l, set_remove), returns("undefined", &[])),
|
||||
]),
|
||||
None,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings.
|
||||
pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> {
|
||||
let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect();
|
||||
realm.define_host_object("VariableKind", items)
|
||||
}
|
||||
@@ -1109,6 +1109,20 @@ impl Host {
|
||||
self.pause.set(true);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about
|
||||
/// it, for [`Host::put_growth_back`].
|
||||
fn growth_mark(&self) -> (u64, u64, bool) {
|
||||
(self.objects.get(), self.bytes_kept.get(), self.waiting.get())
|
||||
}
|
||||
|
||||
/// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added
|
||||
/// it were put back.
|
||||
fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) {
|
||||
self.objects.set(objects);
|
||||
self.bytes_kept.set(bytes);
|
||||
self.waiting.set(waiting);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run in progress.
|
||||
@@ -1352,16 +1366,15 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let id = id.to_string();
|
||||
let params = params.clone();
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let before = dom::before_command(host, id);
|
||||
let r = {
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, &id, ¶ms)
|
||||
step(&mut s, host, id, params)
|
||||
};
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
let mut times = host.commands.borrow_mut();
|
||||
let row = times.entry(spec.id).or_insert((0, 0, 0));
|
||||
@@ -1374,13 +1387,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())),
|
||||
Err(e) => return Err(HostError::Error(e.to_string())),
|
||||
};
|
||||
let mark = host.growth_mark();
|
||||
let crossed = host.charge_growth(objects, added).and_then(|()| {
|
||||
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
|
||||
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
|
||||
host.charge_call(data_size(&data))?;
|
||||
Ok(data)
|
||||
});
|
||||
// A command whose result does not reach the script is put back, like one that failed.
|
||||
// A command whose result does not reach the script is put back, like one that failed, and so is
|
||||
// the growth it was charged.
|
||||
if crossed.is_err() {
|
||||
host.put_growth_back(mark);
|
||||
}
|
||||
if let Some(save) = save {
|
||||
let mut s = session.borrow_mut();
|
||||
if crossed.is_ok() {
|
||||
@@ -1389,6 +1407,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
dom::after_command(host, before);
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
@@ -2162,7 +2181,7 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
dom: dom::State::default(),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
run_docs: RefCell::new(
|
||||
self.docs
|
||||
.iter()
|
||||
|
||||
Reference in new issue
Block a user