Scripts: File and Folder objects write files inside a script's scope, with per-script grants and pickers

A script's File and Folder objects now open files for writing, appending
and editing, and copy, rename, remove and create files and folders. A
script reads and writes its run's temporary folder (Folder.temp) and its
own data folder (Folder.userData), kept between runs for a script run
from a file and inside Folder.temp for a script given as text. It reads
its own folder, and reaches other places only through File.openDialog,
File.saveDialog, Folder.selectDialog and the objects' openDlg, saveDlg and
selectDlg.

- A file dialog asks first. The person picks the file or folder with
  Choose..., then allows it once or, for a script run from a file, always.
  A kept grant is bound to the script's path, the SHA-256 of its text and
  every source the run evaluated. It is withdrawn when a later run of the
  script evaluates other code, including code an earlier run left in the
  same named engine. It stays on the real path that was granted, so a
  link put in that place later does not carry it elsewhere.
- A dialog's filter is a string of file types or a function that is
  called with each file picked; multiSelect gives an array of the files
  picked, at most 2,048, and the dialog says when more were left out.
- A folder's selectDlg opens the host's folder dialog in that folder,
  also where the host shows file dialogs in line. Enter in the file
  dialog denies, unless it goes to the focused Choose... button.
  script.grants.revoke is refused with the busy error while a script
  runs, as the run keeps the grants it started with.
- The paths a file dialog allows come only from the host's file dialog:
  ui.dialog.set cannot set them. Only the person at the keyboard allows
  access; Allow Once and Always Allow sent by automation are refused. The
  dialog describes the access the run asked for, whatever its fields say.
- No grant reaches the settings folder, also when the script's own folder
  holds it.
- A file left open is not written through a link put in place of its
  folder since it was opened, and Folder.userData is null when the data
  folder or the script's folder in it is a link.
- copy onto another link to the same file (a hard link) leaves the file's
  bytes as they are, after the source's open objects have written what
  they hold. Files are compared by identity (device and inode on Unix,
  volume and file index on Windows).
- Folder.temp and Folder.userData check each folder they make against the
  automation write roots first, and Folder.create() makes nothing when a
  missing folder above the target is outside the places the script may
  write.
- An open file holds at most 8 MiB, a run writes at most 32 MiB and keeps
  at most 256 files open, and the files a run left open are written in
  the order they were opened. Setting length and copying a file count the
  bytes every open object of that file takes, and write checks the joined
  text against the limit while joining it. The report names at most 4,096
  written files and sets writtenMore when there were more.
