Merge main into fix/script-handles-after-revert

This commit is contained in:
dotCooCoo committed 2026-11-27 22:12:29 -08:00
commit 1371fdab0d
657 files changed
+50260 -4568

No files matched your search

+80 -12
View File
@@ -18,7 +18,8 @@
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! gives, and a script may name the application's members without `app.`, as
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
//! that holds for `activeDocument`, `documents` and `selection`.
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
//! document, as the same page says.
//!
//! VectorCraft's own rules:
//! - A document's selection lists the selected objects topmost first, as `pageItems` does, whatever
@@ -29,8 +30,8 @@
//! - Assigning `activeDocument` or `selection` without `app.` assigns `app.activeDocument` or the
//! active document's selection. A top-level `var selection = ...` does the same and does
//! not make a variable of the script. Assigning `documents` keeps its value.
//! - Collections list documents in tab order. The objectReferences page says `documents[0]` is
//! always the active document; VectorCraft does not follow that yet.
//! - After `documents[0]`, documents are listed from the one active most recently to the one
//! active longest ago. A change a script makes to a document in the back does not move it.
//! - `pageItems` lists every object, with the objects inside groups and compound paths after the
//! group or compound path, and leaves out layers and ruler guides. An index out of range gives
//! `undefined`; `index` and `getByName` throw `Not found` when nothing matches.
@@ -66,6 +67,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMem
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
use crate::{DocState, Document, NodeId, NodeKind, Session};
mod tags;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -664,11 +667,11 @@ fn on_doc<T>(
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before, layer) = {
let (index, active, before, layer, activated) = {
let s = h.session.borrow();
let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let st = &s.documents()[index];
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()))
(index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.activated)
};
let switch = active != Some(index);
if switch {
@@ -694,6 +697,13 @@ fn on_doc<T>(
Some(a) if switch => command(h, "document.activate", &json!({"index": a})).map(drop),
_ => Ok(()),
};
// The switch for the change does not move the document up in `documents`.
if switch
&& back.is_ok()
&& let Some(st) = h.session.borrow_mut().document_mut(uid)
{
st.activated = activated;
}
let v = r?;
restored?;
back?;
@@ -853,12 +863,17 @@ fn app_ref(_: &Host, _: &[Data]) -> Answer {
Ok(host_ref("Application", &[]))
}
/// The open documents in the order `documents` lists them ([`Session::front_order`]).
fn front_docs(s: &Session) -> impl Iterator<Item = &DocState> {
s.front_order().into_iter().map(|i| &s.documents()[i])
}
/// `documents[i]`, and `documents["name"]` as `getByName` reads it.
fn docs_at(h: &Host, a: &[Data]) -> Answer {
let s = h.session.borrow();
let at = match arg(a, 1) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| s.documents().get(i)),
Data::String(name) => match s.documents().iter().find(|d| d.title() == *name) {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()).and_then(|i| front_docs(&s).nth(i)),
Data::String(name) => match front_docs(&s).find(|d| d.title() == *name) {
None if !probing(a) => return Err(HostError::Error(NOT_FOUND.into())),
found => found,
},
@@ -870,7 +885,7 @@ fn docs_at(h: &Host, a: &[Data]) -> Answer {
fn docs_by_name(h: &Host, a: &[Data]) -> Answer {
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
let s = h.session.borrow();
let st = s.documents().iter().find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
let st = front_docs(&s).find(|d| d.title() == *name).ok_or_else(|| HostError::Error(NOT_FOUND.into()))?;
Ok(doc_ref(h, st.uid))
}
@@ -1193,8 +1208,58 @@ fn preset_of(h: &Host, d: &Data) -> Option<usize> {
(i < h.dom.presets.borrow().len()).then_some(i)
}
/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and
/// a value is checked when `addDocument` uses it.
/// The enumeration whose values the `DocumentPreset` setting `key` takes, when it takes one.
fn preset_enum(key: &str) -> Option<&'static str> {
Some(match key {
"artboardLayout" => "DocumentArtboardLayout",
"colorMode" => "DocumentColorSpace",
"previewMode" => "DocumentPreviewMode",
"rasterResolution" => "DocumentRasterResolution",
"transparencyGrid" => "DocumentTransparencyGrid",
"units" => "RulerUnits",
_ => return None,
})
}
/// Checks that `value` is of the kind the `DocumentPreset` setting `key` holds: a value of its
/// enumeration, a finite number, a title of at most [`MAX_TEXT_BYTES`] bytes, `true` or `false` for
/// `documentBleedLink`, or four finite numbers for `documentBleedOffsetRect`. `undefined` unsets any
/// setting, and the three settings `addDocument` does not apply yet also take `null`.
fn check_preset_value(key: &str, value: &Data) -> std::result::Result<(), HostError> {
let wrong = |kind: &str| Err(HostError::Type(format!("DocumentPreset.{key} must be {kind}")));
match value {
Data::Undefined => return Ok(()),
Data::Null if matches!(key, "documentBleedLink" | "documentBleedOffsetRect" | "transparencyGrid") => return Ok(()),
_ => {}
}
if let Some(name) = preset_enum(key) {
let member = ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m);
return match value {
Data::String(s) if s.strip_prefix(name).and_then(|r| r.strip_prefix('.')).is_some_and(|m| member.contains(&m)) => Ok(()),
_ => wrong(&format!("a {name} value")),
};
}
match key {
"title" => match value {
Data::String(t) if t.len() > MAX_TEXT_BYTES => Err(HostError::Range("the title is too long".into())),
Data::String(_) => Ok(()),
_ => wrong("a string"),
},
"documentBleedLink" => match value {
Data::Bool(_) => Ok(()),
_ => wrong("true or false"),
},
"documentBleedOffsetRect" => match value {
Data::Array(r) if r.len() == 4 && r.iter().all(|n| matches!(n, Data::Number(n) if n.is_finite())) => Ok(()),
_ => wrong("an array of four finite numbers"),
},
_ => number(value, &format!("DocumentPreset.{key}")).map(|_| ()),
}
}
/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`. The
/// setter checks the kind and size of a value ([`check_preset_value`]) and keeps the old value when
/// it throws; `addDocument` checks the ranges.
fn preset_field(link: &Link, key: &'static str) -> HostMember {
let not_preset = || HostError::Type("this is not a DocumentPreset".into());
let l = link.clone();
@@ -1214,6 +1279,7 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember {
let value = arg(&a, 1).clone();
h.charge_call(16 + data_size(&value))?;
let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?;
check_preset_value(key, &value)?;
let mut presets = h.dom.presets.borrow_mut();
let fields = &mut presets[i];
match fields.iter_mut().find(|(k, _)| k == key) {
@@ -1368,7 +1434,7 @@ fn selection_of(h: &Host, uid: u64) -> Answer {
/// `[]`. Every one must be an object of that document that can be selected.
fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result<Vec<NodeId>, HostError> {
let list: Vec<&Data> = match v {
Data::Null | Data::Undefined => Vec::new(),
Data::Null => Vec::new(),
Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))),
Data::Array(a) => a.iter().collect(),
d => vec![d],
@@ -2225,6 +2291,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
.into_iter()
.map(|m| later(l, "Document", m)),
);
document.push(("tags".into(), get(l, tags::doc_tags)));
classes.push(class("Document", None, document, None));
classes.push(class(
"PageItems",
@@ -2245,6 +2312,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
("parent", get(l, item_parent)),
("name", property(l, item_name, item_set_name)),
("note", property(l, item_note, item_set_note)),
("tags", get(l, tags::item_tags)),
("hidden", property(l, item_hidden, item_set_hidden)),
("locked", property(l, item_locked, item_set_locked)),
("selected", property(l, item_selected, item_set_selected)),
@@ -2273,7 +2341,6 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
"layer",
"pixelAligned",
"sliced",
"tags",
"uRL",
"uuid",
"visibilityVariable",
@@ -2297,6 +2364,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
named(vec![("typename", get(l, layer_typename)), ("name", get(l, layer_name)), ("toString", method(l, layer_to_string))]),
None,
));
classes.extend(tags::classes(l));
realm.define_host_classes(classes, vec![("app".into(), host_ref("Application", &[]))])?;
// The application's members a script may name without `app.`, assigned as `app.<member>` is.
realm.define_host_globals(vec![
+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
@@ -1026,7 +1026,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()
@@ -1041,11 +1041,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"));
@@ -1068,7 +1068,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"))
}
@@ -1080,14 +1080,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)?;
@@ -1670,8 +1684,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);
@@ -1679,7 +1697,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.
@@ -1861,6 +1879,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();
@@ -2466,8 +2706,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
@@ -2487,6 +2739,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)))
}
+53 -7
View File
@@ -72,6 +72,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;
@@ -186,6 +187,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,
@@ -1716,9 +1718,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.
@@ -1931,9 +1934,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();
@@ -1941,9 +1945,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;
@@ -1975,6 +1986,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<()> {
@@ -2194,8 +2215,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);
+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),
}