mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge feat/scripts-api-d1a-app-documents into feat/scripts-api-d4b-text-styles
This commit is contained in:
commit
771383bed8
1307 files changed
+194081
-268410
No files matched your search
+382
-71
@@ -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,8 +42,20 @@
|
||||
//! - 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};
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -86,13 +114,15 @@ pub(super) enum Coords {
|
||||
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
|
||||
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
|
||||
/// What the object model keeps for one run: its coordinate system, the last list of a document's
|
||||
/// page items, kept while that document is unchanged, whether a call's own savepoint
|
||||
/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made.
|
||||
/// 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.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
items: RefCell<Option<ItemList>>,
|
||||
items: RefCell<Vec<ItemList>>,
|
||||
locked: RefCell<Vec<LockedList>>,
|
||||
saving: Cell<bool>,
|
||||
presets: RefCell<Vec<Vec<(String, Data)>>>,
|
||||
text: text::TextState,
|
||||
@@ -135,6 +165,57 @@ fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostE
|
||||
/// A document's uid, the document as it was, and the ids of its page items then.
|
||||
type ItemList = (u64, Arc<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for
|
||||
/// each object of a layer or sublayer asked about then, whether it was on a locked artboard.
|
||||
type LockedList = (u64, Arc<Document>, Arc<HashSet<NodeId>>, HashMap<NodeId, bool>);
|
||||
|
||||
/// How many documents' lists [`State`] keeps at once, of each kind.
|
||||
const ITEM_LISTS: usize = 4;
|
||||
|
||||
/// The kept list of the document `uid` as `doc` is, if there is one.
|
||||
fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc<Document>) -> Option<Rc<Vec<NodeId>>> {
|
||||
lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone())
|
||||
}
|
||||
|
||||
/// Keeps `list` in place of any earlier list of the same document, dropping the least recently
|
||||
/// kept list beyond [`ITEM_LISTS`].
|
||||
fn keep_items(lists: &mut Vec<ItemList>, list: ItemList) {
|
||||
lists.retain(|(u, _, _)| *u != list.0);
|
||||
if lists.len() >= ITEM_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push(list);
|
||||
}
|
||||
|
||||
/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each
|
||||
/// object of a layer or sublayer is measured once while the document and its new art stay as they
|
||||
/// are, so the members of a group are answered with one measurement of the group.
|
||||
fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool {
|
||||
if !st.doc.artboards.iter().any(|a| a.locked) {
|
||||
return false;
|
||||
}
|
||||
let Some(object) = st.doc.layer_object(id).map(|n| n.id) else {
|
||||
return false;
|
||||
};
|
||||
let new_art = st.doc.new_art.get();
|
||||
let mut lists = h.dom.locked.borrow_mut();
|
||||
let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) {
|
||||
Some(at) => at,
|
||||
None => {
|
||||
lists.retain(|(u, ..)| *u != st.uid);
|
||||
if lists.len() >= ITEM_LISTS {
|
||||
lists.remove(0);
|
||||
}
|
||||
lists.push((st.uid, st.doc.clone(), new_art, HashMap::new()));
|
||||
lists.len() - 1
|
||||
}
|
||||
};
|
||||
match lists.get_mut(at) {
|
||||
Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)),
|
||||
None => st.doc.on_locked_artboard(object),
|
||||
}
|
||||
}
|
||||
|
||||
type Answer = std::result::Result<Data, HostError>;
|
||||
|
||||
/// A member function: the run's host and the call's arguments, `this` first.
|
||||
@@ -162,7 +243,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, page item or text range `this` is still there.
|
||||
/// the check that a document, page item or text range `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();
|
||||
@@ -183,7 +265,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 {
|
||||
@@ -345,31 +427,30 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data {
|
||||
}
|
||||
}
|
||||
|
||||
/// The ids of a document's page items in paint order ([`State`] keeps the last list).
|
||||
/// 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((uid, doc, ids)) = &*h.dom.items.borrow()
|
||||
&& *uid == st.uid
|
||||
&& Arc::ptr_eq(doc, &st.doc)
|
||||
{
|
||||
return ids.clone();
|
||||
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 { .. } => {}
|
||||
NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => {
|
||||
_ => {
|
||||
out.push(n.id);
|
||||
walk(children, out);
|
||||
if let Some(children) = n.children() {
|
||||
walk(children, out);
|
||||
}
|
||||
}
|
||||
_ => out.push(n.id),
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
walk(&st.doc.layers, &mut ids);
|
||||
let ids = Rc::new(ids);
|
||||
*h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone()));
|
||||
keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone()));
|
||||
ids
|
||||
}
|
||||
|
||||
@@ -544,6 +625,31 @@ fn done_unless_refused(r: std::result::Result<Data, HostError>) -> std::result::
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted
|
||||
/// Layers panel rows, after selecting objects made the layer of the last of them current and
|
||||
/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when
|
||||
/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not.
|
||||
fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) -> std::result::Result<(), HostError> {
|
||||
let Some(layer) = layer else { return Ok(()) };
|
||||
let rows = {
|
||||
let s = h.session.borrow();
|
||||
let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) };
|
||||
if st.doc.node(layer).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let rows: Vec<NodeId> = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect();
|
||||
(st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::<Vec<_>>())
|
||||
};
|
||||
if let Some(rows) = rows {
|
||||
command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?;
|
||||
}
|
||||
let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer));
|
||||
if !current {
|
||||
command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs `f` with the document `uid` active, and makes the document that was active before active
|
||||
/// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
@@ -556,10 +662,11 @@ fn on_doc<T>(
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before) = {
|
||||
let (index, active, before, layer) = {
|
||||
let s = h.session.borrow();
|
||||
let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
(index, s.active_index(), s.documents()[index].selection.clone())
|
||||
let st = &s.documents()[index];
|
||||
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()))
|
||||
};
|
||||
let switch = active != Some(index);
|
||||
if switch {
|
||||
@@ -575,6 +682,9 @@ fn on_doc<T>(
|
||||
if let Some(doc) = doc {
|
||||
restored = restore_selection(h, &doc, &before);
|
||||
}
|
||||
if restored.is_ok() {
|
||||
restored = restore_layer(h, uid, layer.0, &layer.1);
|
||||
}
|
||||
}
|
||||
// The document that was active is active again before any error is given: `f`'s error first,
|
||||
// then the selection's, then the switch back's.
|
||||
@@ -632,6 +742,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 }))
|
||||
}
|
||||
@@ -678,10 +800,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)))
|
||||
@@ -820,7 +947,10 @@ impl NewDoc<'_> {
|
||||
if let Some(d) = self.preview {
|
||||
let mode = match d {
|
||||
Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default",
|
||||
Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel",
|
||||
// Pixel Preview is a setting of the app's view, which a script cannot turn on.
|
||||
Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => {
|
||||
return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into()));
|
||||
}
|
||||
Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint",
|
||||
_ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())),
|
||||
};
|
||||
@@ -897,6 +1027,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
None | Some(Data::Null) => Vec::new(),
|
||||
Some(d) => {
|
||||
let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?;
|
||||
// The settings are charged as data passed to the call before they are copied.
|
||||
let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::<u64>();
|
||||
h.charge_call(bytes)?;
|
||||
h.dom.presets.borrow()[i].clone()
|
||||
}
|
||||
};
|
||||
@@ -944,6 +1077,10 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer {
|
||||
let reason = e["reason"].as_str().unwrap_or_default();
|
||||
return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}")));
|
||||
}
|
||||
// Each warning from reading the profile's file goes to the console.
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut));
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?;
|
||||
Ok(doc_ref(h, st.uid))
|
||||
@@ -1010,8 +1147,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
|
||||
let l = link.clone();
|
||||
let get: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
|
||||
// The value handed back is charged as the setter charges it, before it is copied.
|
||||
let i = preset_of(&h, arg(&a, 0));
|
||||
let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v)));
|
||||
h.charge_call(16 + bytes)?;
|
||||
let i = i.ok_or_else(not_preset)?;
|
||||
let presets = h.dom.presets.borrow();
|
||||
Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone()))
|
||||
});
|
||||
@@ -1137,19 +1277,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()))
|
||||
}
|
||||
|
||||
@@ -1163,10 +1321,16 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId
|
||||
d => vec![d],
|
||||
};
|
||||
let mut ids: Vec<NodeId> = Vec::with_capacity(list.len());
|
||||
for d in list {
|
||||
let item = item_of(h, d)?;
|
||||
// The document is read once for every object: nothing changes it while the list is checked.
|
||||
let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked()));
|
||||
let locks = d.locked_artboards();
|
||||
for v in list {
|
||||
let item = item_of(h, v)?;
|
||||
// A path made into a guide is not selected while Lock Guides is on, as the selection
|
||||
// commands leave it out.
|
||||
let ok = item.doc.uid == doc.uid
|
||||
&& with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id));
|
||||
&& crate::cmd::select::is_selectable(&d, isolation, &locks, item.id)
|
||||
&& !(guides_locked && crate::is_guide_path(&d, item.id));
|
||||
if !ok {
|
||||
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)));
|
||||
@@ -1237,8 +1401,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))))
|
||||
@@ -1335,8 +1512,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()));
|
||||
}
|
||||
@@ -1351,9 +1540,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()));
|
||||
}
|
||||
@@ -1365,12 +1555,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}))
|
||||
}
|
||||
|
||||
@@ -1380,6 +1585,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}))
|
||||
}
|
||||
|
||||
@@ -1392,7 +1598,24 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
}
|
||||
set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v}))
|
||||
// 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, 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 {
|
||||
@@ -1415,18 +1638,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 {
|
||||
@@ -1439,8 +1663,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 {
|
||||
@@ -1459,19 +1685,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])]);
|
||||
@@ -1507,7 +1734,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")));
|
||||
@@ -1530,9 +1758,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer {
|
||||
resize(h, a, false)
|
||||
}
|
||||
|
||||
/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group,
|
||||
/// or on a locked artboard.
|
||||
fn item_editable(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id))))
|
||||
Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id))))
|
||||
}
|
||||
|
||||
/// The item's place in its parent's stacking order, from 1 at the bottom.
|
||||
@@ -1544,7 +1774,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| {
|
||||
@@ -1556,7 +1786,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)
|
||||
}
|
||||
|
||||
@@ -1602,9 +1833,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"));
|
||||
@@ -1623,7 +1854,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 {
|
||||
@@ -1641,7 +1872,8 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
|
||||
if !editable(d, parent) {
|
||||
return Err(HostError::Error("the layer or group is hidden or locked".into()));
|
||||
}
|
||||
if !editable(d, item.id) {
|
||||
// An object on a locked artboard is not moved, as `editable` reads false for it.
|
||||
if !editable(d, item.id) || on_locked_artboard(h, st, item.id) {
|
||||
let name = d.node(item.id).and_then(typename).unwrap_or("page item");
|
||||
return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0)));
|
||||
}
|
||||
@@ -1682,14 +1914,19 @@ 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`).
|
||||
/// 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. 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)?;
|
||||
place(h, item.doc, item.id, &to)?;
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -1713,6 +1950,13 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
if in_compound(h, item) {
|
||||
return Err(HostError::Error(COMPOUND_MEMBER.into()));
|
||||
}
|
||||
// `edit.duplicate` copies only what it can select.
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
(!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item"))
|
||||
});
|
||||
if let Some(name) = refused {
|
||||
return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0)));
|
||||
}
|
||||
let to = match arg(a, 1) {
|
||||
Data::Undefined => {
|
||||
if !matches!(arg(a, 2), Data::Undefined) {
|
||||
@@ -1720,7 +1964,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]})))?;
|
||||
@@ -1736,7 +1980,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",
|
||||
@@ -1749,6 +1993,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);
|
||||
@@ -1779,6 +2024,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))))
|
||||
}
|
||||
@@ -1831,9 +2101,10 @@ 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)),
|
||||
("toString", class_text("Application")),
|
||||
]);
|
||||
application.push(("textFonts".into(), text::app_text_fonts(l)));
|
||||
application.push(later(l, "Application", "beep"));
|
||||
@@ -1844,7 +2115,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) }
|
||||
};
|
||||
@@ -1862,6 +2133,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)),
|
||||
),
|
||||
@@ -1879,6 +2151,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("pageItems", get(l, doc_page_items)),
|
||||
("textFrames", text::doc_text_frames(l)),
|
||||
("selection", property(l, doc_selection, doc_set_selection)),
|
||||
("toString", method(l, doc_to_string)),
|
||||
]);
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
@@ -1897,6 +2170,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)),
|
||||
));
|
||||
@@ -1923,6 +2197,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(
|
||||
[
|
||||
@@ -1951,8 +2226,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().filter(|c| **c != "TextFrame").map(|c| class(c, Some("PageItem"), Vec::new(), None)));
|
||||
classes.extend(text::classes(l));
|
||||
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)]
|
||||
@@ -1967,4 +2253,29 @@ mod tests {
|
||||
assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into())));
|
||||
assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_lists_are_kept_for_several_documents() {
|
||||
let docs: Vec<Arc<Document>> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect();
|
||||
let ids = |n: u64| Rc::new(vec![NodeId(n)]);
|
||||
let mut lists = Vec::new();
|
||||
keep_items(&mut lists, (1, docs[0].clone(), ids(1)));
|
||||
keep_items(&mut lists, (2, docs[1].clone(), ids(2)));
|
||||
// Reading two documents in turn keeps both lists.
|
||||
assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1)));
|
||||
assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2)));
|
||||
// A changed document has no kept list, and its new list replaces the old one.
|
||||
let changed = Arc::new(Document::new(100.0, 100.0));
|
||||
assert_eq!(kept_items(&lists, 1, &changed), None);
|
||||
keep_items(&mut lists, (1, changed.clone(), ids(3)));
|
||||
assert_eq!(lists.len(), 2);
|
||||
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
|
||||
// Past the limit, the list kept longest ago goes.
|
||||
for (uid, d) in (10..).zip(&docs[2..]) {
|
||||
keep_items(&mut lists, (uid, d.clone(), ids(uid)));
|
||||
}
|
||||
assert_eq!(lists.len(), ITEM_LISTS);
|
||||
assert_eq!(kept_items(&lists, 2, &docs[1]), None);
|
||||
assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3)));
|
||||
}
|
||||
}
|
||||
@@ -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) };
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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`.
|
||||
@@ -1046,7 +1075,7 @@ impl Host {
|
||||
}
|
||||
let bridge = self.bridge.get().saturating_add(bytes);
|
||||
self.bridge.set(bridge);
|
||||
if bridge > MAX_BRIDGE_BYTES {
|
||||
if bridge > bridge_bytes() {
|
||||
return Err(self.over(OVER_BRIDGE));
|
||||
}
|
||||
let n = self.calls_this_slice.get() + 1;
|
||||
@@ -1243,9 +1272,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()) {
|
||||
@@ -1562,7 +1601,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);
|
||||
@@ -1652,16 +1691,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()
|
||||
@@ -2060,11 +2093,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 => {
|
||||
@@ -2134,6 +2172,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)) {
|
||||
@@ -2159,6 +2205,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) {
|
||||
@@ -2167,6 +2214,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(()) })
|
||||
@@ -2578,6 +2626,15 @@ fn growth_objects() -> u64 {
|
||||
GROWTH_OBJECTS
|
||||
}
|
||||
|
||||
/// The data a run may pass to and from commands.
|
||||
fn bridge_bytes() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) {
|
||||
return n;
|
||||
}
|
||||
MAX_BRIDGE_BYTES
|
||||
}
|
||||
|
||||
/// The limits of a command's result on its way to the script.
|
||||
fn result_limits() -> DataLimits {
|
||||
#[cfg(test)]
|
||||
@@ -2595,6 +2652,8 @@ thread_local! {
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
pub(crate) static TEST_GROWTH: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`].
|
||||
pub(crate) static TEST_BRIDGE_BYTES: Cell<Option<u64>> = const { Cell::new(None) };
|
||||
/// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`].
|
||||
pub(crate) static TEST_ENGINE_HEAP: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`].
|
||||
|
||||
Reference in new issue
Block a user