Merge main into feat/js-es2015-modules

This commit is contained in:
dotCooCoo committed 2026-11-28 19:45:10 -08:00
commit 3e2a615aee
948 files changed
+102581 -8012

No files matched your search

+218 -11
View File
@@ -21,8 +21,9 @@ use std::collections::VecDeque;
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
use super::{Host, console};
/// The most bytes (UTF-8) of a dialog's message.
@@ -48,6 +49,8 @@ pub enum DialogKind {
Alert,
Confirm,
Prompt,
/// A ScriptUI dialog's `show()` ([`super::scriptui`]).
Window,
}
impl DialogKind {
@@ -57,6 +60,7 @@ impl DialogKind {
Self::Alert => "alert",
Self::Confirm => "confirm",
Self::Prompt => "prompt",
Self::Window => "window",
}
}
}
@@ -85,6 +89,8 @@ pub enum DialogAnswer {
Confirm(bool),
/// OK with the field's text, or Cancel (`None`), for `prompt`.
Prompt(Option<String>),
/// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask.
Window(Vec<UiStep>),
}
impl DialogAnswer {
@@ -93,13 +99,14 @@ impl DialogAnswer {
Self::Ok => DialogKind::Alert,
Self::Confirm(_) => DialogKind::Confirm,
Self::Prompt(_) => DialogKind::Prompt,
Self::Window(_) => DialogKind::Window,
}
}
/// What the function returns.
fn data(&self) -> Data {
match self {
Self::Ok => Data::Undefined,
Self::Ok | Self::Window(_) => Data::Undefined,
Self::Confirm(b) => Data::Bool(*b),
Self::Prompt(Some(t)) => Data::String(t.clone()),
Self::Prompt(None) => Data::Null,
@@ -112,6 +119,7 @@ impl DialogAnswer {
Self::Ok => json!("ok"),
Self::Confirm(b) => json!(b),
Self::Prompt(t) => json!(t),
Self::Window(steps) => json!(steps.len()),
}
}
}
@@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str {
}
/// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value:
/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter
/// took before dialogs existed, is an empty list.
/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}`
/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an
/// empty list.
pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, String> {
let list = match v {
None => return Ok(Vec::new()),
@@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result<Vec<DialogAnswer>, Stri
list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect()
}
fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") };
fn answer(a: &Value) -> Result<DialogAnswer, String> {
let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) };
if o.len() != 2 || !o.contains_key("value") {
return Err("must have exactly `kind` and `value`");
return Err("must have exactly `kind` and `value`".into());
}
if o.get("kind").and_then(Value::as_str) == Some("window") {
return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window);
}
known_answer(o).map_err(String::from)
}
fn known_answer(o: &Map<String, Value>) -> Result<DialogAnswer, &'static str> {
match (o.get("kind").and_then(Value::as_str), &o["value"]) {
(Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok),
(Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""),
@@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result<DialogAnswer, &'static str> {
(Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))),
(Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"),
(Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"),
_ => Err("must have `kind` alert, confirm or prompt"),
_ => Err("must have `kind` alert, confirm, prompt or window"),
}
}
@@ -199,6 +215,15 @@ pub(crate) struct Dialogs {
record_bytes: Cell<usize>,
count: Cell<u64>,
truncated: Cell<bool>,
/// The ScriptUI dialog whose `show()` is running.
window: RefCell<Option<Showing>>,
/// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler
/// opens is listed after it; `None` when the list had stopped at its limit.
window_slot: Cell<Option<usize>>,
/// That dialog waits for what the person does.
window_waiting: Cell<bool>,
/// The `show()` calls the run has made.
shows: Cell<u64>,
}
impl Dialogs {
@@ -213,6 +238,10 @@ impl Dialogs {
record_bytes: Cell::new(0),
count: Cell::new(0),
truncated: Cell::new(false),
window: RefCell::default(),
window_slot: Cell::new(None),
window_waiting: Cell::new(false),
shows: Cell::new(0),
}
}
@@ -222,7 +251,176 @@ impl Dialogs {
}
pub(crate) fn is_waiting(&self) -> bool {
self.waiting.borrow().is_some()
self.waiting.borrow().is_some() || self.window_waiting.get()
}
/// The ScriptUI dialog that waits for what the person does.
pub(crate) fn waiting_window(&self) -> Option<ScriptUiDialog> {
if !self.window_waiting.get() {
return None;
}
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs.
pub(crate) fn showing_window(&self) -> Option<ScriptUiDialog> {
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog.
pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> {
if !self.window_waiting.get() {
return Err("no script dialog waits".into());
}
let event = {
let mut window = self.window.borrow_mut();
let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) };
let event = scriptui::check_event(&showing.dialog, event)?;
showing.events = showing.events.saturating_add(1);
event
};
self.window_waiting.set(false);
if let Err(e) = realm.answer(event.data()) {
*self.failed.borrow_mut() = Some(e);
}
Ok(())
}
fn cannot_wait(&self) -> Result<(), HostError> {
if self.framed && !self.can_wait.get() {
return Err(HostError::Error(
"show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code"
.into(),
));
}
Ok(())
}
/// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a
/// `window` answer.
pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> {
self.cannot_wait()?;
self.shows.set(self.shows.get().saturating_add(1));
dialog.shown = self.shows.get();
let mut showing = Showing { dialog, steps: None, events: 0 };
if !self.framed {
let next = self.answers.borrow_mut().pop_front();
match next {
Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()),
Some(a) => {
self.push_record(showing.record(json!("missing")));
return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id())));
}
None => {
self.push_record(showing.record(json!("missing")));
return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into()));
}
}
}
self.window_slot.set(self.reserve_record());
*self.window.borrow_mut() = Some(showing);
Ok(())
}
/// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count
/// once the dialog ends. → the place, or `None` when the list stopped at its limit.
fn reserve_record(&self) -> Option<usize> {
self.count.set(self.count.get().saturating_add(1));
let mut records = self.records.borrow_mut();
if self.truncated.get() || records.len() >= MAX_RECORDS {
self.truncated.set(true);
return None;
}
records.push(Value::Null);
Some(records.len() - 1)
}
/// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took
/// in the list when it opened. When the dialogs a handler opened left no room for it, the list
/// drops the last of them until it fits, or stops before the dialog when it does not fit
/// alone, so it still holds the first dialogs in the order they opened, and is marked as
/// stopped at its limit.
fn end_record(&self, showing: &Showing, answer: Value) {
let Some(i) = self.window_slot.take() else { return };
let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len());
let r = showing.record(answer);
let bytes = size(&r);
let mut records = self.records.borrow_mut();
if i >= records.len() {
return;
}
while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 {
let last = records.pop().map_or(0, |r| size(&r));
self.record_bytes.set(self.record_bytes.get().saturating_sub(last));
self.truncated.set(true);
}
if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
records.truncate(i);
self.truncated.set(true);
return;
}
self.record_bytes.set(self.record_bytes.get() + bytes);
if let Some(slot) = records.get_mut(i) {
*slot = r;
}
}
/// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the
/// next step of its answer.
pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result<Data, HostError> {
self.cannot_wait()?;
let mut window = self.window.borrow_mut();
let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) };
dialog.shown = showing.dialog.shown;
showing.dialog = dialog;
let Some(steps) = showing.steps.as_mut() else {
drop(window);
self.window_waiting.set(true);
return Err(HostError::Wait);
};
let failure = match steps.pop_front() {
None => "show: the dialog's answer in `answers` has no step left".to_string(),
Some(step) => match scriptui::step_event(&showing.dialog, &step) {
Ok(event) => {
showing.events = showing.events.saturating_add(1);
return Ok(event.data());
}
Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"),
},
};
if let Some(showing) = window.take() {
self.end_record(&showing, json!("missing"));
}
Err(HostError::Abort(failure))
}
/// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask
/// must have used every step of the dialog's answer.
pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> {
self.window_waiting.set(false);
let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) };
let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len);
let steps = if left == 1 { "step" } else { "steps" };
let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use");
if normal && left > 0 {
self.end_record(&showing, json!("missing"));
return Err(HostError::Abort(unused));
}
// A show that a handler's error ended still ends the run when steps are left: the script
// can catch that error, and the run must not finish as if it took every step.
if left > 0 {
let mut failed = self.failed.borrow_mut();
if failed.is_none() {
*failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false });
}
}
let answer = match result {
_ if !normal => json!("error"),
r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64),
r => json!(r),
};
self.end_record(&showing, answer);
Ok(())
}
/// The error that ended the run when its answer could not reach the script.
@@ -257,10 +455,13 @@ impl Dialogs {
if let Some(d) = self.waiting.borrow_mut().take() {
self.record(&d, json!("stop"));
}
self.window_waiting.set(false);
if let Some(showing) = self.window.borrow_mut().take() {
self.end_record(&showing, json!("stop"));
}
}
fn record(&self, d: &ScriptDialog, answer: Value) {
self.count.set(self.count.get().saturating_add(1));
let mut r = Map::new();
r.insert("kind".into(), json!(d.kind.id()));
r.insert("message".into(), json!(d.message));
@@ -269,9 +470,14 @@ impl Dialogs {
DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)),
DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)),
DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)),
DialogKind::Window => None,
};
r.insert("answer".into(), answer);
let r = Value::Object(r);
self.push_record(Value::Object(r));
}
fn push_record(&self, r: Value) {
self.count.set(self.count.get().saturating_add(1));
let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len());
let mut records = self.records.borrow_mut();
if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES {
@@ -325,6 +531,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result<Data, HostError>
let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) };
(text(args, 2), false, false, preset)
}
DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())),
};
if message.len() > MAX_MESSAGE_BYTES {
return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB")));
File diff suppressed because it is too large. Load diff
+306
View File
@@ -0,0 +1,306 @@
//! `PageItem.tags`, `Document.tags` and the `Tag` objects in them, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tags/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Tag/> describe them: name and value pairs on a
//! page item, which the native file keeps. Each change runs one of the `object.tag.*` commands.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A `Tags` collection is live: it lists the tags in their order on the object, counted from 0.
//! `Document.tags` lists the tags of every page item, in the order `pageItems` lists the items,
//! and cannot add a tag, since a tag belongs to a page item.
//! - `add()` gives a tag with an empty name and value. Names may be empty or repeated, and
//! `getByName` gives the first tag with the name.
//! - `name` and `value` are strings of at most 65,536 bytes, and an object has at most 64 tags.
//! - A tag that was deleted, or whose page item was, throws an error on every member.
use std::ops::ControlFlow;
use vectorcraft_doc::{MAX_TAG_TEXT, ObjectTag};
use super::{
Answer, Doc, Host, Item, Link, NOT_FOUND, STALE_DOCUMENT, STALE_ITEM, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float, get,
handle_of, id_of, id_parts, item_of, item_ref, method, named, num, on_doc, page_items, property, 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)]
}
+816
View File
@@ -0,0 +1,816 @@
//! Variables and data sets in the script object model: `Document.variables`, `dataSets`,
//! `activeDataset`, `variablesLocked`, `importVariables` and `exportVariables`, the `Variables`,
//! `Variable`, `Datasets` and `Dataset` classes, and the variables page items are bound to, as the
//! help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Variables/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Variable/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/> describe them. Every change runs
//! one of the `variable.*` and `dataset.*` commands.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A `Variable` or a `Dataset` names its variable or data set by name. A rename or kind change
//! made through the object keeps the object working; once the name leaves the document any other
//! way (a delete, a rename by another command, an undo, a kind change by another command, or an
//! import that replaces the data sets), the object throws [`STALE_VARIABLE`] or
//! [`STALE_DATASET`] on every member, also after the name comes back. A run holds at most
//! [`MAX_HANDLES`] of each.
//! - Collections list variables and data sets in the order the document holds them, counted from
//! 0. An index out of range gives `undefined`; `index` and `getByName` throw `Not found`.
//! - `Variables.add()` defines a text variable named `Variable1`, `Variable2` and so on, the first
//! name that is free. `Datasets.add()` captures what the bound objects hold now as a new data
//! set named `Data Set 1` and so on, which becomes the active one.
//! - Kinds are the strings `VariableKind.TEXTUAL`, `VariableKind.VISIBILITY`, `VariableKind.IMAGE`,
//! `VariableKind.GRAPH` and `VariableKind.Unknown`; `Unknown` is the kind of a variable a file
//! declared without one VectorCraft knows, and cannot be given.
//! - `Variable.pageItems` is a new array of the objects bound to the variable, in id order.
//! - `activeDataset` is `null` with no active data set; assigning a `Dataset` of the document shows
//! its values in the art, as `display()` does.
//! - `visibilityVariable` and `contentVariable` give the first variable of their kind bound to the
//! object, in the order the variables are defined, or `null`. Assigning a `Variable` binds the
//! object to it and unbinds the object's other variables of that kind; `null` unbinds them all.
//! An embedded image (`RasterItem`) cannot take an image variable.
//! - `importVariables` and `exportVariables` take a `File`, not a path. The file must be one the
//! script may read, or write, as its `File` objects may: the files of the open documents do not
//! count.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use serde_json::json;
use vectorcraft_js::{Data, HostClass, HostError, HostItem, MemberInfo, Realm, RunError, file_ref_path, host_ref};
use super::{
Answer, Described, Doc, Host, Link, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, arg, class, command, doc_of, doc_ref, edit_item, find_doc, float,
function, get, handle_of, item_of, item_ref, method, named, num, on_doc, property, returns, text, typed, typename, whole, with_doc,
};
use crate::doc::{DataSet, Node, Variable, VariableKind};
use crate::file_access::Access;
/// The error for a `Variable` whose variable left the document, or that came from an earlier run.
pub const STALE_VARIABLE: &str = "Stale variable";
/// The error for a `Dataset` whose data set left the document, or that came from an earlier run.
pub const STALE_DATASET: &str = "Stale data set";
/// The most `Variable` objects, and the most `Dataset` objects, one run gives out.
pub const MAX_HANDLES: usize = 10_000;
/// The kinds, each with the name of its `VariableKind` member.
const KINDS: [(VariableKind, &str); 5] = [
(VariableKind::Text, "TEXTUAL"),
(VariableKind::Visibility, "VISIBILITY"),
(VariableKind::Image, "IMAGE"),
(VariableKind::Graph, "GRAPH"),
(VariableKind::Unknown, "Unknown"),
];
/// What a `Variable` or `Dataset` object names: the document's uid, the name, the kind of a
/// variable (`None` for a data set) and whether it still names it.
struct Entry {
uid: u64,
name: String,
kind: Option<VariableKind>,
alive: bool,
}
/// The objects of one class a run gave out: each one's handle is its index here.
#[derive(Default)]
struct Table {
entries: Vec<Entry>,
/// The entry that names each document's name, while it does.
live: HashMap<(u64, String), usize>,
}
impl Table {
/// The entry for `name` of the document `uid`, made when there is none.
fn slot(&mut self, uid: u64, name: &str, kind: Option<VariableKind>, what: &str) -> std::result::Result<usize, HostError> {
if let Some(&at) = self.live.get(&(uid, name.to_string()))
&& self.entries.get(at).is_some_and(|e| e.alive && e.kind == kind)
{
return Ok(at);
}
if self.entries.len() >= MAX_HANDLES {
return Err(HostError::Range(format!("a script can hold at most {MAX_HANDLES} {what} objects in one run")));
}
self.entries.push(Entry { uid, name: name.to_string(), kind, alive: true });
let at = self.entries.len() - 1;
self.live.insert((uid, name.to_string()), at);
Ok(at)
}
/// The entry `at` no longer names anything.
fn kill(&mut self, at: usize) {
if let Some(e) = self.entries.get_mut(at) {
e.alive = false;
let k = (e.uid, std::mem::take(&mut e.name));
if self.live.get(&k) == Some(&at) {
self.live.remove(&k);
}
}
}
/// The entry `at` names `name`, of `kind`, from now on: a rename made through it.
fn rename(&mut self, at: usize, name: &str, kind: Option<VariableKind>) {
let Some(uid) = self.entries.get(at).map(|e| e.uid) else { return };
self.kill(at);
if let Some(e) = self.entries.get_mut(at) {
*e = Entry { uid, name: name.to_string(), kind, alive: true };
}
self.live.insert((uid, name.to_string()), at);
}
/// Kills each live entry `keep` refuses.
fn sweep(&mut self, keep: impl Fn(&Entry) -> bool) {
let gone: Vec<usize> = self.live.values().copied().filter(|at| self.entries.get(*at).is_none_or(|e| !keep(e))).collect();
for at in gone {
self.kill(at);
}
}
}
/// The `Variable` and `Dataset` objects of a run, and each document's revision when they were last
/// checked against it.
#[derive(Default)]
pub(super) struct Handles {
vars: RefCell<Table>,
sets: RefCell<Table>,
seen: RefCell<Vec<(u64, u64)>>,
}
/// The data sets of the active document before a command that may replace them (an import), while
/// the run holds a `Dataset`; `None` for any other command.
pub(super) fn before_command(h: &Host, id: &str) -> Option<(u64, Vec<DataSet>)> {
if !matches!(id, "dataset.import" | "variable.loadLibrary" | "variable.import") || h.dom.vars.sets.borrow().live.is_empty() {
return None;
}
let s = h.session.try_borrow().ok()?;
s.active().map(|st| (st.uid, st.doc.variables.datasets.clone()))
}
/// After each command a script runs: the objects whose variable or data set it removed stop
/// working, so one made again under the same name does not bring them back. An import that leaves
/// its document with other data sets than `before` ([`before_command`]) holds stops every `Dataset`
/// of that document, also when the new data sets reuse the names; an import that failed, was put
/// back or left the data sets as they were stops none.
pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<DataSet>)>) {
let hs = &h.dom.vars;
if hs.vars.borrow().live.is_empty() && hs.sets.borrow().live.is_empty() {
return;
}
let Ok(s) = h.session.try_borrow() else { return };
let replaced = before.and_then(|(uid, sets)| s.documents().iter().find(|d| d.uid == uid && d.doc.variables.datasets != sets).map(|d| d.uid));
let now: Vec<(u64, u64)> = s.documents().iter().map(|d| (d.uid, d.revision)).collect();
let changed: HashSet<u64> = {
let seen = hs.seen.borrow();
now.iter().filter(|n| !seen.contains(n)).chain(seen.iter().filter(|o| !now.iter().any(|n| n.0 == o.0))).map(|(uid, _)| *uid).collect()
};
*hs.seen.borrow_mut() = now;
if changed.is_empty() && replaced.is_none() {
return;
}
let mut kinds: HashMap<u64, HashMap<&str, VariableKind>> = HashMap::new();
let mut sets: HashMap<u64, HashSet<&str>> = HashMap::new();
for st in s.documents().iter().filter(|d| changed.contains(&d.uid)) {
let vars = &st.doc.variables;
kinds.insert(st.uid, vars.variables.iter().map(|v| (v.name.as_str(), v.kind)).collect());
sets.insert(st.uid, vars.datasets.iter().map(|d| d.name.as_str()).collect());
}
hs.vars.borrow_mut().sweep(|e| !changed.contains(&e.uid) || kinds.get(&e.uid).and_then(|k| k.get(e.name.as_str())).copied() == e.kind);
hs.sets
.borrow_mut()
.sweep(|e| Some(e.uid) != replaced && (!changed.contains(&e.uid) || sets.get(&e.uid).is_some_and(|n| n.contains(e.name.as_str()))));
}
fn kind_text(k: VariableKind) -> Data {
let name = KINDS.iter().find(|(kind, _)| *kind == k).map_or("Unknown", |(_, n)| n);
text(format!("VariableKind.{name}"))
}
fn kind_of(d: &Data) -> std::result::Result<VariableKind, HostError> {
let found = match d {
Data::String(s) => s.strip_prefix("VariableKind.").and_then(|m| KINDS.iter().find(|(_, n)| *n == m)).map(|(k, _)| *k),
_ => None,
};
match found {
Some(VariableKind::Unknown) => Err(HostError::Error("a variable cannot be given the kind VariableKind.Unknown".into())),
Some(k) => Ok(k),
None => Err(HostError::Type("kind must be a VariableKind value".into())),
}
}
/// A name a script gives: a string of at most [`MAX_TEXT_BYTES`] bytes.
fn name_arg<'a>(d: &'a Data, what: &str) -> std::result::Result<&'a str, HostError> {
let Data::String(s) = d else { return Err(HostError::Type(format!("{what} must be a string"))) };
if s.len() > MAX_TEXT_BYTES {
return Err(HostError::Range(format!("the {what} is too long")));
}
Ok(s)
}
/// The `name` field of a command's result.
fn result_name(d: &Data) -> Option<String> {
let Data::Object(o) = d else { return None };
o.iter().find(|(k, _)| k == "name").and_then(|(_, v)| if let Data::String(s) = v { Some(s.clone()) } else { None })
}
fn var_ref(h: &Host, uid: u64, v: &Variable) -> Answer {
let at = h.dom.vars.vars.borrow_mut().slot(uid, &v.name, Some(v.kind), "Variable")?;
Ok(host_ref("Variable", &[float(h.run), float(at as u64)]))
}
fn set_ref(h: &Host, uid: u64, name: &str) -> Answer {
let at = h.dom.vars.sets.borrow_mut().slot(uid, name, None, "Dataset")?;
Ok(host_ref("Dataset", &[float(h.run), float(at as u64)]))
}
/// A variable or data set an object names: its document, its handle's index and its name.
struct Named {
doc: Doc,
at: usize,
name: String,
kind: Option<VariableKind>,
}
/// What the `Variable` (`variable`) or `Dataset` object `d` names, which must still be in its
/// document.
fn named_of(h: &Host, d: &Data, variable: bool) -> std::result::Result<Named, HostError> {
let (class, stale) = if variable { ("Variable", STALE_VARIABLE) } else { ("Dataset", STALE_DATASET) };
let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) };
let &[run, at] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {class}"))) };
let stale = || HostError::Error(stale.into());
if whole(run) != Some(h.run) {
return Err(stale());
}
let at = whole(at).and_then(|a| usize::try_from(a).ok()).ok_or_else(stale)?;
let table = if variable { &h.dom.vars.vars } else { &h.dom.vars.sets };
let (uid, name, kind) = {
let t = table.borrow();
let e = t.entries.get(at).filter(|e| e.alive).ok_or_else(stale)?;
(e.uid, e.name.clone(), e.kind)
};
let doc = find_doc(h, float(h.run), float(uid));
let there = doc.is_some_and(|doc| {
with_doc(h, doc, |_, st| {
let vars = &st.doc.variables;
if variable { vars.variable(&name).is_some_and(|v| Some(v.kind) == kind) } else { vars.dataset(&name).is_some() }
})
});
match doc {
Some(doc) if there => Ok(Named { doc, at, name, kind }),
_ => {
table.borrow_mut().kill(at);
Err(stale())
}
}
}
fn this_var(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
named_of(h, arg(a, 0), true)
}
fn this_set(h: &Host, a: &[Data]) -> std::result::Result<Named, HostError> {
named_of(h, arg(a, 0), false)
}
/// The index argument of a collection's indexer: a whole number, or `None`.
fn index_arg(d: &Data) -> Option<usize> {
match d {
Data::Number(n) => whole(*n).and_then(|i| usize::try_from(i).ok()),
_ => None,
}
}
// ---- Document ----
fn this_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Document")
}
fn doc_variables(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("Variables", &[float(h.run), float(doc.uid)]))
}
fn doc_datasets(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(host_ref("Datasets", &[float(h.run), float(doc.uid)]))
}
fn doc_locked(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
Ok(Data::Bool(with_doc(h, doc, |_, st| st.doc.variables.locked)))
}
/// `variablesLocked = flag`: `variable.lock`, with no command when it is already so.
fn doc_set_locked(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let Data::Bool(locked) = arg(a, 1) else { return Err(HostError::Type("variablesLocked must be true or false".into())) };
if with_doc(h, doc, |_, st| st.doc.variables.locked) != *locked {
on_doc(h, doc.uid, false, |h| command(h, "variable.lock", &json!({"locked": locked})))?;
}
Ok(Data::Undefined)
}
fn doc_active_dataset(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
match with_doc(h, doc, |_, st| st.doc.variables.active_dataset.clone()) {
Some(name) => set_ref(h, doc.uid, &name),
None => Ok(Data::Null),
}
}
/// Shows the data set `set` in the art with `dataset.select`, with no command when it is the active
/// one and the art already shows it.
fn display(h: &Host, set: &Named) -> Answer {
let shown = with_doc(h, set.doc, |_, st| {
let vars = &st.doc.variables;
vars.active_dataset.as_deref() == Some(set.name.as_str()) && vars.dataset(&set.name).is_some_and(|d| d.matches(&st.doc.captured_values()))
});
if !shown {
on_doc(h, set.doc.uid, false, |h| command(h, "dataset.select", &json!({"name": set.name})))?;
}
Ok(Data::Undefined)
}
fn doc_set_active_dataset(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
if handle_of(arg(a, 1), "Dataset").is_none() {
return Err(HostError::Type("activeDataset must be a Dataset".into()));
}
let set = named_of(h, arg(a, 1), false)?;
if set.doc.uid != doc.uid {
return Err(HostError::Error("the data set is in another document".into()));
}
display(h, &set)
}
/// The path of the `File` argument of `what`, which must be a file the script may reach for
/// `access` through its own `File` objects.
fn file_arg(h: &Host, a: &[Data], what: &str, access: Access) -> std::result::Result<String, HostError> {
let Some(path) = file_ref_path(arg(a, 1)) else { return Err(HostError::Type(format!("{what} needs a File"))) };
if path.chars().count() > super::super::files::MAX_PATH_CHARS {
return Err(HostError::Range(format!("{what}: the path is too long")));
}
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
gate.check(path, access).map_err(HostError::Error)?;
Ok(path.to_string())
}
/// `importVariables(file)`: `variable.loadLibrary` with the file, which replaces the document's
/// variables and data sets with the library's.
fn doc_import(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = file_arg(h, a, "importVariables", Access::Read)?;
on_doc(h, doc.uid, false, |h| command(h, "variable.loadLibrary", &json!({"path": path})))?;
Ok(Data::Undefined)
}
/// `exportVariables(file)`: `variable.saveLibrary` into the file.
fn doc_export(h: &Host, a: &[Data]) -> Answer {
let doc = this_doc(h, a)?;
let path = file_arg(h, a, "exportVariables", Access::Write)?;
on_doc(h, doc.uid, false, |h| command(h, "variable.saveLibrary", &json!({"path": path})))?;
Ok(Data::Undefined)
}
// ---- Variables ----
fn vars_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Variables")
}
fn vars_typename(h: &Host, a: &[Data]) -> Answer {
vars_doc(h, a)?;
Ok(text("Variables"))
}
fn vars_length(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.variables.len()) as u64)))
}
fn vars_parent(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn vars_at(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
match with_doc(h, doc, |_, st| st.doc.variables.variables.get(i).cloned()) {
Some(v) => var_ref(h, doc.uid, &v),
None => Ok(Data::Undefined),
}
}
fn vars_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let name = name_arg(arg(a, 1), "name")?;
let found = with_doc(h, doc, |_, st| {
h.charge_call(st.doc.variables.variables.len() as u64)?;
Ok::<_, HostError>(st.doc.variables.variable(name).cloned())
})?;
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |v| var_ref(h, doc.uid, &v))
}
fn vars_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => vars_by_name(h, a),
Data::Number(_) => match vars_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `variables.add()`: `variable.define` of a text variable named `Variable1`, `Variable2`… (the
/// first free name). → the new variable.
fn vars_add(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let name = with_doc(h, doc, |_, st| {
let vars = &st.doc.variables;
(1..=vars.variables.len() + 1).map(|i| format!("Variable{i}")).find(|n| vars.variable(n).is_none()).unwrap_or_default()
});
on_doc(h, doc.uid, false, |h| command(h, "variable.define", &json!({"name": name, "kind": "text"})))?;
var_ref(h, doc.uid, &Variable { name, kind: VariableKind::Text })
}
/// `variables.removeAll()`: one `variable.delete` of every variable, with no command when there is
/// none.
fn vars_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = vars_doc(h, a)?;
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.variables.iter().map(|v| v.name.clone()).collect());
if !names.is_empty() {
on_doc(h, doc.uid, false, |h| command(h, "variable.delete", &json!({"names": names})))?;
}
Ok(Data::Undefined)
}
// ---- Variable ----
fn var_typename(h: &Host, a: &[Data]) -> Answer {
this_var(h, a)?;
Ok(text("Variable"))
}
fn var_parent(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
Ok(doc_ref(h, v.doc.uid))
}
fn var_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(this_var(h, a)?.name))
}
/// `name = text`: `variable.rename`, which trims it, with no command when the name stays.
fn var_set_name(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
let to = name_arg(arg(a, 1), "name")?;
if to.trim() == v.name {
return Ok(Data::Undefined);
}
let r = on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "newName": to})))?;
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
h.dom.vars.vars.borrow_mut().rename(v.at, &name, v.kind);
Ok(Data::Undefined)
}
fn var_kind(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
Ok(kind_text(v.kind.unwrap_or(VariableKind::Unknown)))
}
/// `kind = VariableKind.…`: `variable.rename` with the kind, which unbinds the objects that cannot
/// hold it and drops the variable's values, with no command when the kind stays.
fn var_set_kind(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
let kind = kind_of(arg(a, 1))?;
if Some(kind) == v.kind {
return Ok(Data::Undefined);
}
on_doc(h, v.doc.uid, false, |h| command(h, "variable.rename", &json!({"name": v.name, "kind": kind.label()})))?;
h.dom.vars.vars.borrow_mut().rename(v.at, &v.name, Some(kind));
Ok(Data::Undefined)
}
fn var_page_items(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
with_doc(h, v.doc, |_, st| {
let ids: Vec<crate::NodeId> =
st.doc.variables.objects_of(&v.name).into_iter().filter(|i| st.doc.node(*i).and_then(typename).is_some()).collect();
if ids.len() > MAX_LISTED {
return Err(HostError::Range(format!("the variable is bound to more than {MAX_LISTED} objects")));
}
h.charge_call(16 * ids.len() as u64)?;
Ok(Data::Array(ids.iter().map(|i| item_ref(h, st, *i)).collect()))
})
}
/// `variable.remove()`: `variable.delete` of the variable, with its bindings and values.
fn var_remove(h: &Host, a: &[Data]) -> Answer {
let v = this_var(h, a)?;
on_doc(h, v.doc.uid, false, |h| command(h, "variable.delete", &json!({"names": [v.name]})))?;
h.dom.vars.vars.borrow_mut().kill(v.at);
Ok(Data::Undefined)
}
// ---- Datasets ----
fn sets_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "Datasets")
}
fn sets_typename(h: &Host, a: &[Data]) -> Answer {
sets_doc(h, a)?;
Ok(text("Datasets"))
}
fn sets_length(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| st.doc.variables.datasets.len()) as u64)))
}
fn sets_parent(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
fn sets_at(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let Some(i) = index_arg(arg(a, 1)) else { return Ok(Data::Undefined) };
match with_doc(h, doc, |_, st| st.doc.variables.datasets.get(i).map(|d| d.name.clone())) {
Some(name) => set_ref(h, doc.uid, &name),
None => Ok(Data::Undefined),
}
}
fn sets_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let name = name_arg(arg(a, 1), "name")?;
let found = with_doc(h, doc, |_, st| {
h.charge_call(st.doc.variables.datasets.len() as u64)?;
Ok::<_, HostError>(st.doc.variables.dataset(name).map(|d| d.name.clone()))
})?;
found.map_or_else(|| Err(HostError::Error(NOT_FOUND.into())), |n| set_ref(h, doc.uid, &n))
}
fn sets_index(h: &Host, a: &[Data]) -> Answer {
match arg(a, 1) {
Data::String(_) => sets_by_name(h, a),
Data::Number(_) => match sets_at(h, a)? {
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
d => Ok(d),
},
_ => Err(HostError::Type("give a name or an index".into())),
}
}
/// `dataSets.add()`: `dataset.capture`, which records what the bound objects hold now as a new
/// data set and makes it the active one. → the new data set.
fn sets_add(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let r = on_doc(h, doc.uid, false, |h| command(h, "dataset.capture", &json!({})))?;
let name = result_name(&r).ok_or_else(|| HostError::Error("the data set was not made".into()))?;
set_ref(h, doc.uid, &name)
}
/// `dataSets.removeAll()`: one `dataset.delete` of every data set, with no command when there is
/// none.
fn sets_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = sets_doc(h, a)?;
let names: Vec<String> = with_doc(h, doc, |_, st| st.doc.variables.datasets.iter().map(|d| d.name.clone()).collect());
if !names.is_empty() {
on_doc(h, doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": names})))?;
}
Ok(Data::Undefined)
}
// ---- Dataset ----
fn set_typename(h: &Host, a: &[Data]) -> Answer {
this_set(h, a)?;
Ok(text("Dataset"))
}
fn set_parent(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
Ok(doc_ref(h, d.doc.uid))
}
fn set_name(h: &Host, a: &[Data]) -> Answer {
Ok(text(this_set(h, a)?.name))
}
/// `name = text`: `dataset.rename`, which trims it, with no command when the name stays.
fn set_set_name(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
let to = name_arg(arg(a, 1), "name")?;
if to.trim() == d.name {
return Ok(Data::Undefined);
}
let r = on_doc(h, d.doc.uid, false, |h| command(h, "dataset.rename", &json!({"name": d.name, "newName": to})))?;
let name = result_name(&r).unwrap_or_else(|| to.trim().to_string());
h.dom.vars.sets.borrow_mut().rename(d.at, &name, None);
Ok(Data::Undefined)
}
fn set_display(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
display(h, &d)
}
/// `dataset.update()`: `dataset.update` of this data set, also when another one is active, with no
/// command when it already holds what the bound objects hold.
fn set_update(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
let same = with_doc(h, d.doc, |_, st| {
let doc = &st.doc;
let bound = doc.variables.bindings.iter().any(|(id, names)| !names.is_empty() && doc.node(*id).is_some());
bound && doc.variables.dataset(&d.name).is_some_and(|ds| ds.matches(&doc.captured_values()))
});
if !same {
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.update", &json!({"name": d.name})))?;
}
Ok(Data::Undefined)
}
/// `dataset.remove()`: `dataset.delete` of this data set.
fn set_remove(h: &Host, a: &[Data]) -> Answer {
let d = this_set(h, a)?;
on_doc(h, d.doc.uid, false, |h| command(h, "dataset.delete", &json!({"names": [d.name]})))?;
h.dom.vars.sets.borrow_mut().kill(d.at);
Ok(Data::Undefined)
}
// ---- Page items ----
/// The kind of variable a binding slot takes for the object `n`: visibility, or what drives its
/// content.
fn slot_kind(n: &Node, content: bool) -> std::result::Result<VariableKind, HostError> {
if !content {
return Ok(VariableKind::Visibility);
}
crate::cmd::content_kind(n).ok_or_else(|| HostError::Error("the object has no content a variable can drive".into()))
}
/// `visibilityVariable` (`content` false) or `contentVariable`: the first variable of the slot's
/// kind bound to the object, in the order the variables are defined, or `null`.
fn binding(h: &Host, a: &[Data], content: bool) -> Answer {
let item = item_of(h, arg(a, 0))?;
let found = with_doc(h, item.doc, |_, st| {
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
let kind = slot_kind(n, content)?;
let vars = &st.doc.variables;
let bound = vars.bindings.get(&item.id);
Ok::<_, HostError>(vars.variables.iter().find(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).cloned())
})?;
match found {
Some(v) => var_ref(h, item.doc.uid, &v),
None => Ok(Data::Null),
}
}
/// Assigning `visibilityVariable` or `contentVariable`: `variable.setBinding` with a `Variable` of
/// the object's document, or with none for `null`. No command runs when the object already has just
/// that binding of the slot's kind.
fn set_binding(h: &Host, a: &[Data], content: bool) -> Answer {
let item = item_of(h, arg(a, 0))?;
let variable = match arg(a, 1) {
Data::Null => None,
d if handle_of(d, "Variable").is_some() => {
let v = named_of(h, d, true)?;
if v.doc.uid != item.doc.uid {
return Err(HostError::Error("the variable is in another document".into()));
}
Some(v.name)
}
_ => return Err(HostError::Type("give a Variable or null".into())),
};
let same = with_doc(h, item.doc, |_, st| {
let n = st.doc.node(item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?;
let kind = slot_kind(n, content)?;
let vars = &st.doc.variables;
let bound = vars.bindings.get(&item.id);
let held: Vec<&str> =
vars.variables.iter().filter(|v| v.kind == kind && bound.is_some_and(|b| b.contains(&v.name))).map(|v| v.name.as_str()).collect();
Ok::<_, HostError>(held == variable.as_deref().into_iter().collect::<Vec<_>>())
})?;
if !same {
let slot = if content { "content" } else { "visibility" };
edit_item(h, item, "variable.setBinding", &json!({"id": item.id.0, "slot": slot, "variable": variable}))?;
}
Ok(Data::Undefined)
}
fn item_visibility(h: &Host, a: &[Data]) -> Answer {
binding(h, a, false)
}
fn item_set_visibility(h: &Host, a: &[Data]) -> Answer {
set_binding(h, a, false)
}
fn item_content(h: &Host, a: &[Data]) -> Answer {
binding(h, a, true)
}
fn item_set_content(h: &Host, a: &[Data]) -> Answer {
set_binding(h, a, true)
}
// ---- Registration ----
/// The members this module adds to `Document`.
pub(super) fn document_members(l: &Link) -> Vec<Described> {
named(vec![
("variables", get(l, doc_variables), MemberInfo { collection: true, ..typed("Variables") }),
("dataSets", get(l, doc_datasets), MemberInfo { collection: true, ..typed("Datasets") }),
("activeDataset", property(l, doc_active_dataset, doc_set_active_dataset), typed("Dataset")),
("variablesLocked", property(l, doc_locked, doc_set_locked), typed("boolean")),
("importVariables", method(l, doc_import), returns("undefined", &[("fileSpec", "File")])),
("exportVariables", method(l, doc_export), returns("undefined", &[("fileSpec", "File")])),
])
}
/// The members this module adds to `PageItem`.
pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
named(vec![("visibilityVariable", property(l, item_visibility, item_set_visibility), typed("Variable"))])
}
/// The members this module adds to the page item class `class`.
pub(super) fn item_members(l: &Link, class: &str) -> Vec<Described> {
match class {
"TextFrame" | "PlacedItem" | "RasterItem" | "GraphItem" => {
named(vec![("contentVariable", property(l, item_content, item_set_content), typed("Variable"))])
}
_ => Vec::new(),
}
}
/// The classes this module adds.
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
vec![
class(
"Variables",
None,
named(vec![
("typename", get(l, vars_typename), typed("string")),
("length", get(l, vars_length), typed("number")),
("parent", get(l, vars_parent), typed("Document")),
("index", method(l, vars_index), returns("Variable", &[("itemKey", "*")])),
("getByName", method(l, vars_by_name), returns("Variable", &[("name", "string")])),
("add", method(l, vars_add), returns("Variable", &[])),
("removeAll", method(l, vars_remove_all), returns("undefined", &[])),
]),
Some(function(l, vars_at)),
),
class(
"Variable",
None,
named(vec![
("typename", get(l, var_typename), typed("string")),
("parent", get(l, var_parent), typed("Document")),
("name", property(l, var_name, var_set_name), typed("string")),
("kind", property(l, var_kind, var_set_kind), typed("VariableKind")),
("pageItems", get(l, var_page_items), typed("Array")),
("remove", method(l, var_remove), returns("undefined", &[])),
]),
None,
),
class(
"Datasets",
None,
named(vec![
("typename", get(l, sets_typename), typed("string")),
("length", get(l, sets_length), typed("number")),
("parent", get(l, sets_parent), typed("Document")),
("index", method(l, sets_index), returns("Dataset", &[("itemKey", "*")])),
("getByName", method(l, sets_by_name), returns("Dataset", &[("name", "string")])),
("add", method(l, sets_add), returns("Dataset", &[])),
("removeAll", method(l, sets_remove_all), returns("undefined", &[])),
]),
Some(function(l, sets_at)),
),
class(
"Dataset",
None,
named(vec![
("typename", get(l, set_typename), typed("string")),
("parent", get(l, set_parent), typed("Document")),
("name", property(l, set_name, set_set_name), typed("string")),
("display", method(l, set_display), returns("undefined", &[])),
("update", method(l, set_update), returns("undefined", &[])),
("remove", method(l, set_remove), returns("undefined", &[])),
]),
None,
),
]
}
/// Adds `VariableKind`, a frozen object whose members are `"VariableKind.MEMBER"` strings.
pub(super) fn define_enums(realm: &mut Realm) -> std::result::Result<(), RunError> {
let items = KINDS.iter().map(|(_, m)| (m.to_string(), HostItem::Value(text(format!("VariableKind.{m}"))))).collect();
realm.define_host_object("VariableKind", items)
}
+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)))
}
+115 -15
View File
@@ -53,8 +53,10 @@ pub mod dialogs;
pub mod dollar;
pub mod dom;
pub mod include;
pub mod scriptui;
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
@@ -73,6 +75,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;
@@ -135,7 +138,7 @@ impl Written {
/// The version `vc.api.version` gives.
pub const API_VERSION: &str = "1.0";
/// The features `vc.api.has` knows.
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"];
pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"];
/// The most commands a run's report lists in `slowestCommands`.
pub const SLOWEST_COMMANDS: usize = 5;
@@ -187,6 +190,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,
@@ -1127,6 +1131,20 @@ impl Host {
self.pause.set(true);
Ok(())
}
/// The growth [`Host::charge_growth`] has counted, and whether the run waits for an answer about
/// it, for [`Host::put_growth_back`].
fn growth_mark(&self) -> (u64, u64, bool) {
(self.objects.get(), self.bytes_kept.get(), self.waiting.get())
}
/// Puts back the growth counted after [`Host::growth_mark`] gave `mark`: the commands that added
/// it were put back.
fn put_growth_back(&self, (objects, bytes, waiting): (u64, u64, bool)) {
self.objects.set(objects);
self.bytes_kept.set(bytes);
self.waiting.set(waiting);
}
}
/// A run in progress.
@@ -1370,16 +1388,15 @@ fn command(host: &Host, id: &str, params: &Value) -> std::result::Result<Data, H
/// [`command`], with the command's result as it gave it as well as the script's copy of it.
fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
let id = id.to_string();
let params = params.clone();
let session = host.session.clone();
let started = clock();
let before = dom::before_command(host, id);
let r = {
let mut s = session.borrow_mut();
step(&mut s, host, &id, &params)
step(&mut s, host, id, params)
};
// Only commands that exist are timed, so the table holds at most one row per command.
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
if let (Some(started), Some(spec)) = (started, crate::find_command(id)) {
let nanos = started.elapsed().as_nanos();
let mut times = host.commands.borrow_mut();
let row = times.entry(spec.id).or_insert((0, 0, 0));
@@ -1392,13 +1409,18 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
Err(EngineError::Cancelled) => return Err(HostError::Abort("canceled".into())),
Err(e) => return Err(HostError::Error(e.to_string())),
};
let mark = host.growth_mark();
let crossed = host.charge_growth(objects, added).and_then(|()| {
let data = to_data(&value, &result_limits(), 0, &mut (0, 0))
.map_err(|place| HostError::Range(format!("vc.run: the result{place} is too large for a script")))?;
host.charge_call(data_size(&data))?;
Ok(data)
});
// A command whose result does not reach the script is put back, like one that failed.
// A command whose result does not reach the script is put back, like one that failed, and so is
// the growth it was charged.
if crossed.is_err() {
host.put_growth_back(mark);
}
if let Some(save) = save {
let mut s = session.borrow_mut();
if crossed.is_ok() {
@@ -1407,6 +1429,7 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
return Err(HostError::Abort(HISTORY_LOST.to_string()));
}
}
dom::after_command(host, before);
crossed.map(|data| (data, value))
}
@@ -1652,7 +1675,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str {
/// `e`'s message, with what to do about a failure that comes from a script written for another
/// program. A message the script supplied itself ([`RunError::authored`]) is given as it is.
fn explained(e: &RunError) -> String {
const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"];
const HOST_OBJECTS: &[&str] = &["BridgeTalk"];
let message = &e.message;
let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next());
let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f));
@@ -1763,9 +1786,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.
@@ -1933,6 +1957,32 @@ impl Session {
with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false)
}
/// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run
/// asked to stop no longer waits: the next [`Session::script_pump`] ends it.
pub fn script_window(&self) -> Option<ScriptUiDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten()
}
/// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs
/// one of its handlers. A run asked to stop is in none.
pub fn script_window_showing(&self) -> Option<ScriptUiDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten()
}
/// Gives the ScriptUI dialog the running script waits at `event`; the next
/// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still
/// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]).
pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> {
let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) };
with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into()))
}
/// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects'
/// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no
/// longer waits.
@@ -1978,9 +2028,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();
@@ -1988,9 +2039,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;
@@ -2022,6 +2080,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<()> {
@@ -2172,7 +2240,7 @@ impl Session {
eval_strict: Cell::new(None),
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::default(),
dom: dom::State::new(heap_bytes),
run_docs: RefCell::new(
self.docs
.iter()
@@ -2219,6 +2287,7 @@ impl Session {
.and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) })
.and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) })
.and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { dom::install(&mut realm, &link) } else { Ok(()) })
.and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() })
.and_then(|()| {
@@ -2259,8 +2328,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);
@@ -2288,6 +2382,12 @@ impl Session {
}
job.host.calls_this_slice.set(0);
let outcome = run_slice(self, &mut job);
// A failure a dialog recorded in the slice (steps a show left unused) ends the run, even
// when the script went on.
let outcome = match (outcome, job.host.dialogs.take_failure()) {
(Ok(Ok(_)), Some(e)) => Ok(Err(e)),
(outcome, _) => outcome,
};
match outcome {
Err(panic) => {
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
+736
View File
@@ -0,0 +1,736 @@
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
//! person or `script.run`'s `answers` give back.
//!
//! A description lists the dialog first and each control after the container that holds it. It is
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than
//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`],
//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its
//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's
//! or progress bar's value to its range.
//!
//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`,
//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`,
//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of
//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by
//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out
//! with loops over the list, from the last control to the first for sizes and from the first to the
//! last for places, so a description's nesting takes no native stack.
//!
//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window",
//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change",
//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an
//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog
//! waits it takes the next step; a dialog that waits with no step left, a step for a control the
//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run.
//!
//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`],
//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`].
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
use super::Host;
/// The largest size or place, in pixels, of a dialog or a control in it.
pub const MAX_EXTENT: f32 = 8192.0;
/// A character's width and a line's height in VectorCraft's size estimates, in pixels.
const CHAR: f32 = 7.0;
const LINE: f32 = 16.0;
/// A dialog's element.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UiKind {
Dialog,
Group,
Panel,
StaticText,
EditText,
Button,
CheckBox,
RadioButton,
DropDownList,
ListBox,
Slider,
ProgressBar,
}
impl UiKind {
fn parse(s: &str) -> Option<Self> {
Some(match s {
"dialog" => Self::Dialog,
"group" => Self::Group,
"panel" => Self::Panel,
"statictext" => Self::StaticText,
"edittext" => Self::EditText,
"button" => Self::Button,
"checkbox" => Self::CheckBox,
"radiobutton" => Self::RadioButton,
"dropdownlist" => Self::DropDownList,
"listbox" => Self::ListBox,
"slider" => Self::Slider,
"progressbar" => Self::ProgressBar,
_ => return None,
})
}
/// Does it hold controls?
pub fn container(self) -> bool {
matches!(self, Self::Dialog | Self::Group | Self::Panel)
}
/// Does a click reach it?
pub fn clicks(self) -> bool {
matches!(self, Self::Button | Self::CheckBox | Self::RadioButton)
}
}
/// How a container places its controls.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Orientation {
Row,
Column,
Stack,
}
/// Where a control goes across its container: left or top, right or bottom, the middle, or the
/// whole width or height.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
Start,
End,
Center,
Fill,
}
/// A control's place and size in the dialog, from its top left corner.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct UiRect {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
/// One element of a [`ScriptUiDialog`].
#[derive(Clone, Debug, PartialEq)]
pub struct UiNode {
pub kind: UiKind,
/// A number no other element of the run has, which stays with the element while the script
/// adds and removes controls; its index in the description when the description gives none.
pub id: u64,
/// The index of its container; the dialog's own is 0.
pub parent: usize,
pub name: String,
pub text: String,
/// It and every container around it are enabled.
pub enabled: bool,
/// It and every container around it are visible.
pub visible: bool,
/// A check box's or radio button's value.
pub checked: bool,
/// A slider's or progress bar's value, within `min` to `max`.
pub value: f64,
pub min: f64,
pub max: f64,
pub items: Vec<String>,
/// How many times the script replaced a list's items (removed or added some), which tells a
/// list from one that holds the same texts again.
pub items_revision: u64,
pub selection: Option<usize>,
pub multiline: bool,
pub readonly: bool,
pub rect: UiRect,
orientation: Orientation,
align_children: (Option<Align>, Option<Align>),
alignment: (Option<Align>, Option<Align>),
spacing: f32,
margins: [f32; 4],
size: [Option<f32>; 2],
min_size: [Option<f32>; 2],
max_size: [Option<f32>; 2],
bounds: Option<UiRect>,
/// The characters an edit field or static text reserves room for in its width.
characters: Option<f32>,
}
impl UiNode {
/// How much of a progress bar is done, from 0 to 1.
pub fn fraction(&self) -> f32 {
if self.max <= self.min || self.value <= self.min {
return 0.0;
}
if self.value >= self.max {
return 1.0;
}
let span = self.max - self.min;
// A range wider than the largest number is measured at half scale.
let part =
if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) };
part.clamp(0.0, 1.0) as f32
}
}
/// A dialog a run shows, checked and laid out.
#[derive(Clone, Debug, PartialEq)]
pub struct ScriptUiDialog {
/// The dialog first, then each control after the container that holds it.
pub nodes: Vec<UiNode>,
/// The button Enter clicks and the one Escape clicks.
pub default_element: Option<usize>,
pub cancel_element: Option<usize>,
/// Which `show()` of the run this is, counted from 1; 0 before it shows.
pub shown: u64,
}
impl ScriptUiDialog {
/// The dialog's title.
pub fn title(&self) -> &str {
self.nodes.first().map_or("", |n| n.text.as_str())
}
/// The size of the dialog's content.
pub fn size(&self) -> (f32, f32) {
self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h))
}
/// The first control whose name is `control`, or else the first control without a name
/// whose text is `control`.
pub fn find(&self, control: &str) -> Option<usize> {
let by = |name: bool| {
let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control };
self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i)
};
by(true).or_else(|| by(false))
}
}
/// A value a control takes in a change.
#[derive(Clone, Debug, PartialEq)]
pub enum UiValue {
Text(String),
Number(f64),
Index(Option<usize>),
}
/// What the person did with a dialog.
#[derive(Clone, Debug, PartialEq)]
pub enum UiEvent {
/// A click on a button, check box or radio button.
Click(usize),
/// A new value for an edit field, a slider or a list.
Change(usize, UiValue),
/// The dialog's close box.
Close,
}
impl UiEvent {
/// The event as `show()` takes it.
pub(crate) fn data(&self) -> Data {
let event = |e: &str| ("event".to_string(), Data::String(e.into()));
let id = |i: usize| ("id".to_string(), Data::Number(i as f64));
match self {
Self::Click(i) => Data::Object(vec![event("click"), id(*i)]),
Self::Change(i, v) => {
let value = match v {
UiValue::Text(t) => Data::String(t.clone()),
UiValue::Number(n) => Data::Number(*n),
UiValue::Index(Some(k)) => Data::Number(*k as f64),
UiValue::Index(None) => Data::Null,
};
Data::Object(vec![event("change"), id(*i), ("value".into(), value)])
}
Self::Close => Data::Object(vec![event("close")]),
}
}
}
/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped
/// to its range.
pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result<UiEvent, String> {
let id = match &event {
UiEvent::Close => return Ok(event),
UiEvent::Click(i) | UiEvent::Change(i, _) => *i,
};
let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) };
if !n.enabled || !n.visible {
return Err(format!("the control {} is disabled or hidden", label(n)));
}
match event {
UiEvent::Click(_) if n.kind.clicks() => Ok(event),
UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))),
UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => {
if t.len() > MAX_TEXT_BYTES {
return Err("the text is longer than 16 KiB".into());
}
Ok(UiEvent::Change(id, UiValue::Text(t)))
}
UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => {
Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max))))
}
UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k {
Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))),
k => Ok(UiEvent::Change(id, UiValue::Index(k))),
},
UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))),
UiEvent::Close => Ok(UiEvent::Close),
}
}
fn label(n: &UiNode) -> String {
let shown = if n.name.is_empty() { &n.text } else { &n.name };
super::dialogs::cut_to(shown, 64).to_string()
}
/// A step of a `window` answer in `script.run`'s `answers`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct UiStep {
/// The control's name or text; none for a close.
pub control: Option<String>,
pub event: String,
pub value: Option<Value>,
}
/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value}
/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a
/// number or null.
pub(crate) fn parse_steps(v: &Value) -> Result<Vec<UiStep>, String> {
let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) };
list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect()
}
fn step(s: &Value) -> Option<UiStep> {
let o = s.as_object()?;
if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) {
return None;
}
let control = match o.get("control") {
None => None,
Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()),
Some(_) => return None,
};
let value = o.get("value").cloned();
let event = o.get("event").and_then(Value::as_str)?;
let fits = match event {
"close" => control.is_none() && value.is_none(),
"click" => control.is_some() && value.is_none(),
"change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)),
_ => false,
};
fits.then(|| UiStep { control, event: event.to_string(), value })
}
/// The event `step` is for `dialog`.
pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEvent, String> {
let Some(control) = &step.control else { return Ok(UiEvent::Close) };
let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) };
let event = match (step.event.as_str(), &step.value) {
("click", _) => UiEvent::Click(id),
(_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) {
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
None => return Err("a list's `value` must be an item index or null".into()),
},
(_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))),
(_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)),
_ => return Err("a change's `value` must be a string, a number or null".into()),
};
check_event(dialog, event)
}
/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as
/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative
/// number.
pub fn list_index(n: &serde_json::Number) -> Option<usize> {
if let Some(k) = n.as_u64() {
return Some(usize::try_from(k).unwrap_or(usize::MAX));
}
let f = n.as_f64()?;
// `as` saturates a whole number too large for usize at usize::MAX.
(f >= 0.0 && f.fract() == 0.0).then_some(f as usize)
}
fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data {
fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v)
}
fn bad(what: &str) -> HostError {
HostError::Type(format!("show: the dialog's description {what}"))
}
/// A finite number.
fn number(d: &Data) -> Option<f64> {
match d {
Data::Number(n) if n.is_finite() => Some(*n),
_ => None,
}
}
fn text(d: &Data, what: &str) -> Result<String, HostError> {
match d {
Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()),
Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))),
_ => Err(bad(&format!("has no {what}"))),
}
}
fn extent(n: f64) -> f32 {
(n as f32).clamp(-MAX_EXTENT, MAX_EXTENT)
}
fn align_name(s: &str, horizontal: Option<bool>) -> Result<(Option<Align>, Option<Align>), HostError> {
let a = match (s, horizontal) {
("left", Some(true) | None) => (Some(Align::Start), None),
("right", Some(true) | None) => (Some(Align::End), None),
("top", Some(false) | None) => (None, Some(Align::Start)),
("bottom", Some(false) | None) => (None, Some(Align::End)),
("center", _) => (Some(Align::Center), Some(Align::Center)),
("fill", _) => (Some(Align::Fill), Some(Align::Fill)),
_ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))),
};
Ok(match horizontal {
Some(true) => (a.0, None),
Some(false) => (None, a.1),
None => a,
})
}
fn alignment(d: &Data) -> Result<(Option<Align>, Option<Align>), HostError> {
match d {
Data::Null | Data::Undefined => Ok((None, None)),
Data::String(s) => align_name(s, None),
Data::Array(a) if a.len() == 2 => {
let part = |d: &Data, h: bool| match d {
Data::String(s) => align_name(s, Some(h)),
_ => Err(bad("has an alignment that is not a name")),
};
Ok((part(&a[0], true)?.0, part(&a[1], false)?.1))
}
_ => Err(bad("has an alignment that is not a name or a pair of names")),
}
}
fn numbers<const N: usize>(d: &Data) -> Result<Option<[f64; N]>, HostError> {
match d {
Data::Null | Data::Undefined => Ok(None),
Data::Array(a) if a.len() == N => {
let mut out = [0.0; N];
for (o, v) in out.iter_mut().zip(a) {
*o = number(v).ok_or_else(|| bad("has a size that is not a number"))?;
}
Ok(Some(out))
}
_ => Err(bad("has a size with the wrong count of numbers")),
}
}
/// Reads, checks and lays out a dialog's description.
pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
let Data::Object(top) = d else { return Err(bad("is not an object")) };
let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) };
if list.is_empty() {
return Err(bad("has no dialog"));
}
if list.len() > MAX_CONTROLS + 1 {
return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls")));
}
let mut nodes: Vec<UiNode> = Vec::with_capacity(list.len());
let mut depth: Vec<usize> = Vec::with_capacity(list.len());
let mut items_total = 0usize;
for (i, n) in list.iter().enumerate() {
let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) };
let kind = match field(f, "kind") {
Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?,
_ => return Err(bad("has a control without a kind")),
};
let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?;
let parent = if i == 0 {
if kind != UiKind::Dialog || parent != -1.0 {
return Err(bad("does not start with the dialog"));
}
0
} else {
let p = parent as usize;
if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog {
return Err(bad("has a control before its container"));
}
if !nodes[p].kind.container() {
return Err(bad("has a control inside a control that holds none"));
}
p
};
let level = if i == 0 { 0 } else { depth[parent] + 1 };
if level > MAX_DEPTH {
return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep")));
}
depth.push(level);
let flag = |name: &str| matches!(field(f, name), Data::Bool(true));
let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) };
let items = match field(f, "items") {
Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::<Result<Vec<_>, _>>()?,
_ => Vec::new(),
};
items_total = items_total.saturating_add(items.len());
if items_total > MAX_ITEMS {
return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all")));
}
let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len());
let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0));
if min > max {
return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into()));
}
let orientation = match field(f, "orientation") {
Data::String(s) if s == "row" => Orientation::Row,
Data::String(s) if s == "column" => Orientation::Column,
Data::String(s) if s == "stack" => Orientation::Stack,
Data::Undefined => Orientation::Column,
_ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())),
};
let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| {
let (l, t) = (extent(l), extent(t));
UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) }
});
// A width or height of 0 or less leaves that side to the layout.
let sides = |name: &str| -> Result<[Option<f32>; 2], HostError> {
Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]))
};
let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?);
let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0)));
nodes.push(UiNode {
kind,
id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64),
parent,
name: text(field(f, "name"), "a control's name")?,
text: text(field(f, "text"), "a control's text")?,
enabled: flag("enabled") && parent_enabled,
visible: flag("visible") && parent_visible,
checked: flag("value"),
value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max),
min,
max,
items,
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
selection,
multiline: flag("multiline"),
readonly: flag("readonly"),
rect: UiRect::default(),
orientation,
align_children: alignment(field(f, "alignChildren"))?,
alignment: alignment(field(f, "alignment"))?,
spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)),
margins,
size,
min_size,
max_size,
bounds,
// At most as many characters as the longest text holds.
characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)),
});
}
let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button));
let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement"));
let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 };
layout(&mut dialog);
Ok(dialog)
}
/// A control's own size, by VectorCraft's estimates.
fn own_size(n: &UiNode) -> [f32; 2] {
let chars = |s: &str| s.chars().count() as f32;
let widest = |lines: &mut dyn Iterator<Item = &str>| lines.map(chars).fold(0.0, f32::max);
let lines = |s: &str| s.lines().count().max(1) as f32;
let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max);
// `characters` reserves room for that many characters, however long the text is now.
let reserved = n.characters.unwrap_or(0.0);
match n.kind {
UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0],
UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0],
UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0],
UiKind::EditText if n.multiline => {
[(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0]
}
UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0],
UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0],
UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0],
UiKind::Slider => [160.0, 20.0],
UiKind::ProgressBar => [160.0, 12.0],
UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0],
}
}
/// Lays the dialog out: each control's size from the last to the first, then each place from the
/// first to the last.
fn layout(d: &mut ScriptUiDialog) {
let n = d.nodes.len();
let mut kids: Vec<Vec<usize>> = vec![Vec::new(); n];
for (i, node) in d.nodes.iter().enumerate().skip(1) {
kids[node.parent].push(i);
}
let mut size = vec![[0.0f32; 2]; n];
for i in (0..n).rev() {
let node = &d.nodes[i];
let mut s = if node.kind.container() {
let [l, t, r, b] = node.margins;
let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]);
for &k in &kids[i] {
// A hidden control, and everything in it, takes no room.
if !d.nodes[k].visible {
continue;
}
if let Some(bounds) = d.nodes[k].bounds {
reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)];
continue;
}
let [w, h] = size[k];
count += 1;
match node.orientation {
Orientation::Row => (main, cross) = (main + w, cross.max(h)),
Orientation::Column => (main, cross) = (main + h, cross.max(w)),
Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)),
}
}
if node.orientation != Orientation::Stack {
main += node.spacing * count.saturating_sub(1) as f32;
}
let (w, h) = match node.orientation {
Orientation::Row | Orientation::Stack => (main, cross),
Orientation::Column => (cross, main),
};
[(w + l + r).max(reach[0]), (h + t + b).max(reach[1])]
} else {
own_size(node)
};
for axis in 0..2 {
if let Some(v) = node.size[axis] {
s[axis] = v;
}
if let Some(v) = node.min_size[axis] {
s[axis] = s[axis].max(v);
}
if let Some(v) = node.max_size[axis] {
s[axis] = s[axis].min(v);
}
}
if let Some(b) = node.bounds {
s = [b.w, b.h];
}
size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)];
}
d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] };
for i in 0..n {
if !d.nodes[i].kind.container() {
continue;
}
let node = d.nodes[i].clone();
let [l, t, r, b] = node.margins;
let (x, y) = (node.rect.x + l, node.rect.y + t);
let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0));
let mut cursor = 0.0f32;
for &k in &kids[i] {
let kid = &d.nodes[k];
let rect = if !kid.visible {
UiRect { x, y, w: 0.0, h: 0.0 }
} else if let Some(bounds) = kid.bounds {
UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h }
} else {
let [w, h] = size[k];
let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center);
let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center);
let max = kid.max_size;
// A control that fills its container's room stays within its maximum.
let place = |align: Align, own: f32, room: f32, axis: usize| match align {
Align::Start => (0.0, own),
Align::End => ((room - own).max(0.0), own),
Align::Center => (((room - own) / 2.0).max(0.0), own),
Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))),
};
match node.orientation {
Orientation::Row => {
let (dy, kh) = place(v_align, h, ch, 1);
let r = UiRect { x: x + cursor, y: y + dy, w, h: kh };
cursor += w + node.spacing;
r
}
Orientation::Column => {
let (dx, kw) = place(h_align, w, cw, 0);
let r = UiRect { x: x + dx, y: y + cursor, w: kw, h };
cursor += h + node.spacing;
r
}
Orientation::Stack => {
let (dx, kw) = place(h_align, w, cw, 0);
let (dy, kh) = place(v_align, h, ch, 1);
UiRect { x: x + dx, y: y + dy, w: kw, h: kh }
}
}
};
d.nodes[k].rect = UiRect {
x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT),
y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT),
w: rect.w.clamp(0.0, MAX_EXTENT),
h: rect.h.clamp(0.0, MAX_EXTENT),
};
}
}
}
/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it
/// took.
pub(crate) struct Showing {
pub(crate) dialog: ScriptUiDialog,
pub(crate) steps: Option<std::collections::VecDeque<UiStep>>,
pub(crate) events: u64,
}
impl Showing {
/// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`,
/// `"missing"` or `"error"`.
pub(crate) fn record(&self, answer: Value) -> Value {
let mut r = Map::new();
r.insert("kind".into(), json!("window"));
r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES)));
r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1)));
r.insert("events".into(), json!(self.events));
r.insert("answer".into(), answer);
Value::Object(r)
}
}
/// The host function `name` of `Window`, for the run `link` holds.
fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>) -> HostItem {
let l = link.clone();
HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a)))
}
/// Adds `Window` to the realm, for the run `link` holds.
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
}
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
host.charge_call(args.iter().map(super::data_size).sum())?;
parse(args.first().unwrap_or(&Data::Undefined))
}
fn open(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let dialog = described(host, args)?;
host.dialogs.window_open(dialog)?;
Ok(Data::Undefined)
}
fn wait(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let dialog = described(host, args)?;
host.dialogs.window_wait(dialog)
}
fn end(host: &Host, args: &[Data]) -> Result<Data, HostError> {
let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0);
let normal = matches!(args.get(1), Some(Data::Bool(true)));
host.dialogs.window_end(result, normal)?;
Ok(Data::Undefined)
}
+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),
}