Merge feat/scripts-api-d2-paths-colors into feat/scripts-doc-defaults

This commit is contained in:
dotCooCoo committed 2026-11-25 00:32:34 -08:00
commit 1e382904fa
1308 files changed
+193143 -268844

No files matched your search

+197 -15
View File
@@ -39,6 +39,17 @@
//! says it is not available yet. `rotateAbout` and `scaleAbout` default to
//! `Transformation.CENTER`. A transform that leaves the path where it is (`rotate(360)`,
//! `resize(100, 100)`) checks its arguments and runs no command, on a path with no points too.
//! - `PathPoint.selected` and `selectedPathPoints` count every point of a path selected as a whole
//! as a selected anchor point, and not the endpoints of selected segments; a path in a selected
//! group or compound path is selected as a whole. Direction handles are not selected on their
//! own, so `LEFTDIRECTION`, `RIGHTDIRECTION` and `LEFTRIGHTPOINT` throw an error that says they
//! are not available yet, and so does `NOSELECTION` on a point of a path in a selected group or
//! compound path. Selecting a point of a path with selected segments replaces that path's
//! segment selection. Selecting a point of a guide while guides are locked throws an error. A
//! clipping path cannot be made a guide. Assigning `guides` a value the path does not have
//! throws an error that says it is not available yet on a path inside a compound path, throws
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
//! are locked; assigning the value the path has runs no command.
//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
//! `changeStrokePattern` given as different values throw an error; gradients move with the art,
//! so `changeFillGradients` false throws an error that says it is not available yet.
@@ -585,6 +596,56 @@ fn path_guides(h: &super::Host, a: &[Data]) -> Answer {
read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { guide: true, .. })))
}
/// The error of assigning `guides` on a path inside a compound path.
pub const COMPOUND_MEMBER_GUIDES: &str = "Changing guides on a path inside a compound path is not available yet";
/// `guides = true` makes the path a guide with `view.guides.make`, and `false` makes it a path again
/// with `view.guides.release`; the selection stays as it was. A value the path has already runs no
/// command and throws no error. Otherwise a clipping path cannot be a guide, a path inside a
/// compound path throws [`COMPOUND_MEMBER_GUIDES`], and while guides are locked both values throw
/// an error.
fn path_set_guides(h: &super::Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "guides")?;
let item = this_path(h, a)?;
let (now, clipping) = read_path(h, item, |_, n, _| match &n.kind {
NodeKind::Path { guide, clipping, .. } => (*guide, *clipping),
_ => (false, false),
})?;
if now == on {
return Ok(Data::Undefined);
}
let (member, editable, selectable) = with_doc(h, item.doc, |_, st| {
let member = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p)).is_some_and(|p| matches!(p.kind, NodeKind::Compound { .. }));
let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id);
(member, editable(&st.doc, item.id), selectable)
});
if member {
return Err(HostError::Error(COMPOUND_MEMBER_GUIDES.into()));
}
if !editable || !selectable {
return Err(cannot_edit(item.id));
}
if h.session.borrow().menu.guides_locked {
return Err(HostError::Error(format!("Cannot change guides on PathItem {}: guides are locked", item.id.0)));
}
if !on {
edit_path(h, item, "view.guides.release", json!({}))?;
return Ok(Data::Undefined);
}
if clipping {
return Err(HostError::Error(format!("Cannot make PathItem {} a guide: it is a clipping path", item.id.0)));
}
see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
command(h, "view.guides.make", &json!({}))
});
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
fn path_clipping(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
read_path(h, item, |_, n, _| Data::Bool(matches!(n.kind, NodeKind::Path { clipping: true, .. })))
@@ -1331,6 +1392,129 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer {
Ok(path_ref(h, item))
}
/// Whether a group or compound path that holds the path `id` is selected, which selects the path
/// as a whole whatever the path's own selection is.
fn held_selected(d: &crate::Document, sel: &crate::doc::Selection, id: NodeId) -> bool {
d.ancestry(id).is_some_and(|a| a.iter().any(|i| *i != id && sel.contains(*i) && d.node(*i).is_some_and(|n| !n.is_layer())))
}
/// The point at index `i` of `subs` is a selected anchor point of the path `id` in `sel`: every
/// point of a path selected as a whole is (a path is when a group or compound path that holds it
/// is selected, `held`), and of a path with direct-selected anchors only those anchors are. The
/// endpoints of selected segments are not.
fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[SubPath], i: usize) -> bool {
if held {
return true;
}
if !sel.contains(id) || sel.segments.contains_key(&id) {
return false;
}
match sel.partial(id) {
None => true,
Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)),
}
}
/// Whether the subpaths `a` and `b` have the same number of points in the same subpaths, so that a
/// point index names the same anchor in both.
fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.anchors.len() == y.anchors.len())
}
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
/// [`super::State`] are written first only when they add or remove points of this path, since
/// the selection names anchors by their place in the document's path.
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
let moved = match &*h.dom.pending.borrow() {
Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?,
_ => false,
};
if moved {
super::flush(h)?;
}
let on =
read_path(h, item, |st, _, pd| anchor_selected(&st.selection, item.id, held_selected(&st.doc, &st.selection, item.id), &pd.subpaths, i))?;
Ok(Data::String(if on { "PathPointSelection.ANCHORPOINT" } else { "PathPointSelection.NOSELECTION" }.into()))
}
/// The `PathPointSelection` values that select a point's direction handles.
const HANDLE_SELECTIONS: &[&str] = &["PathPointSelection.LEFTDIRECTION", "PathPointSelection.RIGHTDIRECTION", "PathPointSelection.LEFTRIGHTPOINT"];
/// `selected = PathPointSelection.ANCHORPOINT` adds the point to the direct-selected anchors, and
/// `NOSELECTION` removes it, with `select.anchorsMany`; the other selected objects and anchors stay
/// selected, except that selecting an anchor of a path with selected segments replaces that path's
/// segment selection, as `select.anchorsMany` does. A value the point has already runs no command.
/// Direction handles cannot be selected, so `LEFTDIRECTION`, `RIGHTDIRECTION` and
/// `LEFTRIGHTPOINT` throw an error, and so does `NOSELECTION` on a path selected through a group or
/// compound path that holds it, and `ANCHORPOINT` on a guide while guides are locked. The setter
/// writes the waiting point changes first, as every member that is not a point function does.
fn pt_set_selected(h: &super::Host, a: &[Data]) -> Answer {
let on = match arg(a, 1) {
Data::String(s) if s == "PathPointSelection.ANCHORPOINT" => true,
Data::String(s) if s == "PathPointSelection.NOSELECTION" => false,
Data::String(s) if HANDLE_SELECTIONS.contains(&s.as_str()) => {
return Err(HostError::Error(format!("PathPoint.selected = {s} is not available yet: only anchor points can be selected")));
}
_ => return Err(HostError::Type("selected must be a PathPointSelection value".into())),
};
let (item, i) = this_point(h, a)?;
let (now, at, selectable, held, guide) = with_doc(h, item.doc, |_, st| {
let node = st.doc.node(item.id);
let subs = node.and_then(|n| n.path_data()).map_or(&[][..], |pd| &pd.subpaths[..]);
let guide = node.is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. }));
let selectable = crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id);
let held = held_selected(&st.doc, &st.selection, item.id);
(anchor_selected(&st.selection, item.id, held, subs, i), locate(subs, i), selectable, held, guide)
});
if now == on {
return Ok(Data::Undefined);
}
let Some((s, j)) = at else { return Err(HostError::Error(STALE_POINT.into())) };
if held {
return Err(HostError::Error(format!(
"PathPoint.selected = PathPointSelection.NOSELECTION is not available yet on PathItem {}: the group or compound path that holds it is selected",
item.id.0
)));
}
if on && !selectable {
return Err(HostError::Error(format!("Cannot select PathItem {}", item.id.0)));
}
if on && guide && h.session.borrow().menu.guides_locked {
return Err(HostError::Error(format!("Cannot select PathItem {}: guides are locked", item.id.0)));
}
let params = json!({"items": [{"id": item.id.0, "anchors": [[s, j]]}], "mode": if on { "add" } else { "subtract" }});
on_doc(h, item.doc.uid, false, |h| command(h, "select.anchorsMany", &params))?;
Ok(Data::Undefined)
}
/// `selectedPathPoints`: the points that are selected anchor points ([`anchor_selected`]), in the
/// order of `pathPoints`.
fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let picked: Vec<usize> = read_path(h, item, |st, _, pd| {
let sel = &st.selection;
let held = held_selected(&st.doc, sel, item.id);
if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) {
return Vec::new();
}
let mut out = Vec::new();
let mut first = 0;
for (s, sp) in pd.subpaths.iter().enumerate() {
let n = sp.anchors.len();
out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j));
first += n;
}
out
})?;
h.charge_call(picked.len() as u64)?;
let [high, low] = id_parts(item.id);
let cuts = float(point_cuts(h, item));
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
Ok(Data::Array(points))
}
/// `remove()`: deletes the point; a subpath left with no points goes too.
fn pt_remove(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
@@ -1358,7 +1542,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> {
("evenodd", property(l, path_evenodd, path_set_evenodd)),
("area", get(l, path_area)),
("length", get(l, path_length)),
("guides", get(l, path_guides)),
("guides", property(l, path_guides, path_set_guides)),
("clipping", get(l, path_clipping)),
("setEntirePath", point_method(l, path_set_entire)),
("filled", property(l, path_filled, path_set_filled)),
@@ -1376,8 +1560,9 @@ pub(super) fn path_item_members(l: &Link) -> Vec<(String, HostMember)> {
("translate", method(l, path_translate)),
("rotate", method(l, path_rotate)),
("resize", method(l, path_resize)),
("selectedPathPoints", get(l, path_selected_points)),
]);
m.extend(["selectedPathPoints", "polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n)));
m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n)));
m
}
@@ -1419,19 +1604,16 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
class(
"PathPoint",
None,
{
let mut m = named(vec![
("typename", typename_of("PathPoint")),
("parent", point_get(l, pt_parent)),
("anchor", point_property(l, pt_anchor, pt_set_anchor)),
("leftDirection", point_property(l, pt_left, pt_set_left)),
("rightDirection", point_property(l, pt_right, pt_set_right)),
("pointType", point_property(l, pt_type, pt_set_type)),
("remove", point_method(l, pt_remove)),
]);
m.push(later(l, "PathPoint", "selected"));
m
},
named(vec![
("typename", typename_of("PathPoint")),
("parent", point_get(l, pt_parent)),
("anchor", point_property(l, pt_anchor, pt_set_anchor)),
("leftDirection", point_property(l, pt_left, pt_set_left)),
("rightDirection", point_property(l, pt_right, pt_set_right)),
("pointType", point_property(l, pt_type, pt_set_type)),
("selected", HostMember::Property { get: super::point_function(l, pt_selected), set: super::function(l, pt_set_selected) }),
("remove", point_method(l, pt_remove)),
]),
None,
),
]
+159 -44
View File
@@ -54,7 +54,9 @@
//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and
//! [`NO_PICKER`].
//! - The commands a script runs with `vc.run` read and write only in the places above and in the
//! files of the open documents ([`crate::file_access::ScriptGate`]).
//! files the person gave the open documents ([`crate::file_access::ScriptGate`]). They also read
//! the files that the documents open when the run began link to, as the person last left those
//! documents and as those links led then.
//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most
//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at
//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an
@@ -67,8 +69,15 @@
//! file and once more for each such object. `write` joins its values only for an open file and
//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the
//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed.
//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`.
//! `execute` is counted in the report's `fileExecutes`.
//! - On Unix, where a name that starts with a dot is hidden, setting `hidden` renames the file in
//! its folder, adding one dot or taking its leading dots off, under the rules for `rename`: the
//! old and the new name must both be places the script may write, and a name in use is refused.
//! `createAlias` makes a symbolic link at the object's path, a place the script may write where
//! nothing is, that leads to the real path of a file the script may read. `hidden` and `alias`
//! tell of a link itself, and setting `hidden`, `rename` and `remove` change the link, never what
//! it leads to. On other systems both set `error` and change nothing.
//! - `execute` is not available: it returns `false`, sets `error`, and is counted in the report's
//! `fileExecutes`.
//! - In a wasm build every lookup fails with [`NO_WEB`].
use std::collections::HashMap;
@@ -118,6 +127,7 @@ pub(crate) const WRITE_FAILED: &str = "Script file could not be written";
pub(crate) const NOT_EMPTY: &str = "Script folder is not empty";
pub(crate) const NAME_TAKEN: &str = "Script file name is already in use";
pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder";
#[cfg(not(unix))]
pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases";
pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed";
pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed";
@@ -454,10 +464,11 @@ impl Disk {
}
}
/// The gate for a command the script runs: the places it reads and writes now, and the files of
/// the open documents, `documents`.
pub(crate) fn gate(&self, documents: Vec<String>) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, also: None }
/// The gate for a command the script runs: the places it reads and writes now, the files the
/// person gave the open documents, `documents`, and the files it may only read because the documents open when
/// the run began link to them, `linked`.
pub(crate) fn gate(&self, documents: Vec<String>, linked: crate::file_access::LinkedFiles) -> crate::file_access::ScriptGate {
crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents, linked, also: None }
}
/// The files written since this was last asked, to name in the report.
@@ -912,8 +923,15 @@ fn read_head(real: &Path, max: usize) -> std::io::Result<Vec<u8>> {
/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read
/// between two changes, and none are read when the lock cannot be taken.
fn read_store(store: &Path) -> Vec<serde_json::Value> {
let Ok(_lock) = lock_store(store) else { return Vec::new() };
load_store(store, false).unwrap_or_default()
list_store(store).unwrap_or_default()
}
/// The grants [`read_store`] reads; none when the grants file is missing, and `Err` when the lock
/// cannot be taken or the file is there but cannot be read, is too large, is not a grants file of
/// this version or holds no list of grants.
fn list_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
let _lock = lock_store(store)?;
load_store(store, false)
}
/// The grants the grants file at `store` holds, to change and write back; none when it is missing,
@@ -929,7 +947,8 @@ fn try_read_store(store: &Path) -> std::io::Result<Vec<serde_json::Value>> {
fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Value>> {
let bytes = match read_head(store, MAX_STORE_BYTES) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
// A link whose target is missing is there but cannot be read.
Err(e) if e.kind() == std::io::ErrorKind::NotFound && std::fs::symlink_metadata(store).is_err() => return Ok(Vec::new()),
Err(e) => return Err(e),
};
if bytes.len() > MAX_STORE_BYTES {
@@ -947,14 +966,14 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result<Vec<serde_json::Val
&& g["write"].is_boolean()
&& g["folder"].is_boolean()
};
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if strict {
let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?;
if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) {
return Err(std::io::Error::other("the grants file holds a grant that cannot be read"));
}
return Ok(grants.clone());
}
Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default())
Ok(grants.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect())
}
/// The number in the name of the next file [`write_store`] writes before it takes the grants file's
@@ -1054,9 +1073,9 @@ fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
}
/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of
/// its text, the path and whether it may be written (`script.grants`).
pub(crate) fn stored_grants(data_dir: &Path) -> Vec<serde_json::Value> {
read_store(&data_dir.with_file_name(GRANTS_FILE))
/// its text, the path and whether it may be written (`script.grants`); as [`list_store`] reads them.
pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::Value>> {
list_store(&data_dir.with_file_name(GRANTS_FILE))
}
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
@@ -1883,44 +1902,41 @@ fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path.
fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, name) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
Ok(match rename_in(&mut disk, &path, &name) {
Ok(new) => Data::Object(vec![("fs".into(), Data::String(new))]),
Err(m) => error(m),
})
}
/// Renames the file or folder at `path`, a link itself, to `name` in the same folder. → its new
/// path.
fn rename_in(disk: &mut Disk, path: &str, name: &str) -> Result<String, &'static str> {
let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':')));
if bad || name.contains('\0') {
return Ok(error(BAD_NAME));
return Err(BAD_NAME);
}
let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
let mut disk = host.disk.borrow_mut();
let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) {
(Ok(f), Ok(t)) => (f, t),
(Err(m), _) | (_, Err(m)) => return Ok(error(m)),
};
let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) };
let new = Path::new(path).parent().map(|p| p.join(name).to_string_lossy().into_owned()).ok_or(ACCESS_DENIED)?;
let (from, to) = (disk.target(path, false)?, disk.target(&new, false)?);
let was = std::fs::symlink_metadata(&from).map_err(|_| NOT_FOUND)?;
// A folder that holds the settings folder is not moved, also when its name is given in another
// case where case does not matter.
let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept));
if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) {
return Ok(error(ACCESS_DENIED));
return Err(ACCESS_DENIED);
}
// A name that differs in case alone may name the same file, which then takes the new name.
if let Ok(there) = std::fs::symlink_metadata(&to)
&& !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there)))
{
return Ok(error(NAME_TAKEN));
return Err(NAME_TAKEN);
}
// Open objects hold real paths with the names the file system keeps, and `from` keeps the last
// name as given, which where case does not matter can differ in case: they are matched by the
// kept name. A link is renamed itself, and no object holds a path through it. When the kept
// name cannot be learned, nothing is renamed, so no object goes on under the old path's rules.
let kept = if was.file_type().is_symlink() {
from.clone()
} else {
match std::fs::canonicalize(&from) {
Ok(kept) => kept,
Err(_) => return Ok(error(WRITE_FAILED)),
}
};
if std::fs::rename(&from, &to).is_err() {
return Ok(error(WRITE_FAILED));
}
let kept = if was.file_type().is_symlink() { from.clone() } else { std::fs::canonicalize(&from).map_err(|_| WRITE_FAILED)? };
std::fs::rename(&from, &to).map_err(|_| WRITE_FAILED)?;
// Open objects of the file, or of files in the folder, write to the new path, and the rules for
// reading apply to them there.
let moved = |p: &mut Option<std::path::PathBuf>| {
@@ -1935,7 +1951,102 @@ fn rename(host: &Host, a: &[Data]) -> Result<Data, HostError> {
// The old path no longer holds the file, so the report names it as well as the new one.
disk.wrote(&from);
disk.wrote(&to);
Ok(Data::Object(vec![("fs".into(), Data::String(new))]))
Ok(new)
}
/// `setHidden(path, hidden)`: on Unix, where a name that starts with a dot is hidden, the file or
/// link at `path` (a link itself, never what it leads to) renamed with one dot added or its leading
/// dots taken off; → `{fs}`, its path. A file already as asked keeps its name. A name that would be
/// left empty, a folder, and every system that is not Unix give `{error}`.
fn set_hidden(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, on) = (arg_text(a, 0), matches!(a.get(1), Some(Data::Bool(true))));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if !cfg!(unix) {
return Ok(error(NO_HIDDEN));
}
match std::fs::symlink_metadata(&at) {
Err(_) => return Ok(error(NOT_FOUND)),
Ok(m) if m.is_dir() => return Ok(error(NOT_REGULAR)),
Ok(_) => {}
}
let Some(name) = Path::new(&path).file_name().map(|n| n.to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) };
if name.starts_with('.') == on {
return Ok(Data::Object(vec![("fs".into(), Data::String(path))]));
}
let new = if on { format!(".{name}") } else { name.trim_start_matches('.').to_string() };
if new.is_empty() {
return Ok(error(NO_HIDDEN));
}
Ok(match rename_in(&mut disk, &path, &new) {
Ok(fs) => Data::Object(vec![("fs".into(), Data::String(fs))]),
Err(m) => error(m),
})
}
/// `createAlias(path, target)`: on Unix a symbolic link at `path` that leads to the real path of the
/// file `target`. `path` must be a place the script may write where nothing is, not even a link
/// that leads nowhere, and `target` a file the script may read. Every system that is not Unix gives
/// `{error}`.
fn create_alias(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let (path, to) = (arg_text(a, 0), arg_text(a, 1));
let mut disk = host.disk.borrow_mut();
let at = match disk.target(&path, false) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
if std::fs::symlink_metadata(&at).is_ok() {
return Ok(error(NAME_TAKEN));
}
if to.is_empty() {
return Ok(error(NOT_FOUND));
}
let real = match disk.stat(&to) {
Ok(Some(e)) if e.file => disk.checked(&to).ok().and_then(|p| disk.scope.locate(p).ok()),
Ok(Some(_)) => return Ok(error(NOT_REGULAR)),
Ok(None) => return Ok(error(NOT_FOUND)),
Err(m) => return Ok(error(m)),
};
let Some(real) = real else { return Ok(error(ACCESS_DENIED)) };
#[cfg(test)]
if let Some(hook) = BEFORE_ALIAS_LINK.with(|h| h.borrow_mut().take()) {
hook(&at);
}
Ok(make_link(&mut disk, &at, &real))
}
/// A symbolic link at the real path `at` that leads to the real path `real`. → `true`, or `{error}`.
#[cfg(unix)]
fn make_link(disk: &mut Disk, at: &Path, real: &Path) -> Data {
// Making the link fails when something took its place since it was looked up.
if std::os::unix::fs::symlink(real, at).is_err() {
return error(WRITE_FAILED);
}
// A link put in place of a folder above it since it was looked up may have taken the new link
// elsewhere: that link is removed again, when it is still the one made here.
let placed = at.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c == p));
let ours = std::fs::read_link(at).is_ok_and(|l| l == real);
if !placed {
if ours {
let _ = std::fs::remove_file(at);
}
return error(ACCESS_DENIED);
}
// Something else at `at` replaced the new link since it was made: it is left alone.
if !ours {
return error(WRITE_FAILED);
}
disk.wrote(at);
Data::Bool(true)
}
/// Every system that is not Unix: `{error}` with [`NO_ALIAS`].
#[cfg(not(unix))]
fn make_link(_: &mut Disk, _: &Path, _: &Path) -> Data {
error(NO_ALIAS)
}
/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on
@@ -2309,13 +2420,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
}))
};
let value = |s: &str| HostItem::Value(Data::String(s.to_string()));
let text = HostItem::Object(vec![
("notOpen".into(), value(NOT_OPEN)),
("badMode".into(), value(BAD_MODE)),
("noAlias".into(), value(NO_ALIAS)),
("noHidden".into(), value(NO_HIDDEN)),
("tooLarge".into(), value(TOO_LARGE)),
]);
let text =
HostItem::Object(vec![("notOpen".into(), value(NOT_OPEN)), ("badMode".into(), value(BAD_MODE)), ("tooLarge".into(), value(TOO_LARGE))]);
let system = if WINDOWS {
"Windows"
} else if cfg!(target_os = "macos") {
@@ -2357,6 +2463,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("create".into(), call(link, create)),
("setLength".into(), call(link, set_length)),
("setReadonly".into(), call(link, set_readonly)),
("setHidden".into(), call(link, set_hidden)),
("createAlias".into(), call(link, create_alias)),
("pick".into(), call(link, pick)),
];
realm.define_file_classes(items)
@@ -2367,9 +2475,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
#[cfg(test)]
pub(crate) type CopyHook = Box<dyn FnOnce(&Path, &Path)>;
/// Tests: what the next `createAlias` does with the real path of its link.
#[cfg(test)]
pub(crate) type AliasHook = Box<dyn FnOnce(&Path)>;
#[cfg(test)]
thread_local! {
pub(crate) static BEFORE_COPY_READ: std::cell::RefCell<Option<CopyHook>> = const { std::cell::RefCell::new(None) };
/// Tests: what the next `createAlias` does with the real path of its link, after looking it up
/// and before making the link.
pub(crate) static BEFORE_ALIAS_LINK: std::cell::RefCell<Option<AliasHook>> = const { std::cell::RefCell::new(None) };
/// Tests: while set, the bytes `flush` writes fail after the file was opened for them.
pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
+16 -1
View File
@@ -217,6 +217,15 @@ pub(crate) struct Files {
levels: usize,
/// The files `$.evalFile` is running, the script first.
frames: Vec<Frame>,
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
es2015: bool,
}
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
/// ECMAScript 5.1 with the ExtendScript extensions.
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
}
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
@@ -311,9 +320,15 @@ impl Files {
chain: real.into_iter().collect(),
levels: 0,
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
es2015: es2015_script(path),
}
}
/// The options a file of this run is parsed with, preprocessor lines aside.
pub(crate) fn options(&self) -> Options {
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
#[cfg(test)]
@@ -456,7 +471,7 @@ impl Files {
return Ok(());
}
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
let options = Options { preprocessor_lines: true, ..self.options() };
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
let mut cursor = 0usize;
for d in &program.directives {
+58 -4
View File
@@ -802,6 +802,35 @@ struct Host {
args: RefCell<(Data, u64)>,
/// The run's state of the script object model (`app`).
dom: dom::State,
/// The documents open when the run began as the person last left them, each with its own file
/// and the file it was read from ([`crate::DocState::as_person_left`],
/// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files
/// they link to from them ([`Host::linked`]).
run_docs: RefCell<Vec<RunDoc>>,
/// The files the documents open when the run began link to as the person left them
/// ([`crate::file_access::ScriptGate::linked`]).
linked: std::cell::OnceCell<crate::file_access::LinkedFiles>,
}
/// A document open when a run began, with its own file and the file it was read from.
type RunDoc = (Arc<crate::Document>, Option<String>, Option<String>);
impl Host {
/// The files the commands the run runs may read because the documents open when the run began
/// link to them, found once, from those documents as the person left them: a link a script's
/// command added or changed, in this run or an earlier one, and a document it opened, give it
/// no file to read.
fn linked(&self) -> crate::file_access::LinkedFiles {
self.linked
.get_or_init(|| {
let docs = std::mem::take(&mut *self.run_docs.borrow_mut());
let files = docs.iter().flat_map(|(d, path, from)| {
crate::cmd::links::files_linked(d, crate::cmd::links::LinkBase::of_files(path.as_deref(), from.as_deref()))
});
crate::file_access::ScriptGate::real_files(files.collect::<Vec<_>>())
})
.clone()
}
}
/// A run's host calls by kind, as its report gives them in `hostCallCounts`.
@@ -1244,9 +1273,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()) {
@@ -1501,7 +1540,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);
@@ -1999,11 +2038,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 => {
@@ -2073,6 +2117,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)) {
@@ -2098,6 +2150,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) {
@@ -2106,6 +2159,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(()) })