- Errors a script sees are translated in every complete message catalog.
This commit is contained in:
dotCooCoo
2026-11-13 05:42:56 -08:00
parent 1dbdbce91f
commit 4716646c6b
58 changed files with 4948 additions and 265 deletions
File diff suppressed because it is too large Load Diff
+152 -13
View File
@@ -37,7 +37,8 @@
//! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the
//! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`.
//!
//! `File` and `Folder` read files inside the script's own folder ([`files`]).
//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary
//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]).
//!
//! A script with `#targetengine name` runs in that named engine, which the session keeps with the
//! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each
@@ -102,6 +103,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20;
const SLICE_HOST_CALLS: u32 = 256;
/// The bytes that may cross between a script and the host in one run.
const MAX_BRIDGE_BYTES: u64 = 4 << 30;
/// The most files a run's report names in `written`; past them the report has `writtenMore`.
pub const MAX_WRITTEN: usize = 4096;
/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the
/// order they were first written, and whether it wrote more.
#[derive(Default)]
struct Written {
paths: Vec<String>,
seen: std::collections::HashSet<String>,
more: bool,
}
impl Written {
fn add(&mut self, path: String) {
if self.seen.contains(&path) {
return;
}
if self.paths.len() >= MAX_WRITTEN {
self.more = true;
return;
}
self.seen.insert(path.clone());
self.paths.push(path);
}
}
/// The version `vc.api.version` gives.
pub const API_VERSION: &str = "1.0";
@@ -255,9 +281,29 @@ struct KeptMap {
struct KeptMaps {
maps: std::collections::VecDeque<KeptMap>,
bytes: usize,
/// The SHA-256 of each source the engine's runs compiled (their scripts and what they
/// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file
/// grants are in force only for code they were kept for ([`files::Disk`]).
code: std::collections::BTreeSet<String>,
code_full: bool,
}
/// The most sources whose SHA-256 a named engine keeps.
pub const MAX_ENGINE_CODE: usize = 1024;
impl KeptMaps {
/// Adds the sources `code` (and whether a run had more than it counted) to the engine's code.
fn keep_code(&mut self, (code, more): (Vec<String>, bool)) {
self.code_full |= more;
for hash in code {
if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) {
self.code_full = true;
} else {
self.code.insert(hash);
}
}
}
fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option<Arc<str>>) {
let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len());
let limit = kept_map_bytes();
@@ -696,7 +742,7 @@ struct Host {
waiting: Cell<bool>,
log: RefCell<Vec<Value>>,
log_bytes: Cell<usize>,
written: RefCell<Vec<String>>,
written: RefCell<Written>,
/// The run's number in its session, and the script's name, which its console lines carry.
run: u64,
name: Arc<str>,
@@ -813,6 +859,7 @@ impl Host {
return;
}
let mut kept = kept.borrow_mut();
kept.keep_code(self.disk.borrow().code());
kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone()));
for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() {
match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) {
@@ -884,6 +931,35 @@ impl Host {
Some(left)
}
/// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`.
fn note_written(&self, paths: Vec<String>) {
let mut written = self.written.borrow_mut();
for path in paths {
written.add(path);
}
}
/// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names.
fn more_written(&self, report: &mut Value) {
if self.written.borrow().more
&& let Some(o) = report.as_object_mut()
{
o.insert("writtenMore".into(), json!(true));
}
}
/// Writes the files the script left open and adds every file written to the report's `written`.
/// → the files it could not write.
fn flush_files(&self) -> Vec<String> {
let mut disk = self.disk.borrow_mut();
let failed = disk.flush_all();
disk.record_code();
let paths = disk.take_written();
drop(disk);
self.note_written(paths);
failed
}
fn over(&self, limit: &str) -> HostError {
HostError::Abort(limit.to_string())
}
@@ -1100,13 +1176,13 @@ 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();
let r = s.execute(id, params);
// 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());
let r = crate::file_access::with_script_gate(gate, || s.execute(id, params));
// 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()) {
if !written.contains(&path) {
written.push(path);
}
written.add(path);
}
drop(written);
match r {
@@ -1664,6 +1740,32 @@ impl Session {
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
}
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
/// longer waits.
pub fn script_picker(&self) -> Option<files::ScriptPicker> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten()
}
/// Gives the file dialog the running script waits at its answer: the paths the person picked
/// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false
/// when no file dialog waits.
pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool {
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false };
with_job(k, |j| {
let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false };
j.host.note_written(j.host.disk.borrow_mut().take_written());
if let Err(e) = j.realm.answer(data) {
j.host.disk.borrow_mut().failed = Some(e);
}
true
})
.unwrap_or(false)
}
/// The name of the running script.
pub fn script_name(&self) -> Option<String> {
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.name.clone()))
@@ -1790,7 +1892,17 @@ impl Session {
realm.set_limits(limits);
realm
}
None => Realm::with_options(options, limits),
None => {
let mut realm = Realm::with_options(options, limits);
// Code the run evaluates withdraws the kept file grants not kept for it, before it runs.
let l = link.clone();
realm.observe_code(move |units| {
if let Ok(h) = current(&l) {
h.disk.borrow_mut().saw_code(units);
}
});
realm
}
};
realm.share_interrupt(&self.script_stop);
realm.set_data_limits(DataLimits::default());
@@ -1810,7 +1922,7 @@ impl Session {
waiting: Cell::new(false),
log: RefCell::new(Vec::new()),
log_bytes: Cell::new(0),
written: RefCell::new(Vec::new()),
written: RefCell::new(Written::default()),
run: self.script_runs,
name: console::line_name(&name),
console: RefCell::default(),
@@ -1819,7 +1931,20 @@ impl Session {
commands: RefCell::default(),
run_nanos: Cell::new(0),
dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers),
disk: RefCell::new(files::Disk::new(files.scope())),
disk: RefCell::new(files::Disk::new(
files.scope(),
files::Setup {
framed: self.script_frames,
script: request.file.clone(),
// The text with its included files, so a changed included file asks again.
source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()),
data_dir: self.script_data_dir.clone(),
engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| {
let m = m.borrow();
(m.code.iter().cloned().collect(), m.code_full)
}),
},
)),
files: RefCell::new(files),
script_map: RefCell::default(),
eval_maps: RefCell::default(),
@@ -1902,14 +2027,16 @@ impl Session {
self.script_gone(key, console::Ending::Internal);
return Some(Err(EngineError::Other(JOB_GONE.to_string())));
};
if let Some(e) = job.host.dialogs.take_failure() {
let picker_failed = job.host.disk.borrow_mut().failed.take();
if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) {
return Some(self.script_failed(job, &e));
}
// A canceled request ends a sleep or a wait at this pump.
if vectorcraft_doc::cancel::check().is_err() {
self.script_stop.set();
}
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() {
let picking = job.host.disk.borrow().picker.is_some();
if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() {
JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job));
self.script_key = Some(key);
return None;
@@ -1949,6 +2076,9 @@ impl Session {
fn script_failed(&mut self, job: Job, e: &RunError) -> Result<Value> {
job.host.dialogs.stopped();
job.host.disk.borrow_mut().picker = None;
// The run fails already; a file it could not write is left out of `written`.
let _ = job.host.flush_files();
let fuel_left = job.realm.fuel_left();
let (e, file) = located(&job.host, &job.realm, e);
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
@@ -1966,6 +2096,12 @@ impl Session {
/// Makes the working copy the session's state: one undo step for each document whose art
/// changed, nothing for the others.
fn script_commit(&mut self, mut job: Job) -> Result<Value> {
let unwritten = job.host.flush_files();
if !unwritten.is_empty() {
let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", "));
let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 };
return self.script_failed(job, &e);
}
// The working copy goes into the session; `job.world` holds the state before the run.
job.world.swap(self);
self.prefs = merged_prefs(&job.world.start_prefs, &self.prefs, &job.world.choices.prefs);
@@ -2029,11 +2165,12 @@ impl Session {
"ok": true,
"name": job.name,
"changed": changed_names,
"written": *host.written.borrow(),
"written": host.written.borrow().paths,
"log": *host.log.borrow(),
"fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(),
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
close_run(self, host, &mut report, console::Ending::Finished);
self.end_job(job, false);
self.script_report = Some(report.clone());
@@ -2060,6 +2197,7 @@ impl Session {
const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
const INVALID_RESULT: &str = "the script left a document that cannot be kept";
const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written";
const JOB_GONE: &str = "the script's run is no longer available";
const HISTORY_LOST: &str = "a failed command changed undo steps that could not be put back, so the script was stopped";
// Text a script reads from the errors it catches, or that ends its run with its name and place.
@@ -2088,12 +2226,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue
"name": name,
"line": e.line,
"column": e.column,
"written": *host.written.borrow(),
"written": host.written.borrow().paths,
"log": *host.log.borrow(),
"fuelLeft": fuel_left,
"fuelUsed": fuel_used,
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
if let (Some(file), Some(o)) = (file, report.as_object_mut()) {
o.insert("file".into(), json!(file));
}