Merge feat/scripts-api-d1a-app-documents into feat/scripts-app-redraw

This commit is contained in:
dotCooCoo committed 2026-11-24 23:59:14 -08:00
commit 950cf819dd
1311 files changed
+193671 -269038

No files matched your search

+217 -64
View File
@@ -13,9 +13,25 @@
//! 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.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - Collections list documents in tab order and art in paint order (bottom first), counted from 0.
//! `pageItems` lists every object, with the objects inside groups and compound paths after the
//! 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`
//! 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`.
//!
//! VectorCraft's own rules:
//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever
//! order they were selected or made in. The objectReferences page above says instead that the
//! first object is the one last added to the page; VectorCraft does not follow that sentence.
//! - A collection read with a name that nothing has throws `Not found`, and `"name" in pageItems` is
//! 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.
//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is
//! always the active document; VectorCraft does not follow that yet.
//! - `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. 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
@@ -26,6 +42,17 @@
//! - 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.
//! - 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
//! object has when that changes nothing; on a graph's mark or label whose series or kind keeps
//! another opacity it would still change the graph, so it is refused too. Its `name` and `note`
//! still change. An object that is hidden or locked itself, or is in a hidden or locked group,
//! takes them.
//! - `name` and `note` take a number or a Boolean as the text `String(value)` gives.
//! - A compound path whose last path `move` or `remove()` takes out stays, empty.
//! - An object with nothing in it, such as an empty group or a compound path whose paths moved out,
//! reads its bounds, `position`, `width` and `height` as zeros, and assigning them does nothing.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
@@ -206,7 +233,8 @@ fn method(link: &Link, f: Member) -> HostMember {
}
/// 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.
/// 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) {
let message = format!("{class}.{name} is not available yet");
let l = link.clone();
@@ -224,7 +252,7 @@ fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostM
}
Err(HostError::Error(message.clone()))
});
(name.to_string(), HostMember::Property { get: f.clone(), set: f })
(name.to_string(), HostMember::Unavailable(f))
}
fn text(s: impl Into<String>) -> Data {
@@ -386,14 +414,14 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
}
}
/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last
/// documents read).
/// The ids of a document's page items, topmost first, each group or compound path before the
/// objects in it ([`State`] keeps the lists of the last documents read).
fn page_items(h: &Host, st: &DocState) -> Rc<Vec<NodeId>> {
if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) {
return ids;
}
fn walk(nodes: &[Arc<crate::doc::Node>], out: &mut Vec<NodeId>) {
for n in nodes {
for n in nodes.iter().rev() {
match &n.kind {
NodeKind::Layer { children, .. } => walk(children, out),
NodeKind::RulerGuide { .. } => {}
@@ -696,6 +724,18 @@ fn app_selection(h: &Host, _: &[Data]) -> Answer {
}
}
/// `app.selection = objects`: the active document's selection, as `selection` of that document is
/// assigned.
fn app_set_selection(h: &Host, a: &[Data]) -> Answer {
let doc = {
let s = h.session.borrow();
let active = s.active_index().and_then(|index| s.documents().get(index).map(|st| Doc { index, uid: st.uid }));
active.ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?
};
let ids = selection_ids(h, doc, arg(a, 1))?;
set_selection(h, doc, ids)
}
fn app_coords(h: &Host, _: &[Data]) -> Answer {
Ok(text(if h.dom.coords.get() == Coords::Document { DOCUMENT_COORDS } else { ARTBOARD_COORDS }))
}
@@ -749,10 +789,15 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
Ok(host_ref("Application", &[]))
}
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
},
_ => None,
};
Ok(at.map_or(Data::Undefined, |st| doc_ref(h, st.uid)))
@@ -1221,19 +1266,37 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
selection_of(h, doc.uid)
}
/// The selection of the document `uid`: `null` when nothing is selected, otherwise a new list of
/// the selected objects.
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
/// `pageItems` lists them, empty when nothing is selected.
fn selection_of(h: &Host, uid: u64) -> Answer {
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let ids: Vec<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if ids.is_empty() {
return Ok(Data::Null);
}
if ids.len() > MAX_LISTED {
let picked: HashSet<NodeId> = st.selection.objects.iter().copied().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if picked.len() > MAX_LISTED {
return Err(HostError::Range(format!("the selection has more than {MAX_LISTED} objects")));
}
h.charge_call(16 * ids.len() as u64)?;
// Only the selected objects are ordered, by their place in the tree, so the cost follows the
// size of the selection and not of the document. `pageItems` walks each list of children
// topmost first and puts a group before the objects in it: a higher index comes first, and an
// ancestor's path, a prefix of its descendants' paths, sorts before them.
let mut placed: Vec<(Vec<std::cmp::Reverse<usize>>, NodeId)> = Vec::with_capacity(picked.len());
let mut unplaced: Vec<NodeId> = Vec::new();
let mut seen: HashSet<NodeId> = HashSet::with_capacity(picked.len());
let mut steps = 0u64;
for id in st.selection.objects.iter().copied().filter(|i| picked.contains(i) && seen.insert(*i)) {
match st.doc.index_path(id) {
Some(path) => {
steps += path.len() as u64;
placed.push((path.into_iter().map(std::cmp::Reverse).collect(), id));
}
// A selected object outside the tree's walk still comes last, in the order it was
// selected.
None => unplaced.push(id),
}
}
placed.sort();
let ids: Vec<NodeId> = placed.into_iter().map(|(_, id)| id).chain(unplaced).collect();
h.charge_call(steps + 16 * ids.len() as u64)?;
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
}
@@ -1327,8 +1390,21 @@ fn items_parent(h: &Host, a: &[Data]) -> Answer {
Ok(doc_ref(h, doc.uid))
}
/// Whether an indexer was called for `name in collection` ([`vectorcraft_js::HostClass::index`]),
/// where a name nothing has gives `undefined` instead of the `Not found` error a read throws.
fn probing(a: &[Data]) -> bool {
matches!(arg(a, 2), Data::Bool(true))
}
/// `pageItems[i]`, and `pageItems["name"]` as `getByName` reads it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
let doc = items_doc(h, a)?;
if let Data::String(_) = arg(a, 1) {
return match items_by_name(h, a) {
Err(HostError::Error(e)) if e == NOT_FOUND && probing(a) => Ok(Data::Undefined),
r => r,
};
}
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| page_items(h, st).get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
@@ -1425,8 +1501,20 @@ fn set_props(h: &Host, a: &[Data], unchanged: impl FnOnce(&crate::doc::Node) ->
Ok(Data::Undefined)
}
/// The text a string property such as `name` or `note` is given: a number or a Boolean becomes the
/// text `String(value)` gives, and any other value that is not a string is refused.
fn text_arg(v: &Data, what: &str) -> std::result::Result<String, HostError> {
match v {
Data::String(s) => Ok(s.clone()),
Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)),
Data::Bool(b) => Ok(b.to_string()),
_ => Err(HostError::Type(format!("{what} must be a string"))),
}
}
/// `name = value`: a number or a Boolean becomes the text `String(value)` gives.
fn item_set_name(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("name must be a string".into())) };
let name = &text_arg(arg(a, 1), "name")?;
if name.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the name is too long".into()));
}
@@ -1441,9 +1529,10 @@ fn item_note(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(text(note_of(n))))
}
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it.
/// `note = text`: the Attributes panel's note, set with `attributes.set`, which trims it. A number
/// or a Boolean becomes the text `String(value)` gives.
fn item_set_note(h: &Host, a: &[Data]) -> Answer {
let Data::String(note) = arg(a, 1) else { return Err(HostError::Type("note must be a string".into())) };
let note = &text_arg(arg(a, 1), "note")?;
if note.len() > MAX_TEXT_BYTES {
return Err(HostError::Range("the note is too long".into()));
}
@@ -1455,12 +1544,27 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in
/// is hidden or locked. Its name and note may still change.
fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> {
let refused = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
});
match refused {
Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))),
None => Ok(()),
}
}
fn item_hidden(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(Data::Bool(!n.visible)))
}
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
let hidden = boolean(arg(a, 1), "hidden")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
}
@@ -1470,6 +1574,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
let locked = boolean(arg(a, 1), "locked")?;
refuse_in_closed_layer(h, this_item(h, a)?)?;
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
@@ -1485,10 +1590,21 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
// A value the getter reports for the item's opacity sends the opacity it has, and
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
// replaces the one the graph keeps for its series or kind.
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
// it would still replace the opacity a graph keeps for the item's series or kind.
let item = this_item(h, a)?;
let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0));
let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v);
set_props(h, a, |_| false, json!({"opacity": v}))
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
let keeps_other =
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
(now, keeps_other)
});
if now.is_none() || keeps_other {
refuse_in_closed_layer(h, item)?;
}
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
}
fn item_selected(h: &Host, a: &[Data]) -> Answer {
@@ -1511,18 +1627,19 @@ fn item_set_selected(h: &Host, a: &[Data]) -> Answer {
}
/// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the
/// document's [`Frame`].
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Rect, Frame), HostError> {
with_doc(h, item.doc, |_, st| {
let r = st.doc.bounds_of(&[item.id], visual).ok_or_else(|| HostError::Error("the object has no bounds".into()))?;
Ok((r, frame(st)?))
})
/// document's [`Frame`]. An object with nothing in it, such as an empty group or a compound path
/// whose paths moved out, has no bounds: its bounds read as zeros, and moving or resizing it does
/// nothing.
fn item_rect(h: &Host, item: Item, visual: bool) -> std::result::Result<(Option<Rect>, Frame), HostError> {
with_doc(h, item.doc, |_, st| Ok((st.doc.bounds_of(&[item.id], visual), frame(st)?)))
}
fn bounds(h: &Host, a: &[Data], visual: bool) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, visual)?;
Ok(f.bounds(h.dom.coords.get(), r))
match item_rect(h, item, visual)? {
(Some(r), f) => Ok(f.bounds(h.dom.coords.get(), r)),
(None, _) => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
}
}
fn item_geometric(h: &Host, a: &[Data]) -> Answer {
@@ -1535,8 +1652,10 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
fn item_position(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, false)?;
Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0))))
match item_rect(h, item, false)? {
(Some(r), f) => Ok(pair(f.to_script(h.dom.coords.get(), Point::new(r.x0, r.y0)))),
(None, _) => Ok(pair([0.0, 0.0])),
}
}
fn item_left(h: &Host, a: &[Data]) -> Answer {
@@ -1555,19 +1674,20 @@ fn item_top(h: &Host, a: &[Data]) -> Answer {
fn item_width(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(num(item_rect(h, item, false)?.0.width()))
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.width())))
}
fn item_height(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
Ok(num(item_rect(h, item, false)?.0.height()))
Ok(num(item_rect(h, item, false)?.0.map_or(0.0, |r| r.height())))
}
/// Moves the item so its top-left corner is at `x` and `y` in script coordinates (`None`: that one
/// stays).
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, false)?;
refuse_in_closed_layer(h, item)?;
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let c = h.dom.coords.get();
let now = f.to_script(c, Point::new(r.x0, r.y0));
let to = f.to_document(c, [x.unwrap_or(now[0]), y.unwrap_or(now[1])]);
@@ -1603,7 +1723,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
}
let item = this_item(h, a)?;
let (r, _) = item_rect(h, item, false)?;
refuse_in_closed_layer(h, item)?;
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
let now = if width { r.width() } else { r.height() };
if now <= 0.0 {
return Err(HostError::Error(format!("the object has no {what} to scale")));
@@ -1642,7 +1763,7 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer {
/// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or
/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`]
/// refuses it.
/// refuses it. A compound path whose last path this is stays, empty.
fn item_remove(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (whole, on_locked) = with_doc(h, item.doc, |_, st| {
@@ -1654,7 +1775,8 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?;
// A compound path whose last path this is stays, empty, as it does after `move`.
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
Ok(Data::Undefined)
}
@@ -1700,9 +1822,9 @@ struct Destination {
}
/// The object a relative object of `move` or `duplicate` names: a page item or a layer of the
/// same document as `item`. A copy (`copy`) may go directly above or below `item` itself, as
/// `layer.move` puts copies.
fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result<Destination, HostError> {
/// same document as `item`. An object may go directly above or below itself: a copy goes there, as
/// `layer.move` puts copies, and a move there leaves the object where it is.
fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result::Result<Destination, HostError> {
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"));
@@ -1721,7 +1843,7 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
let d = &st.doc;
let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let inside = d.ancestry(target).is_some_and(|a| a.iter().any(|i| *i == item.id && *i != target));
if inside || (target == item.id && !(copy && beside)) {
if inside || (target == item.id && !beside) {
return Err(HostError::Error("an object cannot go into itself".into()));
}
let (parent, beside) = match how {
@@ -1783,27 +1905,16 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
/// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a
/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An
/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard
/// is refused.
/// is refused. Moving an object directly above or below itself leaves it where it is, and a compound
/// path whose last path moves out stays, empty.
fn item_move(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
if matches!(arg(a, 1), Data::Undefined) {
return Err(HostError::Type("move needs a relative object".into()));
}
let to = destination(h, item, arg(a, 1), arg(a, 2), false)?;
// When the last path leaves a compound path, the compound path is deleted in the same step
// rather than left empty.
let emptied = with_doc(h, item.doc, |_, st| {
let parent = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p))?;
(matches!(parent.kind, NodeKind::Compound { .. }) && parent.children().is_some_and(|c| c.len() == 1) && parent.id != to.parent)
.then_some(parent.id)
});
match emptied {
None => place(h, item.doc, item.id, &to)?,
Some(compound) => atomically(h, |h| {
place(h, item.doc, item.id, &to)?;
on_doc(h, item.doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": [compound.0]})))?;
Ok(())
})?,
let to = destination(h, item, arg(a, 1), arg(a, 2))?;
if to.beside != Some(item.id) {
place(h, item.doc, item.id, &to)?;
}
Ok(arg(a, 0).clone())
}
@@ -1842,7 +1953,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
None
}
target => Some(destination(h, item, target, arg(a, 2), true)?),
target => Some(destination(h, item, target, arg(a, 2))?),
};
let id = atomically(h, |h| {
let (_, made) = on_doc(h, item.doc.uid, true, |h| command_value(h, "edit.duplicate", &json!({"ids": [item.id.0]})))?;
@@ -1858,7 +1969,7 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
}
/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a
/// compound path is refused.
/// compound path is refused, and so is an object in a hidden or locked layer.
fn item_z_order(h: &Host, a: &[Data]) -> Answer {
let id = match arg(a, 1) {
Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront",
@@ -1871,6 +1982,7 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
if in_compound(h, item) {
return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into()));
}
refuse_in_closed_layer(h, item)?;
let (before, after) = with_doc(h, item.doc, |_, st| {
let at = st.doc.position(item.id);
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
@@ -1901,6 +2013,31 @@ fn layer_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Layer"))
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
}
}
fn item_to_string(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(text(format!("[{} {}]", typename(n).unwrap_or("PageItem"), n.name.as_deref().unwrap_or("")))))
}
fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Document", doc_name(h, a))
}
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
/// `toString()` of an object without a name: `[Class]`.
fn class_text(name: &'static str) -> HostMember {
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
}
fn typename_of(name: &'static str) -> HostMember {
HostMember::Get(Rc::new(move |_| Ok(text(name))))
}
@@ -1952,10 +2089,11 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("typename", typename_of("Application")),
("documents", get(l, app_documents)),
("activeDocument", property(l, app_active, app_set_active)),
("selection", get(l, app_selection)),
("selection", property(l, app_selection, app_set_selection)),
("coordinateSystem", property(l, app_coords, app_set_coords)),
("getIsFileOpen", method(l, app_is_open)),
("redraw", method(l, app_redraw)),
("toString", class_text("Application")),
]);
application.push(later(l, "Application", "beep"));
let preset = {
@@ -1965,7 +2103,7 @@ 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"))];
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) }
};
@@ -1983,6 +2121,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("getByName", method(l, docs_by_name)),
("add", method(l, docs_add)),
("addDocument", method(l, docs_add_document)),
("toString", class_text("Documents")),
]),
Some(function(l, docs_at)),
),
@@ -1999,6 +2138,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("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)),
]);
document.extend(
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
@@ -2016,6 +2156,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("index", method(l, items_index)),
("getByName", method(l, items_by_name)),
("removeAll", method(l, items_remove_all)),
("toString", class_text("PageItems")),
]),
Some(function(l, items_at)),
));
@@ -2042,6 +2183,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("move", method(l, item_move)),
("remove", method(l, item_remove)),
("zOrder", method(l, item_z_order)),
("toString", method(l, item_to_string)),
]);
page_item.extend(
[
@@ -2069,8 +2211,19 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
);
classes.push(class("PageItem", None, page_item, None));
classes.extend(ITEM_CLASSES.iter().map(|c| class(c, Some("PageItem"), Vec::new(), None)));
classes.push(class("Layer", None, named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name))]), None));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])
classes.push(class(
"Layer",
None,
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
None,
));
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))),
])
}
#[cfg(test)]
+159 -44
View File
@@ -54,7 +54,9 @@
//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and
//! [`NO_PICKER`].
//! - The commands a script runs with `vc.run` read and write only in the places above and in the
//! files of the open documents ([`crate::file_access::ScriptGate`]).
//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read
//! the files that the documents open when the run began link to, as the person last left those
//! documents and as those links led then.
//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most
//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at
//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an
@@ -67,8 +69,15 @@
//! file and once more for each such object. `write` joins its values only for an open file and
//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the
//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed.
//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`.
//! `execute` is counted in the report's `fileExecutes`.
//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in
//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the
//! old and the new name must both be places the script may write, and a name in use is refused.
//! `createAlias` makes a symbolic link at the object's path, a place the script may write where
//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias`
//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what
//! it leads to. On other systems both set `error` and change nothing.
//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's
//! `fileExecutes`.
//! - In a wasm build every lookup fails with [`NO_WEB`].
use std::collections::HashMap;
@@ -118,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
#[cfg(not(unix))]
pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases";
pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed";
pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed";
@@ -454,10 +464,11 @@ impl Disk {
}
}
/// The gate for a command the script runs: the places it reads and writes now, and the files of
/// the open documents, `documents`.
pub(crate) fn gate(&self, documents: Vec<String>) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None }
/// The gate for a command the script runs: the places it reads and writes now, the files the
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
}
/// The files written since this was last asked, to name in the report.
@@ -912,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
/// between two changes, and none are read when the lock cannot be taken.
fn read_store(store: &Path) -> Vec<serde_json::Value> {
let Ok(_lock) = lock_store(store) else { return Vec::new() };
load_store(store, false).unwrap_or_default()
list_store(store).unwrap_or_default()
}
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
/// this version or holds no list of grants.
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
let _lock = lock_store(store)?;
load_store(store, false)
}
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
@@ -929,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
let bytes = match read_head(store, MAX_STORE_BYTES) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
// A link whose target is missing is there but cannot be read.
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
Err(e) => return Err(e),
};
if bytes.len() > MAX_STORE_BYTES {
@@ -947,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
&& g["write"].is_boolean()
&& g["folder"].is_boolean()
};
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if strict {
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
}
return Ok(grants.clone());
}
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
}
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
@@ -1054,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
}
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
/// its text, the path and whether it may be written (`script.grants`).
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
read_store(&data_dir.with_file_name(GRANTS_FILE))
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
list_store(&data_dir.with_file_name(GRANTS_FILE))
}
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
@@ -1883,44 +1902,41 @@ fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path.
fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, name) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
Ok(match rename_in(&mut disk, &path, &name) {
Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]),
Err(m) => error(m),
})
}
/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new
/// path.
fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result<String, &'static str> {
let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':')));
if bad || name.contains('\0') {
return Ok(error(BAD_NAME));
return Err(BAD_NAME);
}
let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
let mut disk = host.disk.borrow_mut();
let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) {
(Ok(f), Ok(t)) => (f, t),
(Err(m), _) | (_, Err(m)) => return Ok(error(m)),
};
let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) };
let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?;
let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?);
let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?;
// A folder that holds the settings folder is not moved, also when its name is given in another
// case where case does not matter.
let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept));
if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) {
return Ok(error(ACCESS_DENIED));
return Err(ACCESS_DENIED);
}
// A name that differs in case alone may name the same file, which then takes the new name.
if let Ok(there) = std::fs::symlink_metadata(&to)
&& !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there)))
{
return Ok(error(NAME_TAKEN));
return Err(NAME_TAKEN);
}
// Open objects hold real paths with the names the file system keeps, and `from` keeps the last
// name as given, which where case does not matter can differ in case: they are matched by the
// kept name. A link is renamed itself, and no object holds a path through it. When the kept
// name cannot be learned, nothing is renamed, so no object goes on under the old path's rules.
let kept = if was.file_type().is_symlink() {
from.clone()
} else {
match std::fs::canonicalize(&from) {
Ok(kept) => kept,
Err(_) => return Ok(error(WRITE_FAILED)),
}
};
if std::fs::rename(&from, &to).is_err() {
return Ok(error(WRITE_FAILED));
}
let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? };
std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?;
// Open objects of the file, or of files in the folder, write to the new path, and the rules for
// reading apply to them there.
let moved = |p: &mut Option<std::path::PathBuf>| {
@@ -1935,7 +1951,102 @@ fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
// The old path no longer holds the file, so the report names it as well as the new one.
disk.wrote(&from);
disk.wrote(&to);
Ok(Data::Object(vec![("fs".into(), Data::String(new))]))
Ok(new)
}
/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or
/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading
/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be
/// left empty, a folder, and every system that is not Unix give `{error}`.
fn set_hidden(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true))));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if !cfg!(unix) {
return Ok(error(NO_HIDDEN));
}
match std::fs::symlink_metadata(&at) {
Err(_) => return Ok(error(NOT_FOUND)),
Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)),
Ok(_) => {}
}
let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
if name.starts_with('.') == on {
return Ok(Data::Object(vec![("fs".into(), Data::String(path))]));
}
let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() };
if new.is_empty() {
return Ok(error(NO_HIDDEN));
}
Ok(match rename_in(&mut disk, &path, &new) {
Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]),
Err(m) => error(m),
})
}
/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the
/// file `target`. `path` must be a place the script may write where nothing is, not even a link
/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives
/// `{error}`.
fn create_alias(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, to) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if std::fs::symlink_metadata(&at).is_ok() {
return Ok(error(NAME_TAKEN));
}
if to.is_empty() {
return Ok(error(NOT_FOUND));
}
let real = match disk.stat(&to) {
Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()),
Ok(Some(_)) => return Ok(error(NOT_REGULAR)),
Ok(None) => return Ok(error(NOT_FOUND)),
Err(m) => return Ok(error(m)),
};
let Some(real) = real else { return Ok(error(ACCESS_DENIED)) };
#[cfg(test)]
if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) {
hook(&at);
}
Ok(make_link(&mut disk, &at, &real))
}
/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`.
#[cfg(unix)]
fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data {
// Making the link fails when something took its place since it was looked up.
if std::os::unix::fs::symlink(real, at).is_err() {
return error(WRITE_FAILED);
}
// A link put in place of a folder above it since it was looked up may have taken the new link
// elsewhere: that link is removed again, when it is still the one made here.
let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p));
let ours = std::fs::read_link(at).is_ok_and(|l| l == real);
if !placed {
if ours {
let _ = std::fs::remove_file(at);
}
return error(ACCESS_DENIED);
}
// Something else at `at` replaced the new link since it was made: it is left alone.
if !ours {
return error(WRITE_FAILED);
}
disk.wrote(at);
Data::Bool(true)
}
/// Every system that is not Unix: `{error}` with [`NO_ALIAS`].
#[cfg(not(unix))]
fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data {
error(NO_ALIAS)
}
/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on
@@ -2309,13 +2420,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
}))
};
let value = |s: &str| HostItem::Value(Data::String(s.to_string()));
let text = HostItem::Object(vec![
("notOpen".into(), value(NOT_OPEN)),
("badMode".into(), value(BAD_MODE)),
("noAlias".into(), value(NO_ALIAS)),
("noHidden".into(), value(NO_HIDDEN)),
("tooLarge".into(), value(TOO_LARGE)),
]);
let text =
HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]);
let system = if WINDOWS {
"Windows"
} else if cfg!(target_os = "macos") {
@@ -2357,6 +2463,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("create".into(), call(link, create)),
("setLength".into(), call(link, set_length)),
("setReadonly".into(), call(link, set_readonly)),
("setHidden".into(), call(link, set_hidden)),
("createAlias".into(), call(link, create_alias)),
("pick".into(), call(link, pick)),
];
realm.define_file_classes(items)
@@ -2367,9 +2475,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
#[cfg(test)]
pub(crate) type CopyHook = Box<dyn FnOnce(&Path, &Path)>;
/// Tests: what the next `createAlias` does with the real path of its link.
#[cfg(test)]
pub(crate) type AliasHook = Box<dyn FnOnce(&Path)>;
#[cfg(test)]
thread_local! {
pub(crate) static BEFORE_COPY_READ: std::cell::RefCell<Option<CopyHook>> = const { std::cell::RefCell::new(None) };
/// Tests: what the next `createAlias` does with the real path of its link, after looking it up
/// and before making the link.
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
+16 -1
View File
@@ -217,6 +217,15 @@ pub(crate) struct Files {
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -311,9 +320,15 @@ impl Files {
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
}
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
#[cfg(test)]
@@ -456,7 +471,7 @@ impl Files {
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
let options = Options { preprocessor_lines: true, ..self.options() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
+59 -11
View File
@@ -802,6 +802,35 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
/// they link to from them ([`Host::linked`]).
run_docs: RefCell<Vec<RunDoc>>,
/// The files the documents open when the run began link to as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
linked: std::cell::OnceCell<crate::file_access::LinkedFiles>,
}
/// A document open when a run began, with its own file and the file it was read from.
type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
impl Host {
/// The files the commands the run runs may read because the documents open when the run began
/// link to them, found once, from those documents as the person left them: a link a script's
/// command added or changed, in this run or an earlier one, and a document it opened, give it
/// no file to read.
fn linked(&self) -> crate::file_access::LinkedFiles {
self.linked
.get_or_init(|| {
let docs = std::mem::take(&mut *self.run_docs.borrow_mut());
let files = docs.iter().flat_map(|(d, path, from)| {
crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref()))
});
crate::file_access::ScriptGate::real_files(files.collect::<Vec<_>>())
})
.clone()
}
}
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
@@ -1242,9 +1271,19 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
let before: Vec<(u64, Arc<crate::Document>, u64)> =
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
crate::file_access::start_recording_writes();
// The command reads and writes only where the script's own files may, and the open documents' files.
let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect());
// The command reads and writes only where the script's own files may, and the files the person gave
// the open documents; it also reads the files the documents open when the run began link to, as the
// person left them. A document a script's command opened gives it no file.
let documents = s.docs.iter().filter_map(|d| d.as_person_left().and_then(|(_, path, _)| path.map(str::to_string))).collect();
let gate = host.disk.borrow().gate(documents, host.linked());
let was: Vec<(u64, RunDoc)> = s.docs.iter().map(|d| (d.uid, (d.doc.clone(), d.path.clone(), d.links_from.clone()))).collect();
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// What the command opened, changed or gave another file is not as the person left it.
for st in &mut s.docs {
let prior = was.iter().find(|(uid, _)| *uid == st.uid);
st.note_script_command(prior.map(|(_, (doc, path, from))| (doc, path, from)));
}
drop(was);
// A file a command wrote before it failed is on disk all the same.
let mut written = host.written.borrow_mut();
for path in crate::file_access::finish_recording_writes(r.is_ok()) {
@@ -1493,7 +1532,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
})?;
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
let options = host.files.borrow().options();
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
host.files.borrow_mut().end_eval();
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
@@ -1583,16 +1622,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
const APP_MEMBERS: &[&str] = &["activeDocument", "documents", "selection"];
let message = &e.message;
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
if e.kind == RunErrorKind::Thrown
&& !e.authored
&& let Some(member) = first.filter(|f| APP_MEMBERS.contains(f))
{
format!("{message} (use `app.{member}`)")
} else if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
if e.kind == RunErrorKind::Thrown && !e.authored && names_host_object {
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
} else {
message.to_string()
@@ -1991,11 +2024,16 @@ impl Session {
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does.
let es2015 = include::es2015_script(request.file.as_deref());
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
let strict = options.strict;
// A kept engine reads each run's code the way that run's script does.
let mut realm = match realm {
Some(mut realm) => {
realm.set_limits(limits);
realm.set_es2015(es2015);
realm
}
None => {
@@ -2065,6 +2103,14 @@ impl Session {
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::default(),
run_docs: RefCell::new(
self.docs
.iter()
.filter_map(DocState::as_person_left)
.map(|(doc, path, from)| (doc.clone(), path.map(str::to_string), from.map(str::to_string)))
.collect(),
),
linked: std::cell::OnceCell::new(),
});
*link.borrow_mut() = Some(host.clone());
let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) {
@@ -2090,6 +2136,7 @@ impl Session {
Ok(expanded) => {
*host.script_map.borrow_mut() = expanded.map;
realm.set_strict_writes(expanded.strict == Some(true));
realm.set_script_name(Some(host.name.to_string()));
if fresh {
let l = link.clone();
realm.set_source_locator(Rc::new(move |tag, line| match current(&l) {
@@ -2098,6 +2145,7 @@ impl Session {
}));
}
(if fresh { realm.add_script_extensions() } else { Ok(()) })
.and_then(|()| if fresh { realm.add_unit_values() } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })