Merge main into feat/scripts-print-printer

This commit is contained in:
dotCooCoo committed 2026-11-27 22:14:06 -08:00
commit 18af8a2761
918 files changed
+91653 -7514

No files matched your search

File diff suppressed because it is too large. Load diff
+306
View File
@@ -0,0 +1,306 @@
//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tags/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tag/> describe them: name and value pairs on a
//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0.
//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items,
//! and cannot add a tag, since a tag belongs to a page item.
//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and
//! `getByName` gives the first tag with the name.
//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags.
//! - A tag that was deleted, or whose page item was, throws an error on every member.
use std::ops::ControlFlow;
use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
use super::{
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, text, typename, whole, with_doc,
};
use crate::NodeId;
use serde_json::json;
use vectorcraft_js::{Data, HostClass, HostError, HostMember, host_ref};
/// The error for a tag that was deleted, or that came from an earlier run.
pub const STALE_TAG: &str = "Stale tag";
/// The error of `Document.tags.add()`.
pub const NO_OWNER: &str = "A tag is added to a page item's tags, not to the document's";
/// What a `Tags` collection lists the tags of.
#[derive(Clone, Copy)]
enum Owner {
Item(Item),
Doc(Doc),
}
/// The owner of the `Tags` collection `d` names.
fn owner_of(h: &Host, d: &Data) -> std::result::Result<Owner, HostError> {
let Some(handle) = handle_of(d, "Tags") else { return Err(HostError::Type("this is not a Tags collection".into())) };
match handle.as_slice() {
[run, uid] => find_doc(h, *run, *uid).map(Owner::Doc).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into())),
[run, uid, high, low] => Ok(Owner::Item(resolve_item(h, *run, *uid, *high, *low)?)),
_ => Err(HostError::Type("this is not a Tags collection".into())),
}
}
/// The page item a handle's run, document uid and id (as [`id_parts`] gave it) name, which must
/// still be in its document.
fn resolve_item(h: &Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
let alive = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| typename(n).is_some()));
if !alive {
return Err(HostError::Error(STALE_ITEM.into()));
}
Ok(Item { doc, id })
}
/// Calls `f` with each tag `owner` lists, in order, and the page item it is on, until `f` breaks.
/// The tags are borrowed from the document, not copied. `Document.tags` charges the run by the
/// number of page items read.
fn each(h: &Host, owner: Owner, mut f: impl FnMut(NodeId, &ObjectTag) -> ControlFlow<()>) -> std::result::Result<(), HostError> {
match owner {
Owner::Item(item) => with_doc(h, item.doc, |_, st| {
if let Some(n) = st.doc.node(item.id) {
for t in crate::cmd::tags::tags_of(n) {
if f(item.id, t).is_break() {
break;
}
}
}
Ok(())
}),
Owner::Doc(doc) => with_doc(h, doc, |_, st| {
let ids = page_items(h, st);
h.charge_call(ids.len() as u64)?;
for id in ids.iter() {
if let Some(n) = st.doc.node(*id) {
for t in crate::cmd::tags::tags_of(n) {
if f(*id, t).is_break() {
return Ok(());
}
}
}
}
Ok(())
}),
}
}
/// The first tag `owner` lists for which `pick` holds: its page item and its id.
fn find(h: &Host, owner: Owner, mut pick: impl FnMut(&ObjectTag) -> bool) -> std::result::Result<Option<(NodeId, u64)>, HostError> {
let mut found = None;
each(h, owner, |id, t| {
if pick(t) {
found = Some((id, t.id));
return ControlFlow::Break(());
}
ControlFlow::Continue(())
})?;
Ok(found)
}
fn doc_of_owner(owner: Owner) -> Doc {
match owner {
Owner::Item(i) => i.doc,
Owner::Doc(d) => d,
}
}
fn tag_ref(h: &Host, doc: Doc, id: NodeId, tag: u64) -> Data {
let [high, low] = id_parts(id);
let [tag_high, tag_low] = id_parts(NodeId(tag));
host_ref("Tag", &[float(h.run), float(doc.uid), high, low, tag_high, tag_low])
}
/// `PageItem.tags`.
pub(super) fn item_tags(h: &Host, a: &[Data]) -> Answer {
let item = item_of(h, arg(a, 0))?;
let [high, low] = id_parts(item.id);
Ok(host_ref("Tags", &[float(h.run), float(item.doc.uid), high, low]))
}
/// `Document.tags`.
pub(super) fn doc_tags(h: &Host, a: &[Data]) -> Answer {
let doc = doc_of(h, arg(a, 0), "Document")?;
Ok(host_ref("Tags", &[float(h.run), float(doc.uid)]))
}
// ---- Tags ----
fn tags_length(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let mut count = 0u64;
each(h, owner, |_, _| {
count += 1;
ControlFlow::Continue(())
})?;
Ok(num(float(count)))
}
fn tags_parent(h: &Host, a: &[Data]) -> Answer {
match owner_of(h, arg(a, 0))? {
Owner::Item(item) => Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))),
Owner::Doc(doc) => Ok(doc_ref(h, doc.uid)),
}
}
fn tags_at(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
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) };
let mut left = i;
let found = find(h, owner, |_| {
let here = left == 0;
left = left.wrapping_sub(1);
here
})?;
Ok(found.map_or(Data::Undefined, |(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)))
}
fn tags_by_name(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
let found = find(h, owner, |t| t.name == *name)?;
found.map(|(id, tag)| tag_ref(h, doc_of_owner(owner), id, tag)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
}
fn tags_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => tags_by_name(h, a),
Data::Number(_) => match tags_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `tags.add()`: a new tag with an empty name and value after the item's other tags.
fn tags_add(h: &Host, a: &[Data]) -> Answer {
let item = match owner_of(h, arg(a, 0))? {
Owner::Item(item) => item,
Owner::Doc(_) => return Err(HostError::Error(NO_OWNER.into())),
};
edit_item(h, item, "object.tag.add", &json!({"id": item.id.0}))?;
// The new tag is the item's last. Its id is read from the document, since the command's answer
// gives it as a number, which is exact only up to 2^53.
let tag = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).last().map(|t| t.id)));
let tag = tag.ok_or_else(|| HostError::Error("the tag was not added".into()))?;
Ok(tag_ref(h, item.doc, item.id, tag))
}
/// `tags.removeAll()`: deletes every tag in the collection, in one command.
fn tags_remove_all(h: &Host, a: &[Data]) -> Answer {
let owner = owner_of(h, arg(a, 0))?;
let mut ids: Vec<u64> = Vec::new();
each(h, owner, |id, _| {
if ids.last() != Some(&id.0) {
ids.push(id.0);
}
ControlFlow::Continue(())
})?;
if !ids.is_empty() {
let doc = doc_of_owner(owner);
on_doc(h, doc.uid, true, |h| command(h, "object.tag.removeAll", &json!({"ids": ids})))?;
}
Ok(Data::Undefined)
}
// ---- Tag ----
/// A tag: its page item and its id there.
#[derive(Clone, Copy)]
struct TagRef {
item: Item,
tag: u64,
}
/// The tag `d` names, which must still be on its page item.
fn tag_of(h: &Host, d: &Data) -> std::result::Result<(TagRef, ObjectTag), HostError> {
let Some(handle) = handle_of(d, "Tag") else { return Err(HostError::Type("this is not a Tag".into())) };
let [run, uid, high, low, tag_high, tag_low] = handle.as_slice() else { return Err(HostError::Type("this is not a Tag".into())) };
let item = resolve_item(h, *run, *uid, *high, *low)?;
let tag = id_of(*tag_high, *tag_low).ok_or_else(|| HostError::Error(STALE_TAG.into()))?.0;
let found = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(|n| crate::cmd::tags::tags_of(n).iter().find(|t| t.id == tag).cloned()));
let t = found.ok_or_else(|| HostError::Error(STALE_TAG.into()))?;
Ok((TagRef { item, tag }, t))
}
fn tag_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(tag_of(h, arg(a, 0))?.1.name))
}
fn tag_value(h: &Host, a: &[Data]) -> Answer {
Ok(text(tag_of(h, arg(a, 0))?.1.value))
}
/// Sets the tag's `key` (`name` or `value`) to the string the script gives, with no command when
/// it already has it.
fn set_text(h: &Host, a: &[Data], key: &str) -> Answer {
let Data::String(v) = arg(a, 1) else { return Err(HostError::Type(format!("{key} must be a string"))) };
if v.len() > MAX_TAG_TEXT {
return Err(HostError::Range(format!("a tag's {key} is longer than 65,536 bytes")));
}
let (t, now) = tag_of(h, arg(a, 0))?;
let same = if key == "name" { now.name == *v } else { now.value == *v };
if !same {
edit_item(h, t.item, "object.tag.set", &json!({"id": t.item.id.0, "tag": t.tag, key: v}))?;
}
Ok(Data::Undefined)
}
fn tag_set_name(h: &Host, a: &[Data]) -> Answer {
set_text(h, a, "name")
}
fn tag_set_value(h: &Host, a: &[Data]) -> Answer {
set_text(h, a, "value")
}
fn tag_parent(h: &Host, a: &[Data]) -> Answer {
let (t, _) = tag_of(h, arg(a, 0))?;
Ok(with_doc(h, t.item.doc, |_, st| item_ref(h, st, t.item.id)))
}
fn tag_remove(h: &Host, a: &[Data]) -> Answer {
let (t, _) = tag_of(h, arg(a, 0))?;
edit_item(h, t.item, "object.tag.remove", &json!({"id": t.item.id.0, "tag": t.tag}))?;
Ok(Data::Undefined)
}
/// `Tags.typename`, which throws like every other member once the collection's owner is gone.
fn tags_typename(h: &Host, a: &[Data]) -> Answer {
owner_of(h, arg(a, 0))?;
Ok(text("Tags"))
}
/// `Tag.typename`, which throws like every other member once the tag is gone.
fn tag_typename(h: &Host, a: &[Data]) -> Answer {
tag_of(h, arg(a, 0))?;
Ok(text("Tag"))
}
/// The `Tags` and `Tag` classes.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
let tags: Vec<(String, HostMember)> = named(vec![
("typename", get(l, tags_typename)),
("length", get(l, tags_length)),
("parent", get(l, tags_parent)),
("index", method(l, tags_index)),
("getByName", method(l, tags_by_name)),
("add", method(l, tags_add)),
("removeAll", method(l, tags_remove_all)),
]);
let tag = named(vec![
("typename", get(l, tag_typename)),
("name", property(l, tag_name, tag_set_name)),
("value", property(l, tag_value, tag_set_value)),
("parent", get(l, tag_parent)),
("remove", method(l, tag_remove)),
]);
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
}
+270 -11
View File
@@ -1068,7 +1068,7 @@ const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50);
/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the
/// lock cannot be taken.
#[cfg(not(target_arch = "wasm32"))]
fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
pub(crate) fn lock_store(store: &Path) -> std::io::Result<crate::store::LockedFile> {
let lock = store.with_extension("lock");
let opened = store
.parent()
@@ -1083,11 +1083,11 @@ fn lock_store(store: &Path) -> std::io::Result<std::fs::File> {
/// `file`, locked within [`lock_store`]'s tries.
#[cfg(not(target_arch = "wasm32"))]
fn take_lock(file: std::fs::File) -> std::io::Result<std::fs::File> {
fn take_lock(file: std::fs::File) -> std::io::Result<crate::store::LockedFile> {
let mut tries = 1;
loop {
match file.try_lock() {
Ok(()) => return Ok(file),
Ok(()) => return Ok(crate::store::LockedFile::new(file)),
Err(std::fs::TryLockError::Error(e)) => return Err(e),
Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => {
return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock"));
@@ -1110,7 +1110,7 @@ thread_local! {
/// The browser has no folders to keep anything in.
#[cfg(target_arch = "wasm32")]
fn lock_store(_: &Path) -> std::io::Result<std::fs::File> {
fn lock_store(_: &Path) -> std::io::Result<crate::store::LockedFile> {
Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system"))
}
@@ -1122,14 +1122,28 @@ pub(crate) fn stored_grants(data_dir: &Path) -> std::io::Result<Vec<serde_json::
/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path
/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`).
/// → how many were removed.
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result<usize> {
/// The spellings of each are tried in order, the script's first, and the first pair that some grant
/// holds is the one removed, so a grant kept under the spellings given first is removed without the
/// grants of later ones. → how many were removed.
pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&[String]>, path: Option<&[String]>) -> std::io::Result<usize> {
let store = data_dir.with_file_name(GRANTS_FILE);
let _lock = lock_store(&store)?;
let grants = try_read_store(&store)?;
let before = grants.len();
let kept: Vec<serde_json::Value> =
grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect();
// `None` matches any value; `Some(name)` only that name.
fn spellings(names: Option<&[String]>) -> Vec<Option<&str>> {
match names {
None => vec![None],
Some(names) => names.iter().map(|n| Some(n.as_str())).collect(),
}
}
let matches = |g: &serde_json::Value, (script, path): (Option<&str>, Option<&str>)| {
script.is_none_or(|s| g["script"] == s) && path.is_none_or(|p| g["path"] == p)
};
let pairs = spellings(script).into_iter().flat_map(|s| spellings(path).into_iter().map(move |p| (s, p)));
let pair = pairs.into_iter().find(|&pair| grants.iter().any(|g| matches(g, pair)));
let Some(pair) = pair else { return Ok(0) };
let kept: Vec<serde_json::Value> = grants.into_iter().filter(|g| !matches(g, pair)).collect();
let removed = before - kept.len();
if removed > 0 {
write_store(&store, kept)?;
@@ -1712,8 +1726,12 @@ fn millis(t: Option<std::time::SystemTime>) -> Data {
/// One host function of `__vcFiles`, counted and charged as a host call of the run `link` holds.
fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
HostItem::Function(call_function(link, f))
}
fn call_function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> vectorcraft_js::HostFunction {
let l = link.clone();
HostItem::Function(Rc::new(move |a| {
Rc::new(move |a| {
let h = super::current(&l)?;
bump(&h.counts.file_calls);
let r = f(&h, &a);
@@ -1721,7 +1739,7 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) ->
let r = r?;
h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?;
Ok(r)
}))
})
}
/// `Ok(true)`, or `{error}` for a failure.
@@ -1903,6 +1921,228 @@ fn copy(host: &Host, a: &[Data]) -> Result<Data, HostError> {
Ok(done(r.map_err(|_| WRITE_FAILED)))
}
/// Is `path` an XMP sidecar file, by its `.xmp` extension in any case?
fn is_sidecar(path: &str) -> bool {
Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp"))
}
/// The text of a sidecar's bytes and its character form as `XMPFile.getPacketInfo` gives it: 0 for
/// UTF-8, 2 for UTF-16 big-endian and 3 for UTF-16 little-endian, by its byte order mark.
fn sidecar_text(bytes: &[u8]) -> Option<(String, u32)> {
let utf16 = |rest: &[u8], big: bool| {
let units = rest.as_chunks::<2>().0.iter().map(|&pair| if big { u16::from_be_bytes(pair) } else { u16::from_le_bytes(pair) });
rest.len().is_multiple_of(2).then(|| char::decode_utf16(units).collect::<Result<String, _>>().ok()).flatten()
};
match bytes {
[0xEF, 0xBB, 0xBF, rest @ ..] => std::str::from_utf8(rest).ok().map(|t| (t.to_string(), 0)),
[0xFE, 0xFF, rest @ ..] => utf16(rest, true).map(|t| (t, 2)),
[0xFF, 0xFE, rest @ ..] => utf16(rest, false).map(|t| (t, 3)),
_ => std::str::from_utf8(bytes).ok().map(|t| (t.to_string(), 0)),
}
}
/// `xmpOpen(path, update, scan)`: the XMP packet of the file at `path` for `XMPFile`, read under
/// the rules for reading; with `update`, a file that can take a packet must also be one the run may write. A `.xmp` file
/// is read whole as its packet unless `scan`; any other file is scanned for its first UTF-8 packet.
/// → `{packet, offset, length, writeable, sidecar, charForm}`, with `packet` null when the file has
/// none.
fn xmp_open(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let path = arg_text(a, 0);
let (update, scan) = (matches!(a.get(1), Some(Data::Bool(true))), matches!(a.get(2), Some(Data::Bool(true))));
let mut disk = host.disk.borrow_mut();
match disk.stat(&path) {
Ok(Some(e)) if !e.file => return Ok(error(NOT_REGULAR)),
Ok(Some(e)) if e.len > MAX_FILE_BYTES as u64 => return Ok(error(TOO_LARGE)),
Ok(Some(_)) => {}
Ok(None) => return Ok(error(NOT_FOUND)),
Err(m) => return Ok(error(m)),
}
let (real, bytes) = match disk.scope.read(Path::new(&path), MAX_FILE_BYTES) {
Ok(read) => read,
Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)),
Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)),
Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)),
Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)),
};
disk.charge_read(&real, bytes.len())?;
let sidecar = is_sidecar(&path) && is_sidecar(&real.to_string_lossy()) && !scan;
// Only a file that can take a packet needs to be one the run may write.
if update
&& sidecar
&& let Err(m) = disk.target(&path, true)
{
return Ok(error(m));
}
let number = |n: usize| Data::Number(n as f64);
let (packet, offset, length, writeable, char_form) = if sidecar {
let Some((text, form)) = sidecar_text(&bytes) else { return Ok(error(UNDECODABLE)) };
(Data::String(text), 0, bytes.len(), true, form)
} else {
match vectorcraft_js::find_xmp_packet(&bytes) {
Some(span) => match bytes.get(span.start..span.end).map(std::str::from_utf8) {
Some(Ok(text)) => (Data::String(text.to_string()), span.start, span.end - span.start, span.writeable, 0),
_ => return Ok(error(UNDECODABLE)),
},
None => (Data::Null, 0, 0, false, 0),
}
};
Ok(Data::Object(vec![
("packet".into(), packet),
("offset".into(), number(offset)),
("length".into(), number(length)),
("writeable".into(), Data::Bool(writeable)),
("sidecar".into(), Data::Bool(sidecar)),
("charForm".into(), Data::Number(f64::from(char_form))),
]))
}
fn xmp_utf8_packet(text: &str) -> Result<Vec<u8>, &'static str> {
let body = text.strip_prefix('\u{feff}').unwrap_or(text);
if body.starts_with("<?xml") && body.as_bytes().get(5).is_some_and(|byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) {
let options = craft_xml::Options { pis: true, comments: true, drop_blank_text: false, ..craft_xml::Options::default() }.strict();
let mut events = options.events(body.as_bytes());
match events.next() {
Ok(Some(_)) => Ok(body.as_bytes()[events.span().start..].to_vec()),
_ => Err(UNDECODABLE),
}
} else {
Ok(text.as_bytes().to_vec())
}
}
/// `xmpWrite(path, packet, safely)`: the `.xmp` file at `path` replaced by `packet` in UTF-8, under
/// the rules for writing. The packet goes to a temporary file in the same folder that then takes the
/// file's name, when the run may write there; otherwise to the file itself, unless `safely`, which
/// fails and leaves the file as it is. Open objects of the file hold the new bytes.
/// The writer omits a leading XML declaration.
/// On Unix, the destination folder is flushed after writing. A folder flush failure returns an
/// error after the written path is recorded and open readers receive the replacement packet.
fn xmp_write(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let path = arg_text(a, 0);
let packet = match xmp_utf8_packet(&arg_text(a, 1)) {
Ok(packet) => packet,
Err(message) => return Ok(error(message)),
};
let safely = matches!(a.get(2), Some(Data::Bool(true)));
if !is_sidecar(&path) {
return Ok(error(ACCESS_DENIED));
}
if packet.len() > MAX_FILE_BYTES {
return Ok(error(TOO_LARGE));
}
let mut disk = host.disk.borrow_mut();
let target = match disk.target(&path, true) {
Ok(t) => t,
Err(m) => return Ok(error(m)),
};
// A `.xmp` link that leads to another kind of file does not make that file a sidecar.
if !is_sidecar(&target.to_string_lossy()) {
return Ok(error(ACCESS_DENIED));
}
if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) {
return Ok(error(NOT_REGULAR));
}
// An open object of the file with changes not yet written keeps them: the packet is not written
// over them.
if disk.open.values().any(|o| o.dirty && o.holds(&target)) {
return Ok(error(WRITE_FAILED));
}
let name = target.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let temp_name = |n: u32| target.with_file_name(format!(".{name}.{}.{n}.tmp", std::process::id()));
let first = temp_name(0);
let temp_allowed = disk.target(&first.to_string_lossy(), false).is_ok_and(|t| t == first);
// A safe update writes only through a temporary file.
if safely && !temp_allowed {
return Ok(error(WRITE_FAILED));
}
let holders = disk.open.values().filter(|o| o.holds(&target)).count();
disk.charge_write(packet.len().saturating_mul(holders.saturating_add(1)))?;
// `changed` is whether the file's bytes may differ from before: after a replacement, or once a
// direct write has opened (and so emptied) the file.
let (r, changed) = if temp_allowed {
// The temporary file takes a name no file or link has, so only the sidecar is replaced; when
// none of the names is free the sidecar is left as it is.
// Each name is checked against the places the run may write before it is made.
let allowed = |t: &Path| disk.target(&t.to_string_lossy(), false).is_ok_and(|r| r == t);
let new_file = |t: &Path| {
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
// On Unix the file starts readable and writable by its owner alone, until the packet is in
// it and the sidecar's permission bits are copied to it.
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
allowed(t).then(|| options.open(t).ok()).flatten()
};
let Some((temp, mut out)) = (0..16).map(temp_name).find_map(|t| new_file(&t).map(|f| (t, f))) else {
return Ok(error(WRITE_FAILED));
};
let mut write_temp = || {
#[cfg(test)]
if XMP_WRITE_FAILS.with(std::cell::Cell::get) {
return Err(std::io::Error::other("write failed"));
}
#[cfg(all(test, unix))]
{
let mode = std::os::unix::fs::PermissionsExt::mode(&out.metadata()?.permissions());
XMP_TEMP_MODE.with(|m| m.set(Some(mode)));
}
std::io::Write::write_all(&mut out, &packet)?;
// The packet is on the disk before it takes the sidecar's name, as a saved document's is.
#[cfg(not(target_arch = "wasm32"))]
vectorcraft_format::sync_file(&out)?;
Ok(())
};
let r = write_temp();
drop(out);
// The replacement keeps the sidecar's permission bits, group and (Linux) access ACL, or is
// readable by its owner alone, as a saved document is (`vectorcraft_format::keep_permissions`).
// On Windows the only permission is the read-only attribute, and a read-only temporary file
// could not be removed after a failed rename. The web build has no such files. Keeping them
// is best effort, as for a saved document: a volume without Unix permissions (SMB, FAT) refuses them, and the
// update still goes through.
#[cfg(not(target_arch = "wasm32"))]
if r.is_ok() {
let _ = vectorcraft_format::keep_permissions(&target, &temp);
}
let r = r.and_then(|()| std::fs::rename(&temp, &target)).inspect_err(|_| {
let _ = std::fs::remove_file(&temp);
});
let changed = r.is_ok();
(r, changed)
} else {
match std::fs::File::create(&target) {
Ok(mut f) => (std::io::Write::write_all(&mut f, &packet), true),
Err(e) => (Err(e), false),
}
};
if changed {
disk.wrote(&target);
}
if r.is_ok() {
for file in disk.open.values_mut().filter(|o| o.holds(&target)) {
let reset = file.bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || matches!(file.encoding, Encoding::Utf16Le | Encoding::Utf16Be);
file.bytes.clone_from(&packet);
// `File` readers with a UTF-8 byte order mark or UTF-16 encoding restart in UTF-8.
if reset {
file.encoding = Encoding::Utf8;
file.name = Encoding::Utf8.name().to_string();
file.pos = 0;
}
file.pos = file.pos.min(packet.len());
file.dirty = false;
}
}
#[cfg(all(unix, not(target_arch = "wasm32")))]
let r = r.and_then(|()| {
#[cfg(test)]
if XMP_DIRECTORY_SYNC_FAILS.with(std::cell::Cell::get) {
return Err(std::io::Error::other("directory flush failed"));
}
vectorcraft_format::sync_parent(&target)
});
Ok(done(r.map_err(|_| WRITE_FAILED)))
}
/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to.
fn remove(host: &Host, a: &[Data]) -> Result<Data, HostError> {
let mut disk = host.disk.borrow_mut();
@@ -2508,8 +2748,20 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr
("setHidden".into(), call(link, set_hidden)),
("createAlias".into(), call(link, create_alias)),
("pick".into(), call(link, pick)),
("xmpOpen".into(), call(link, xmp_open)),
(
"xmpWrite".into(),
HostItem::FunctionWithLimits {
limits: vectorcraft_js::DataLimits {
bytes: 3 * vectorcraft_js::XMP_MAX_BYTES + (128 << 10),
..vectorcraft_js::DataLimits::default()
},
function: call_function(link, xmp_write),
},
),
];
realm.define_file_classes(items)
realm.define_file_classes(items)?;
realm.define_external_object()
}
/// Tests: what the next `copy` does with its source's path, as given and as its real path, after
@@ -2529,6 +2781,13 @@ thread_local! {
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) };
/// Tests: while set, `xmpWrite` fails after its checks and before it writes.
pub(crate) static XMP_WRITE_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
#[cfg(unix)]
pub(crate) static XMP_DIRECTORY_SYNC_FAILS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Tests: the permission bits of the last temporary file `xmpWrite` made, before it wrote to it.
#[cfg(unix)]
pub(crate) static XMP_TEMP_MODE: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
+31 -8
View File
@@ -50,6 +50,30 @@ impl Default for Limits {
}
}
/// How a listing measures the time it has taken, which [`Limits::time`] bounds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Clock {
/// The real time since the listing started.
#[default]
Wall,
/// The same time at every check, whatever the real time: the listing reaches the time limit
/// only when this time is past it.
Fixed(Duration),
}
impl Clock {
/// Calls `f` with this clock's time since `f` was called.
pub fn time<T>(self, f: impl FnOnce(&mut dyn FnMut() -> Duration) -> T) -> T {
match self {
Clock::Wall => {
let start = std::time::Instant::now();
f(&mut || start.elapsed())
}
Clock::Fixed(elapsed) => f(&mut || elapsed),
}
}
}
/// One row of a listing.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Entry {
@@ -93,11 +117,10 @@ impl Listing {
}
}
/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives
/// an empty listing.
pub fn list(root: &Path) -> Listing {
let start = std::time::Instant::now();
list_with(root, &Limits::default(), &mut || start.elapsed())
/// What the folder `root` holds, within the default [`Limits`], with the time measured by `clock`.
/// A folder that does not exist gives an empty listing.
pub fn list(root: &Path, clock: Clock) -> Listing {
clock.time(|elapsed| list_with(root, &Limits::default(), elapsed))
}
/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken.
@@ -237,7 +260,7 @@ fn hidden(entry: &std::fs::DirEntry) -> bool {
/// Does Windows mark the file or folder of `m` hidden or system?
#[cfg(windows)]
fn hidden_meta(m: &std::fs::Metadata) -> bool {
pub(super) fn hidden_meta(m: &std::fs::Metadata) -> bool {
use std::os::windows::fs::MetadataExt as _;
const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4;
m.file_attributes() & HIDDEN_OR_SYSTEM != 0
@@ -245,13 +268,13 @@ fn hidden_meta(m: &std::fs::Metadata) -> bool {
/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name.
#[cfg(not(windows))]
fn hidden_meta(_: &std::fs::Metadata) -> bool {
pub(super) fn hidden_meta(_: &std::fs::Metadata) -> bool {
false
}
/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows
/// marks hidden or system, which a listing leaves out.
fn plain(path: &Path, folder: bool, shown: bool) -> bool {
pub(super) fn plain(path: &Path, folder: bool, shown: bool) -> bool {
std::fs::symlink_metadata(path)
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
}
+1 -1
View File
@@ -326,7 +326,7 @@ impl Files {
/// 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() }
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, e4x: true, ..Options::default() }
}
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
+126 -24
View File
@@ -77,6 +77,7 @@ use crate::{
pub mod files;
pub mod folder;
pub mod startup;
/// The most bytes of source a run takes, as a file or as `source`.
pub const MAX_SOURCE_BYTES: usize = 8 << 20;
@@ -191,6 +192,7 @@ pub(crate) fn refused_text(id: &str) -> String {
}
/// A request to run a script.
#[derive(Clone)]
pub(crate) struct Request {
/// The run's name; unless `name_given`, a `#script` line in the script replaces it.
pub name: String,
@@ -1080,7 +1082,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;
@@ -1641,16 +1643,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()
@@ -1674,24 +1670,31 @@ fn preprocessor_error(f: include::Failure) -> (RunError, Option<Arc<str>>) {
/// `e`, the error `realm` raised in the run of `host`, at the line and column of the file it is in,
/// with that file's name unless it is the run's own script.
fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<str>>) {
let map = |m: &include::SourceMap| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
};
// An error `$.evalFile` raised for a file it could not run, and no script caught, is at that
// file's place.
if let Some((file, line, column)) = realm.error_mark().and_then(|m| host.eval_failures.borrow().get(m as usize).cloned()) {
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
return (RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, Some(file));
}
placed(host, e, realm.error_source(), realm.error_tag())
}
/// `e`, raised at its line and column of the source `source` with tag `tag` ([`Realm::source_of`]
/// and [`Realm::error_tag`]), at the line and column of the file it is in, with that file's name
/// unless it is the run's own script.
fn placed(host: &Host, e: &RunError, source: u32, tag: u32) -> (RunError, Option<Arc<str>>) {
let map = |m: &include::SourceMap| {
let (index, file, line, column) = m.locate(e.line, e.column);
let message = if e.kind == RunErrorKind::Syntax { relocated(&e.message, e.line, e.column, line, column) } else { e.message.clone() };
(RunError { kind: e.kind.clone(), message, line, column, authored: e.authored }, index, file)
};
if e.line == 0 {
return (e.clone(), None);
}
// An error in code from a source whose map is not at hand, such as code that `eval` compiled,
// is given without a place.
let unplaced = || (RunError { line: 0, column: 0, ..e.clone() }, None);
match realm.error_source() {
match source {
0 => {
let (e, index, file) = map(&host.script_map.borrow());
(e, (index > 0).then_some(file))
@@ -1708,7 +1711,7 @@ fn located(host: &Host, realm: &Realm, e: &RunError) -> (RunError, Option<Arc<st
// `$.evalFile` gave. A script given as text is named by that run's name.
_ => {
let kept = host.kept_maps.as_ref().map(|k| k.borrow());
match kept.as_ref().and_then(|k| k.get(realm.error_tag())) {
match kept.as_ref().and_then(|k| k.get(tag)) {
Some(kept) => {
let (e, index, file) = map(&kept.map);
let file = match &kept.script {
@@ -1734,9 +1737,10 @@ fn relocated(message: &str, old_line: u32, old_column: u32, line: u32, column: u
}
impl Session {
/// Is a script running? While one is, the commands that change anything are refused.
/// Is a script running, or a run `script.startup.run` queued waiting to start at the next
/// [`Self::script_pump`]? While one is, the commands that change anything are refused.
pub fn script_running(&self) -> bool {
self.script_key.is_some()
self.script_key.is_some() || !self.script_queue.is_empty()
}
/// The named engine of the running script.
@@ -1965,9 +1969,10 @@ impl Session {
}
}
/// Asks the running script to stop; it is rolled back at the next slice. False with none running.
/// Asks the running script to stop; it is rolled back at the next slice. Between two runs
/// `script.startup.run` queued, the next one stops as it starts. False with none running.
pub fn script_request_stop(&mut self) -> bool {
if self.script_key.is_none() {
if !self.script_running() {
return false;
}
self.script_stop.set();
@@ -1975,9 +1980,16 @@ impl Session {
}
/// Stops the running script at once and puts everything back, with the report of a stopped run
/// ([`Self::script_report`]). False with none running.
/// ([`Self::script_report`]). Between two runs `script.startup.run` queued, the queued runs are
/// not started, and the report stays the last run's. False with none running or queued.
pub fn script_abandon(&mut self) -> bool {
let Some(key) = self.script_key.take() else { return false };
// The runs queued after it are not started.
let queued = !self.script_queue.is_empty();
self.script_queue.clear();
self.script_queue_scope = None;
self.script_queue_then = None;
self.startup_ended();
let Some(key) = self.script_key.take() else { return queued };
let Some(job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
self.script_gone(key, console::Ending::Stopped);
return true;
@@ -2009,6 +2021,16 @@ impl Session {
cmd::compositefonts::sync(self);
}
/// A script named `name` that did not start because its file could not be read as a script:
/// the Script Console gets a run with a start line, `message` as its error and an end line.
pub(crate) fn note_unread(&mut self, name: &str, message: &str) {
self.script_runs += 1;
let name = console::line_name(name);
for entry in [console::Entry::Start, console::Entry::Error(format!("{name}: {message}")), console::Entry::End(console::Ending::Error)] {
self.script_console.push(console::ConsoleLine { run: self.script_runs, name: name.clone(), entry }, false);
}
}
/// A script can't start while a document holds a drag in progress or an undo group, which its
/// one undo step could not take in.
fn settle_for_script(&mut self) -> Result<()> {
@@ -2066,15 +2088,19 @@ impl Session {
// from its first run, and they act for the run that calls them.
let fresh = realm.is_none();
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
// code the way the script does.
// code the way the script does. Its realm has `Promise`: a kept realm gets it at the first
// `.js` run that names it, and keeps it as it keeps its globals.
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 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);
if es2015 {
realm.add_es2015();
}
realm
}
None => {
@@ -2227,8 +2253,33 @@ impl Session {
}
/// Advances the running script by one slice. `None` while it is still running; otherwise the
/// run has ended: its report, or the error that ended it, with the documents put back.
/// run has ended: its report, or the error that ended it, with the documents put back. When
/// `script.startup.run` queued more runs, the next one starts at the pump after that, so the
/// ended run's report ([`Self::script_report`]) stays until then; a queued run that cannot start
/// is kept for [`Self::take_startup_failures`].
pub fn script_pump(&mut self) -> Option<Result<Value>> {
if self.script_key.is_none() {
// A stop asked for between two runs stops the run that starts now, which clears it.
let stop = self.script_stop.is_set();
self.start_queued();
if stop && (self.script_key.is_some() || !self.script_queue.is_empty()) {
self.script_stop.set();
} else {
self.script_stop.clear();
}
return None;
}
// Held aside while the run ends, so that its commit does not see the queue as a running script.
let queue = std::mem::take(&mut self.script_queue);
let result = self.pump_one();
self.script_queue = queue;
let result = result?;
self.startup_ended();
Some(result)
}
/// [`Self::script_pump`] for the running script alone.
fn pump_one(&mut self) -> Option<Result<Value>> {
let key = self.script_key.take()?;
let Some(mut job) = JOBS.with(|jobs| jobs.borrow_mut().remove(&key.id)) else {
self.script_gone(key, console::Ending::Internal);
@@ -2388,6 +2439,11 @@ impl Session {
report["prints"] = json!(prints.len());
self.script_prints = prints;
}
let rejections = rejections_report(host, &job.realm);
if let (false, Some(o)) = (rejections.is_empty(), report.as_object_mut()) {
o.insert("unhandledRejections".into(), Value::Array(rejections));
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
}
close_run(self, host, &mut report, console::Ending::Finished);
self.end_job(job, false);
self.script_report = Some(report.clone());
@@ -2433,6 +2489,29 @@ const NO_RUN: &str = "this function's script run has ended";
const DROP_MAIN: &str = "the main script engine is new for each run and is never kept, so it cannot be dropped";
const NO_ENGINES_ON_WEB: &str = "named script engines (#targetengine) are not available on the web";
const ENGINE_BUSY: &str = "the script engine is in use by another run";
const UNHANDLED_REJECTION: &str = "unhandled promise rejection";
const UNHANDLED_REJECTIONS: &str = "unhandled promise rejections";
/// The promises `realm`'s run rejected and left without a handler, each with its reason and, when
/// known, the line, column and file it was rejected at.
fn rejections_report(host: &Host, realm: &Realm) -> Vec<Value> {
let mut out = Vec::new();
for r in realm.unhandled_rejections() {
let e = RunError { kind: RunErrorKind::Thrown, message: r.message.clone(), line: r.line, column: r.column, authored: r.authored };
let (e, file) = placed(host, &e, realm.source_of(r.tag), r.tag);
let mut o = json!({
"message": e.message,
"messageOrigin": if e.authored { "script" } else { "built-in" },
"line": e.line,
"column": e.column,
});
if let (Some(file), Some(map)) = (file, o.as_object_mut()) {
map.insert("file".into(), json!(&*file));
}
out.push(o);
}
out
}
/// The report of a run that failed; `file` is the included file the error is in.
fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fuel_left: u64, fuel_used: u64) -> Value {
@@ -2513,6 +2592,18 @@ fn close_run(s: &mut Session, host: &Host, report: &mut Value, ending: console::
if report["ok"] == false {
each_line(&error_text(&host.name, report), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
}
if let Some(rejections) = report["unhandledRejections"].as_array() {
for r in rejections {
let mut placed = r.clone();
placed["message"] = json!(format!("{UNHANDLED_REJECTION}: {}", r["message"].as_str().unwrap_or_default()));
each_line(&error_text(&host.name, &placed), |line, cut| line_to(s, host, console::Entry::Error(line), cut));
}
let more = report["unhandledRejectionCount"].as_u64().unwrap_or(0).saturating_sub(rejections.len() as u64);
if more > 0 {
let text = format!("{}: {more} more {UNHANDLED_REJECTIONS}", host.name);
each_line(&text, |line, cut| line_to(s, host, console::Entry::Error(line), cut));
}
}
let timing = clock().is_some();
let ms = millis(host.run_nanos.get());
let slow = slowest(&host.commands.borrow());
@@ -2607,6 +2698,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)]
@@ -2624,6 +2724,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`].
+125
View File
@@ -0,0 +1,125 @@
//! The Startup Scripts folder: the `.jsx` files `script.startup.run` runs, one after another, when
//! the app starts and before a script chosen from File › Scripts runs ([`list`]), and the read of
//! one of them when its turn comes ([`read`]).
//!
//! Only the folder's own files are taken, never its subfolders. A listing follows no link: a
//! symbolic link or a Windows junction is left out, and so is a folder that is itself a link. Names
//! that start with a dot, files Windows marks hidden or system, names that are not Unicode, names
//! longer than [`folder::MAX_NAME_BYTES`] and files whose extension is not `.jsx` are left out too.
//! The files are sorted by name without regard to case, then by name.
//!
//! The limits are the Scripts folder's ([`folder::MAX_ENTRIES`], [`folder::MAX_SCRIPTS`] and
//! [`folder::MAX_SCAN`]), VectorCraft's own values. A listing that reaches one keeps what it found
//! and says so ([`Listing::truncated`]).
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use super::folder;
/// What a Startup Scripts folder holds.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Listing {
/// The scripts, in the order they run.
pub scripts: Vec<PathBuf>,
/// Some scripts may be missing: a limit was reached or an entry could not be read.
pub truncated: bool,
/// The folder is there and could not be read, or is a link.
pub unreadable: bool,
}
/// Does the file name `name` name a startup script: a `.jsx` file (in any case) whose name does not
/// start with a dot and has at most [`folder::MAX_NAME_BYTES`] bytes?
pub fn takes(name: &str) -> bool {
!name.starts_with('.')
&& name.len() <= folder::MAX_NAME_BYTES
&& Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("jsx"))
}
/// The startup scripts in `root`, within the Scripts folder's limits, with the time measured by
/// `clock`. A folder that does not exist gives an empty listing.
pub fn list(root: &Path, clock: folder::Clock) -> Listing {
clock.time(|elapsed| list_with(root, &folder::Limits::default(), elapsed))
}
/// The startup scripts in `root`, within `limits` (the entries, scripts and time ones);
/// `elapsed` says how long the listing has taken.
pub fn list_with(root: &Path, limits: &folder::Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing {
let unreadable = Listing { unreadable: true, ..Listing::default() };
match std::fs::symlink_metadata(root) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(),
Err(_) => return unreadable,
Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable,
Ok(_) => {}
}
if root.to_str().is_none() {
return unreadable;
}
let Ok(entries) = std::fs::read_dir(root) else { return unreadable };
let mut listing = Listing::default();
let mut names: Vec<String> = vec![];
for (visited, entry) in entries.enumerate() {
if visited >= limits.entries || elapsed() > limits.time {
listing.truncated = true;
break;
}
let Ok(entry) = entry else {
listing.truncated = true;
continue;
};
let Ok(name) = entry.file_name().into_string() else { continue };
if !takes(&name) {
continue;
}
let Ok(kind) = entry.file_type() else {
listing.truncated = true;
continue;
};
if !kind.is_file() || kind.is_symlink() || entry.metadata().is_ok_and(|m| folder::hidden_meta(&m)) {
continue;
}
names.push(name);
}
names.sort_by(|a, b| (a.to_lowercase(), a).cmp(&(b.to_lowercase(), b)));
if names.len() > limits.scripts {
listing.truncated = true;
names.truncate(limits.scripts);
}
listing.scripts = names.into_iter().map(|n| root.join(n)).collect();
listing
}
/// Is `path` a startup script a listing of `root` can hold now: a file [`takes`] names, directly in
/// `root`, where neither `root` nor the file is a link and the file is not marked hidden or system?
pub fn holds(root: &Path, path: &Path) -> bool {
if path.parent() != Some(root) {
return false;
}
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false };
takes(name) && folder::plain(root, true, false) && folder::plain(path, false, true)
}
/// The first `max` bytes of the startup script at `path`, or `None` when [`holds`] does not hold for
/// it before the read and again after it, or it cannot be read.
pub fn read(root: &Path, path: &Path, max: usize) -> Option<Vec<u8>> {
if !holds(root, path) {
return None;
}
let file = std::fs::File::open(path).ok()?;
if !file.metadata().is_ok_and(|m| m.is_file()) {
return None;
}
let mut bytes = vec![];
file.take(max as u64).read_to_end(&mut bytes).ok()?;
holds(root, path).then_some(bytes)
}
/// A run `script.startup.run` queued for the app, which starts it when the run before it ends.
#[derive(Clone, Debug, PartialEq)]
pub enum Queued {
/// A startup script, read when its turn comes, with its `maxFuel`.
Startup { path: PathBuf, fuel: u64 },
/// The script that runs after the startup scripts, as `script.run`'s parameters.
Then(serde_json::Value),
}