mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge main into feat/scripts-reflection
This commit is contained in:
commit
f56fcd99f6
812 files changed
+76558
-6091
No files matched your search
+165
-24
@@ -19,7 +19,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
|
||||
@@ -30,8 +31,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.
|
||||
@@ -76,6 +77,8 @@ use vectorcraft_js::{
|
||||
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.
|
||||
@@ -694,11 +697,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 {
|
||||
@@ -724,6 +727,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?;
|
||||
@@ -817,6 +827,62 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
/// lists, and `Fit Artboard to artwork bounds` is the one
|
||||
/// <https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee> gives for Object ›
|
||||
/// Artboards › Fit to Artwork Bounds.
|
||||
const MENU_COMMANDS: &[(&str, &str)] = &[
|
||||
("selectall", "select.all"),
|
||||
("deselectall", "select.none"),
|
||||
("group", "object.group"),
|
||||
("ungroup", "object.ungroup"),
|
||||
("makeMask", "object.clippingMask.make"),
|
||||
("releaseMask", "object.clippingMask.release"),
|
||||
("compoundPath", "object.compoundPath.make"),
|
||||
("noCompoundPath", "object.compoundPath.release"),
|
||||
("Fit Artboard to artwork bounds", "artboard.fitToArt"),
|
||||
];
|
||||
|
||||
/// `app.executeMenuCommand(name)`: runs the command of the menu item `name` names
|
||||
/// ([`MENU_COMMANDS`]) on the active document, as
|
||||
/// <https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts> describes the method. A
|
||||
/// name it does not list throws an error that names it. A menu item that is not available, with
|
||||
/// no document open or nothing selected that it acts on, does nothing, as a dimmed menu item does
|
||||
/// (VectorCraft's own rule). A menu item the menus show as available runs its command, and an error
|
||||
/// that command returns throws. `Fit Artboard to artwork bounds` fits the active artboard, and does
|
||||
/// nothing when that artboard is locked or has no art, as the canvas's right-click menu dims
|
||||
/// the item then ([`DocState::any_art_to_fit`]).
|
||||
fn app_menu_command(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("executeMenuCommand needs a menu command, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the menu command is too long".into()));
|
||||
}
|
||||
let Some(&(_, id)) = MENU_COMMANDS.iter().find(|(n, _)| n == name) else {
|
||||
return Err(HostError::Error(format!("executeMenuCommand: unknown menu command \"{name}\"")));
|
||||
};
|
||||
let params = {
|
||||
let s = h.session.borrow();
|
||||
let Some(spec) = crate::find_command(id) else { return Err(HostError::Abort(format!("executeMenuCommand: no command {id}"))) };
|
||||
if (spec.enabled)(&s).is_err() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
match (id, s.active()) {
|
||||
("artboard.fitToArt", Some(st)) => {
|
||||
let index = active_artboard(st);
|
||||
if !st.any_art_to_fit(&[index]) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
json!({"index": index})
|
||||
}
|
||||
_ => json!({}),
|
||||
}
|
||||
};
|
||||
command(h, id, ¶ms)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- Documents ----
|
||||
|
||||
fn docs_length(h: &Host, _: &[Data]) -> Answer {
|
||||
@@ -827,12 +893,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,
|
||||
},
|
||||
@@ -844,7 +915,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))
|
||||
}
|
||||
|
||||
@@ -1192,8 +1263,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();
|
||||
@@ -1213,6 +1334,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];
|
||||
// The values the presets hold now count against the run's heap: a value assigned again
|
||||
@@ -1456,6 +1578,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(text("PageItems"))
|
||||
}
|
||||
|
||||
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
items_doc(h, a)?;
|
||||
Ok(text("[PageItems]"))
|
||||
}
|
||||
|
||||
fn items_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = items_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
@@ -1615,16 +1742,23 @@ fn item_set_note(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// Refuses a change to the item's appearance, place, stacking order or size while a layer it is in
|
||||
/// is hidden or locked. Its name and note may still change.
|
||||
fn refuse_in_closed_layer(h: &Host, item: Item) -> std::result::Result<(), HostError> {
|
||||
/// Refuses appearance, place, stacking order and size changes in hidden or locked layers and on
|
||||
/// locked artboards. Names and notes may still change.
|
||||
fn refuse_protected_edit(h: &Host, item: Item) -> std::result::Result<(), HostError> {
|
||||
let refused = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let closed = |i: &NodeId| d.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. }) && (!n.visible || n.locked));
|
||||
d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)).then(|| d.node(item.id).and_then(typename).unwrap_or("page item"))
|
||||
let why = if d.ancestry(item.id).is_some_and(|a| a.iter().any(closed)) {
|
||||
Some("a layer it is in is hidden or locked")
|
||||
} else if on_locked_artboard(h, st, item.id) {
|
||||
Some("it is on a locked artboard")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
why.map(|why| (d.node(item.id).and_then(typename).unwrap_or("page item"), why))
|
||||
});
|
||||
match refused {
|
||||
Some(name) => Err(HostError::Error(format!("Cannot edit {name} {}: a layer it is in is hidden or locked", item.id.0))),
|
||||
Some((name, why)) => Err(HostError::Error(format!("Cannot edit {name} {}: {why}", item.id.0))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -1635,7 +1769,7 @@ fn item_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn item_set_hidden(h: &Host, a: &[Data]) -> Answer {
|
||||
let hidden = boolean(arg(a, 1), "hidden")?;
|
||||
refuse_in_closed_layer(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
set_props(h, a, |n| n.visible != hidden, json!({"visible": !hidden}))
|
||||
}
|
||||
|
||||
@@ -1645,7 +1779,7 @@ fn item_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
|
||||
fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
|
||||
let locked = boolean(arg(a, 1), "locked")?;
|
||||
refuse_in_closed_layer(h, this_item(h, a)?)?;
|
||||
refuse_protected_edit(h, this_item(h, a)?)?;
|
||||
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
|
||||
}
|
||||
|
||||
@@ -1673,7 +1807,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
(now, keeps_other)
|
||||
});
|
||||
if now.is_none() || keeps_other {
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
@@ -1777,7 +1911,8 @@ fn item_height(h: &Host, a: &[Data]) -> Answer {
|
||||
/// stays).
|
||||
fn move_to(h: &Host, a: &[Data], x: Option<f64>, y: Option<f64>) -> Answer {
|
||||
let item = this_item(h, a)?;
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), f) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let c = h.dom.coords.get();
|
||||
let now = f.to_script(c, Point::new(r.x0, r.y0));
|
||||
@@ -1814,7 +1949,8 @@ fn resize(h: &Host, a: &[Data], width: bool) -> Answer {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 3999856 points")));
|
||||
}
|
||||
let item = this_item(h, a)?;
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (Some(r), _) = item_rect(h, item, false)? else { return Ok(Data::Undefined) };
|
||||
let now = if width { r.width() } else { r.height() };
|
||||
if now <= 0.0 {
|
||||
@@ -2060,7 +2196,8 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
/// `zOrder(method)`: one of the four Object › Arrange commands for the item. A path inside a
|
||||
/// compound path is refused, and so is an object in a hidden or locked layer.
|
||||
/// compound path is refused. The item must be selectable and outside hidden or locked layers and
|
||||
/// locked artboards.
|
||||
fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
let id = match arg(a, 1) {
|
||||
Data::String(s) if s == "ZOrderMethod.BRINGTOFRONT" => "object.arrange.bringToFront",
|
||||
@@ -2073,7 +2210,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
|
||||
if in_compound(h, item) {
|
||||
return Err(HostError::Error(COMPOUND_MEMBER_ORDER.into()));
|
||||
}
|
||||
refuse_in_closed_layer(h, item)?;
|
||||
refuse_protected_edit(h, item)?;
|
||||
selection_ids(h, item.doc, arg(a, 0))?;
|
||||
let (before, after) = with_doc(h, item.doc, |_, st| {
|
||||
let at = st.doc.position(item.id);
|
||||
let count = at.and_then(|(p, ..)| st.doc.children(p).map(Vec::len)).unwrap_or(0);
|
||||
@@ -2217,6 +2355,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("selection", property(l, app_selection, app_set_selection), typed("*")),
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
("toString", class_text("Application"), returns("string", &[])),
|
||||
]);
|
||||
application.push(later(l, "Application", "beep"));
|
||||
@@ -2295,6 +2434,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
@@ -2306,7 +2446,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
|
||||
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
|
||||
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
|
||||
("toString", class_text("PageItems"), returns("string", &[])),
|
||||
("toString", method(l, items_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, items_at)),
|
||||
));
|
||||
@@ -2315,6 +2455,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("parent", get(l, item_parent), typed("*")),
|
||||
("name", property(l, item_name, item_set_name), typed("string")),
|
||||
("note", property(l, item_note, item_set_note), typed("string")),
|
||||
("tags", get(l, tags::item_tags), MemberInfo { collection: true, ..typed("Tags") }),
|
||||
("hidden", property(l, item_hidden, item_set_hidden), typed("boolean")),
|
||||
("locked", property(l, item_locked, item_set_locked), typed("boolean")),
|
||||
("selected", property(l, item_selected, item_set_selected), typed("boolean")),
|
||||
@@ -2349,7 +2490,6 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
"layer",
|
||||
"pixelAligned",
|
||||
"sliced",
|
||||
"tags",
|
||||
"uRL",
|
||||
"uuid",
|
||||
"visibilityVariable",
|
||||
@@ -2377,6 +2517,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.extend(tags::classes(l));
|
||||
classes
|
||||
}
|
||||
|
||||
|
||||
@@ -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, returns, text, typed, typename, whole, with_doc,
|
||||
};
|
||||
use crate::NodeId;
|
||||
use serde_json::json;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, 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 = named(vec![
|
||||
("typename", get(l, tags_typename), typed("string")),
|
||||
("length", get(l, tags_length), typed("number")),
|
||||
("parent", get(l, tags_parent), typed("*")),
|
||||
("index", method(l, tags_index), returns("Tag", &[("itemKey", "*")])),
|
||||
("getByName", method(l, tags_by_name), returns("Tag", &[("name", "string")])),
|
||||
("add", method(l, tags_add), returns("Tag", &[])),
|
||||
("removeAll", method(l, tags_remove_all), returns("undefined", &[])),
|
||||
]);
|
||||
let tag = named(vec![
|
||||
("typename", get(l, tag_typename), typed("string")),
|
||||
("name", property(l, tag_name, tag_set_name), typed("string")),
|
||||
("value", property(l, tag_value, tag_set_value), typed("string")),
|
||||
("parent", get(l, tag_parent), typed("PageItem")),
|
||||
("remove", method(l, tag_remove), returns("undefined", &[])),
|
||||
]);
|
||||
vec![class("Tags", None, tags, Some(super::function(l, tags_at))), class("Tag", None, tag, None)]
|
||||
}
|
||||
@@ -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)]
|
||||
|
||||
@@ -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)))
|
||||
}
|
||||
|
||||
+112
-15
@@ -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,
|
||||
@@ -1666,24 +1668,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))
|
||||
@@ -1700,7 +1709,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 {
|
||||
@@ -1726,9 +1735,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.
|
||||
@@ -1941,9 +1951,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();
|
||||
@@ -1951,9 +1962,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;
|
||||
@@ -1985,6 +2003,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<()> {
|
||||
@@ -2042,7 +2070,8 @@ 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, e4x: true, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
@@ -2051,6 +2080,9 @@ impl Session {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
if es2015 {
|
||||
realm.add_es2015();
|
||||
}
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
@@ -2200,8 +2232,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);
|
||||
@@ -2355,6 +2412,11 @@ impl Session {
|
||||
"hostCalls": host.calls.get(),
|
||||
});
|
||||
host.more_written(&mut report);
|
||||
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());
|
||||
@@ -2400,6 +2462,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 {
|
||||
@@ -2480,6 +2565,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());
|
||||
|
||||
@@ -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),
|
||||
}
|
||||
Reference in new issue
Block a user