mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-27 16:59:43 +01:00
Merge main into feat/scripts-xmp-objects
This commit is contained in:
commit
2fc172e69a
1472 files changed
+222453
-269065
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -462,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.
|
||||
@@ -920,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,
|
||||
@@ -937,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 {
|
||||
@@ -955,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
|
||||
@@ -1062,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
|
||||
|
||||
@@ -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, e4x: true, ..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 {
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
pub mod console;
|
||||
pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
@@ -799,6 +800,37 @@ struct Host {
|
||||
dollar: dollar::RunState,
|
||||
/// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it.
|
||||
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`.
|
||||
@@ -1043,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;
|
||||
@@ -1234,13 +1266,24 @@ fn note_ids(s: &mut Session) {
|
||||
fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option<Savepoint>)> {
|
||||
raise_ids(s);
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
let save = mutating.then(|| Savepoint::take(s, id));
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
|
||||
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
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()) {
|
||||
@@ -1293,6 +1336,20 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
let bytes = args.iter().map(data_size).sum();
|
||||
host.charge_call(bytes)?;
|
||||
bump(&host.counts.vc_run);
|
||||
command(host, &id, ¶ms)
|
||||
}
|
||||
|
||||
/// Runs command `id` for the script as `vc.run` does, its call already charged: it joins the run's
|
||||
/// transaction, its growth is counted, and a command that fails, or whose result cannot cross to
|
||||
/// the script, is put back. → its result.
|
||||
fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
command_value(host, id, params).map(|(data, _)| data)
|
||||
}
|
||||
|
||||
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
|
||||
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
|
||||
let id = id.to_string();
|
||||
let params = params.clone();
|
||||
let session = host.session.clone();
|
||||
let started = clock();
|
||||
let r = {
|
||||
@@ -1328,7 +1385,7 @@ fn vc_run(host: &Rc<Host>, args: Vec<Data>) -> std::result::Result<Data, HostErr
|
||||
return Err(HostError::Abort(HISTORY_LOST.to_string()));
|
||||
}
|
||||
}
|
||||
crossed
|
||||
crossed.map(|data| (data, value))
|
||||
}
|
||||
|
||||
/// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits
|
||||
@@ -1475,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);
|
||||
@@ -1564,10 +1621,10 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
|
||||
/// `e`'s message, with what to do about a failure that comes from a script written for another
|
||||
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
|
||||
fn explained(e: &RunError) -> String {
|
||||
const HOST_OBJECTS: &[&str] = &["app", "Window", "BridgeTalk", "activeDocument", "documents"];
|
||||
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
|
||||
let message = &e.message;
|
||||
let names_host_object =
|
||||
message.strip_prefix("ReferenceError: ").is_some_and(|m| HOST_OBJECTS.iter().any(|o| m.split_whitespace().next() == Some(o)));
|
||||
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 && names_host_object {
|
||||
format!("{message} (scripts here use the `vc` object; objects other applications give their scripts are not available)")
|
||||
} else {
|
||||
@@ -1967,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, e4x: true, ..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 => {
|
||||
@@ -2040,6 +2102,15 @@ impl Session {
|
||||
eval_strict: Cell::new(None),
|
||||
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)) {
|
||||
@@ -2065,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) {
|
||||
@@ -2073,9 +2145,11 @@ 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(()) })
|
||||
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
|
||||
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
|
||||
.and_then(|()| {
|
||||
let r = realm.start(&expanded.source);
|
||||
@@ -2483,6 +2557,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)]
|
||||
@@ -2500,6 +2583,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