Merge pull request #9255 from dotCooCoo/feat/scripts-scriptui-resources

Scripts: ScriptUI builds windows and controls from resource strings
This commit is contained in:
.CooCoo authored and GitHub committed 2026-11-28 08:03:55 -08:00
commit c2e4966407
49 files changed
+7436 -86

No files matched your search

+1 -1
View File
@@ -32,7 +32,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Run Script",
[],
None,
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that l Line truncated
"{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s resul Line truncated
always,
run
),
+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")));
+37 -2
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;
@@ -135,7 +137,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;
@@ -1642,7 +1644,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));
@@ -1908,6 +1910,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.
@@ -2200,6 +2228,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(|()| {
@@ -2288,6 +2317,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)
}
+1
View File
@@ -184,6 +184,7 @@ mod script_folder;
mod script_include;
mod script_io;
mod script_run;
mod script_scriptui;
mod script_tags;
mod script_variables;
mod script_xmp;
+2 -2
View File
@@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() {
assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)");
let e = run(&mut s, "var = 1;").unwrap_err().to_string();
assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}");
assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`"));
assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`"));
// The application's members need no `app.`, so naming one alone is not an error.
assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true);
assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _"));
@@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() {
assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}");
}
// The app's own reference error names the `vc` object; the same text a script threw does not.
run(&mut s, "new Window('dialog');").unwrap_err();
run(&mut s, "new BridgeTalk();").unwrap_err();
assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`"));
assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in");
// An error in code `eval` compiled keeps where its message came from.
+532
View File
@@ -0,0 +1,532 @@
//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window`
//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the
//! report's `dialogs`.
use serde_json::{Value, json};
use vectorcraft_js::{Data, HostError};
use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES};
use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue};
use crate::*;
/// One open document with one rectangle.
fn one_doc() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap();
s
}
fn art(s: &Session) -> (String, usize) {
let d = &s.documents()[0];
(format!("{:?}", d.doc.layers), d.history.undo.len())
}
fn headless(s: &mut Session, source: &str, answers: Value) -> Result<Value> {
s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers}))
}
/// A run in the app of `source`, one slice in.
fn framed(s: &mut Session, source: &str) {
s.script_frames = true;
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true);
assert!(s.script_pump().is_none());
}
/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`).
fn pump(s: &mut Session) -> Option<Result<Value>> {
for _ in 0..10_000 {
if s.script_window().is_some() {
return None;
}
if let Some(r) = s.script_pump() {
return Some(r);
}
}
panic!("the run neither ended nor waited");
}
fn window(steps: Value) -> Value {
json!([{"kind": "window", "value": steps}])
}
const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});";
/// A dialog with a field, a check box, a slider, a list and OK and Cancel.
const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \
g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \
var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \
var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \
var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');";
#[test]
fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() {
let mut s = one_doc();
let source = format!(
"{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);"
);
let steps = json!([
{"control": "Bold", "event": "click"},
{"control": "size", "event": "change", "value": 99},
{"control": "pick", "event": "change", "value": 2},
{"control": "OK", "event": "click"},
]);
let r = headless(&mut s, &source, window(steps)).unwrap();
assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}");
assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}]));
let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap();
assert_eq!(cancel["log"], json!([2]));
let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap();
assert_eq!(closed["log"], json!([0]));
}
#[test]
fn a_dialog_from_a_resource_specification_takes_the_steps_of_its_window_answer() {
let mut s = one_doc();
let source = "var w = new Window(\"dialog { text: 'Settings', \
g: Group { label: StaticText { text: 'Name:' }, field: EditText { text: 'first', properties: {name: 'field'} } }, \
ok: Button { text: 'OK' } }\"); vc.log([w.show(), w.g.field.text]);";
let steps = json!([{"control": "field", "event": "change", "value": "typed"}, {"control": "OK", "event": "click"}]);
let r = headless(&mut s, source, window(steps)).unwrap();
assert_eq!(r["log"], json!([[1, "typed"]]), "{r}");
assert_eq!(r["dialogs"][0]["title"], "Settings");
assert_eq!(r["dialogs"][0]["controls"], 4);
}
#[test]
fn a_dialog_a_handler_opens_is_listed_after_the_window_that_opened_it() {
let mut s = one_doc();
let source = format!("{FORM} bold.onClick = function () {{ alert('Bolded'); }}; vc.log(w.show());");
let answers = json!([
{"kind": "window", "value": [{"control": "Bold", "event": "click"}, {"control": "OK", "event": "click"}]},
{"kind": "alert", "value": "ok"},
]);
let r = headless(&mut s, &source, answers).unwrap();
assert_eq!(r["log"], json!([1]));
assert_eq!(r["dialogCount"], 2);
assert_eq!(r["dialogs"][0], json!({"kind": "window", "title": "Settings", "controls": 8, "events": 2, "answer": 1}), "{r}");
assert_eq!((&r["dialogs"][1]["kind"], &r["dialogs"][1]["message"]), (&json!("alert"), &json!("Bolded")), "{r}");
}
#[test]
fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() {
let mut s = one_doc();
let before = art(&s);
let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}");
for (given, says) in [
(json!([]), "`answers` has no answer left for this dialog"),
(json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"),
(window(json!([])), "has no step left"),
(window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"),
(window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"),
(window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"),
(window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"),
] {
let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string();
assert!(e.contains(says), "{given}: {e}");
assert_eq!(art(&s), before, "{given}");
let report = s.script_report().unwrap();
assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}");
assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}");
}
}
#[test]
fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() {
let mut s = one_doc();
let source = "var w = new Window('dialog'); \
var named = w.add('button', undefined, 'Apply', {name: 'apply'}); named.onClick = function () { vc.log('named'); }; \
var plain = w.add('button', undefined, 'Apply'); plain.onClick = function () { vc.log('plain'); }; \
w.add('button', undefined, 'OK'); w.show();";
let steps = window(json!([{"control": "Apply", "event": "click"}, {"control": "apply", "event": "click"}, {"control": "OK", "event": "click"}]));
headless(&mut s, source, steps).unwrap();
assert_eq!(s.script_report().unwrap()["log"], json!(["plain", "named"]));
let go = "var w = new Window('dialog'); w.add('button', undefined, 'Go', {name: 'go'}); w.show();";
let e = headless(&mut s, go, window(json!([{"control": "Go", "event": "click"}]))).unwrap_err().to_string();
assert!(e.contains("the dialog has no control named Go"), "{e}");
let help = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; w.show();";
let e = headless(&mut s, help, window(json!([{"control": "", "event": "click"}]))).unwrap_err().to_string();
assert!(e.contains("the dialog has no control named"), "an empty step names no control without a name: {e}");
let blank = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; \
w.add('button', undefined, '').onClick = function () { vc.log('blank'); }; w.add('button', undefined, 'OK'); w.show();";
headless(&mut s, blank, window(json!([{"control": "", "event": "click"}, {"control": "OK", "event": "click"}]))).unwrap();
assert_eq!(s.script_report().unwrap()["log"], json!(["blank"]), "an empty step names the unnamed control whose text is empty");
}
#[test]
fn window_answers_that_do_not_parse_are_refused_before_the_run() {
let mut s = one_doc();
let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close");
for (steps, says) in [
(json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()),
(json!([1]), bad(0)),
(json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)),
(json!([{"event": "click"}]), bad(0)),
(json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)),
(json!([{"event": "change", "control": "x"}]), bad(0)),
(json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)),
(json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)),
(json!([{"event": "close", "control": "x"}]), bad(0)),
(json!([{"event": "close", "extra": 1}]), bad(0)),
] {
let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string();
assert!(e.contains(&says), "{steps}: {e}");
}
}
#[test]
fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() {
let mut s = one_doc();
let undo_before = art(&s).1;
framed(
&mut s,
&format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"),
);
let d = s.script_window().expect("show waits");
assert_eq!(d.title(), "Settings");
assert_eq!(d.nodes.len(), 9);
assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first"));
let bold = d.find("Bold").unwrap();
let size = d.find("size").unwrap();
assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click");
assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err());
assert!(s.script_window_answer(UiEvent::Click(99)).is_err());
s.script_window_answer(UiEvent::Click(bold)).unwrap();
assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on");
assert!(pump(&mut s).is_none());
let d = s.script_window().unwrap();
assert!(d.nodes[bold].checked);
assert!(!d.nodes[size].enabled, "the handler disabled the slider");
assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events");
s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap();
assert!(pump(&mut s).is_none());
s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap();
let r = pump(&mut s).unwrap().unwrap();
assert_eq!(r["log"], json!([[1, "Ann", 5]]));
assert_eq!(r["dialogs"][0]["events"], 3);
assert_eq!(art(&s).1, undo_before + 1, "a finished run is one undo step");
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script");
}
#[test]
fn an_unused_step_after_a_handler_threw_ends_the_run_and_rolls_it_back() {
let mut s = one_doc();
let before = art(&s);
let source = format!(
"{EDIT} var w = new Window('dialog'); var f = w.add('button', undefined, 'Fail'); f.onClick = function () {{ throw new Error('boom'); }}; \
try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"
);
let steps = window(json!([{"control": "Fail", "event": "click"}, {"event": "close"}]));
let e = headless(&mut s, &source, steps).unwrap_err().to_string();
assert!(e.contains("has 1 step the dialog did not use"), "{e}");
assert_eq!(art(&s), before, "the run is rolled back");
}
#[test]
fn a_list_index_written_as_a_whole_float_is_an_index_and_a_fraction_is_refused() {
let mut s = one_doc();
let source = format!("{FORM} vc.log([w.show(), pick.selection.text]);");
let r = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.0}, {"control": "OK", "event": "click"}])))
.unwrap();
assert_eq!(r["log"], json!([[1, "b"]]));
let e = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.5}]))).unwrap_err().to_string();
assert!(e.contains("a list's `value` must be an item index or null"), "{e}");
}
#[test]
fn a_progress_bar_s_fraction_stays_finite_over_the_widest_range() {
let bar = |min: f64, max: f64, value: f64| {
let n =
with(with(with(node("progressbar", 0.0), "minvalue", Data::Number(min)), "maxvalue", Data::Number(max)), "value", Data::Number(value));
scriptui::parse(&description(vec![node("dialog", -1.0), n])).unwrap().nodes[1].fraction()
};
assert_eq!(bar(-1e308, 1e308, 1e308), 1.0);
assert_eq!(bar(-1e308, 1e308, -1e308), 0.0);
assert_eq!(bar(-1e308, 1e308, 0.0), 0.5);
assert_eq!(bar(0.0, 10.0, 3.0), 0.3);
assert_eq!(bar(5.0, 5.0, 5.0), 0.0, "an empty range shows nothing done");
}
#[test]
fn stop_while_show_waits_ends_the_run_and_rolls_it_back() {
let mut s = one_doc();
let before = art(&s);
framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');"));
assert!(s.script_window().is_some());
assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true);
assert_eq!(s.script_window(), None, "a run asked to stop no longer waits");
assert!(s.script_window_answer(UiEvent::Close).is_err());
assert!(s.script_pump().unwrap().is_err());
let report = s.script_report().unwrap();
assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}");
assert_eq!(report["dialogs"][0]["answer"], "stop");
assert_eq!(art(&s), before);
framed(&mut s, &format!("{EDIT} {FORM} w.show();"));
assert!(s.script_abandon(), "quitting while a dialog waits abandons the run");
assert_eq!(art(&s), before);
}
#[test]
fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() {
let mut s = one_doc();
let before = art(&s);
let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();");
let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string();
assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}");
assert_eq!(art(&s), before);
assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error");
}
#[test]
fn a_show_in_a_callback_throws_in_the_app() {
let mut s = one_doc();
s.script_frames = true;
let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);";
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true);
let r = pump(&mut s).expect("show does not wait in a callback").unwrap();
assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}");
}
/// A handler that `notify` runs while no dialog is showing may show one in a run with nobody to
/// ask, which takes a window answer for it; in the app the same `show()` throws.
#[test]
fn a_show_in_a_handler_notify_runs_takes_a_window_answer_with_nobody_to_ask() {
let source = "var b = new Window('dialog').add('button', undefined, 'Go'); var r = ''; \
b.onClick = function () { var d = new Window('dialog'); d.add('button', undefined, 'OK'); r = d.show(); }; \
try { b.notify(); } catch (x) { r = x.message; } vc.log(r);";
let mut s = one_doc();
let r = headless(&mut s, source, window(json!([{"control": "OK", "event": "click"}]))).unwrap();
assert_eq!(r["log"], json!([1]), "{r}");
let mut s = one_doc();
s.script_frames = true;
assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true);
let r = pump(&mut s).expect("show does not wait in a handler notify runs").unwrap();
assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}");
}
fn node(kind: &str, parent: f64) -> Data {
Data::Object(vec![
("kind".into(), Data::String(kind.into())),
("parent".into(), Data::Number(parent)),
("name".into(), Data::String(String::new())),
("text".into(), Data::String("t".into())),
("enabled".into(), Data::Bool(true)),
("visible".into(), Data::Bool(true)),
])
}
fn description(nodes: Vec<Data>) -> Data {
Data::Object(vec![
("nodes".into(), Data::Array(nodes)),
("defaultElement".into(), Data::Number(-1.0)),
("cancelElement".into(), Data::Number(-1.0)),
])
}
fn with(n: Data, name: &str, value: Data) -> Data {
let Data::Object(mut fields) = n else { panic!("a node is an object") };
fields.retain(|(k, _)| k != name);
fields.push((name.into(), value));
Data::Object(fields)
}
fn refused(d: &Data) -> String {
match scriptui::parse(d) {
Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m,
other => panic!("not refused: {other:?}"),
}
}
#[test]
fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() {
let dialog = node("dialog", -1.0);
assert!(refused(&description(vec![])).contains("has no dialog"));
assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog"));
assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container"));
assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself");
assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none"));
assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container"));
let many: Vec<Data> = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect();
assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls")));
let deep: Vec<Data> = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect();
assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep")));
let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1)));
assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB"));
let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0));
assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger"));
let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)]));
assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number"));
let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into()));
assert!(refused(&description(vec![orient])).contains("row, column or stack"));
let align = with(node("button", 0.0), "alignment", Data::String("sideways".into()));
assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways"));
}
#[test]
fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() {
let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4]));
let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0));
let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)]));
let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)]));
let huge =
with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)]));
let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap();
assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height");
assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0));
assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row");
for n in &d.nodes {
for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] {
assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect);
}
}
let (w, h) = d.size();
assert!(w <= MAX_EXTENT && h <= MAX_EXTENT);
}
#[test]
fn characters_reserve_the_width_of_an_edit_field_or_a_static_text() {
let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]);
let text = |kind: &str, t: &str| with(node(kind, 0.0), "text", Data::String(t.into()));
let field = with(text("edittext", "Sample"), "characters", Data::Number(35.0));
let plain = text("edittext", "Sample");
let label = with(text("statictext", "Hi"), "characters", Data::Number(10.0));
let sized = with(with(text("edittext", "Sample"), "characters", Data::Number(35.0)), "size", pair(100.0, 20.0));
let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into()));
let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, field, plain, label, sized])).unwrap();
assert_eq!(d.nodes[1].rect.w, 35.0 * 7.0 + 12.0, "35 characters of room");
assert_eq!(d.nodes[2].rect.w, 80.0, "without characters, the text's own width and the 80 minimum");
assert_eq!(d.nodes[3].rect.w, 10.0 * 7.0 + 4.0);
assert_eq!(d.nodes[4].rect.w, 100.0, "a size set takes the place of the characters' width");
}
#[test]
fn a_hidden_control_and_what_it_holds_take_no_room() {
let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into()));
let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]);
let a = with(node("button", 0.0), "size", pair(100.0, 20.0));
let hidden = with(node("group", 0.0), "visible", Data::Bool(false));
let inside = with(node("button", 2.0), "size", pair(400.0, 300.0));
let b = with(node("button", 0.0), "size", pair(50.0, 20.0));
let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), a.clone(), hidden, inside, b.clone()])).unwrap();
let shown: ScriptUiDialog = scriptui::parse(&description(vec![dialog, a, b])).unwrap();
assert_eq!(d.size(), shown.size(), "the hidden group and the button in it leave the dialog's size as it is");
assert_eq!(d.nodes[4].rect.x, shown.nodes[2].rect.x, "the next control takes the hidden group's place");
assert!(!d.nodes[3].visible, "the button in the hidden group is hidden too");
}
#[test]
fn a_control_s_size_keeps_within_its_minimum_and_maximum() {
let dialog = node("dialog", -1.0);
let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]);
let wide = with(with(node("button", 0.0), "size", pair(300.0, -1.0)), "max", pair(120.0, -1.0));
let tall = with(with(node("button", 0.0), "size", pair(-1.0, -1.0)), "min", pair(-1.0, 60.0));
let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), wide, tall])).unwrap();
assert_eq!(d.nodes[1].rect.w, 120.0, "the maximum width holds over a larger size");
assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate");
let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap();
assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate");
let column = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "size", pair(300.0, -1.0));
let fill = |n: Data| with(n, "alignment", Data::String("fill".into()));
let capped = with(fill(node("button", 0.0)), "max", pair(90.0, -1.0));
let d: ScriptUiDialog = scriptui::parse(&description(vec![column, capped, fill(node("button", 0.0))])).unwrap();
assert!(d.nodes[2].rect.w > 90.0, "a control that fills its column takes the column's width");
assert_eq!(d.nodes[1].rect.w, 90.0, "a control that fills its column stays within its maximum width");
}
#[test]
fn window_s_alert_confirm_and_prompt_open_the_script_dialogs() {
let mut s = one_doc();
let answers = json!([{"kind": "alert", "value": "ok"}, {"kind": "confirm", "value": false}, {"kind": "prompt", "value": "typed"}]);
let r = headless(&mut s, "vc.log([typeof Window.alert('Hi'), Window.confirm('Go?'), Window.prompt('Name', 'x')]);", answers).unwrap();
assert_eq!(r["log"], json!([["undefined", false, "typed"]]), "{r}");
assert_eq!(r["dialogCount"], 3);
}
/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and
/// not-a-number ones included) and texts of any length.
fn any_description() -> impl proptest::strategy::Strategy<Value = Data> {
use proptest::prelude::*;
let kind = prop_oneof![
Just("dialog"),
Just("group"),
Just("panel"),
Just("statictext"),
Just("edittext"),
Just("button"),
Just("checkbox"),
Just("radiobutton"),
Just("dropdownlist"),
Just("listbox"),
Just("slider"),
Just("progressbar"),
Just("wobble"),
];
let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::<f64>(), 6 => -50.0..400.0f64];
let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))];
let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4));
let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2));
// The container is a share of the controls before this one, or with a share past 1, one after it.
let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number);
proptest::collection::vec(fields, 0..40).prop_map(|nodes| {
let mut containers = vec![0usize];
let mut out = Vec::new();
for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() {
let kind = if i == 0 { "dialog" } else { kind };
let parent = match i {
0 => -1.0,
_ if share >= 1.0 => (i + 1) as f64,
_ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64,
};
if matches!(kind, "group" | "panel") {
containers.push(i);
}
let numbers = |v: Option<Vec<f64>>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect()));
let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds));
n = with(n, "size", numbers(size));
n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect()));
n = with(n, "selection", Data::Number(value));
out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value)));
}
description(out)
})
}
proptest::proptest! {
#![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))]
/// Any description is refused with an error or laid out with every place and size finite and
/// within the limit.
#[test]
fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) {
if let Ok(dialog) = scriptui::parse(&d) {
for n in &dialog.nodes {
for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] {
proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect);
}
proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len()));
}
}
}
}
#[test]
fn an_event_is_checked_against_the_dialog() {
let d = scriptui::parse(&description(vec![
node("dialog", -1.0),
node("button", 0.0),
with(node("edittext", 0.0), "readonly", Data::Bool(true)),
with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)),
with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])),
with(node("button", 0.0), "visible", Data::Bool(false)),
]))
.unwrap();
assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1)));
assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control");
assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text");
assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0))));
assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err());
assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err());
assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None))));
assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events");
assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close));
}
@@ -42,11 +42,13 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
];
/// The names the host adds that stay inside the document and the run, by the object that has them.
/// Reading a file or a folder, a file dialog and a message to the person do not change anything
/// outside it. The document model (`app`, its classes and the enumerations) acts on the open
/// documents; `Document.saveAs` and `close` throw "not available yet".
/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not
/// change anything outside it. The document model (`app`, its classes and the enumerations) acts on
/// the open documents; `Document.saveAs` and `close` throw "not available yet".
const INSIDE: &[(&str, &str)] = &[
("", "$ File Folder UnitValue alert confirm localize prompt toSource"),
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
("Window.", "alert confirm length prompt prototype"),
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"),
("Object.prototype.", "reflect toSource"),
("UnitValue.", "baseUnit baseUnit= length prototype"),
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
+1
View File
@@ -659,6 +659,7 @@ fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Val
args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types],
keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()],
resume: picked,
failed: None,
})
}
+64 -20
View File
@@ -243,18 +243,25 @@ pub(crate) type CodeObserver = Rc<dyn Fn(&[u16])>;
pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult<Pause>;
/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the
/// answer, and gives the result of its call.
/// answer, and gives the result of its call. One that puts another [`Pause`] in
/// [`Interp::again`] makes that host call next, and the call's result is what that pause's
/// resume function gives.
pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult<Value>;
/// What a [`Pause`] does with its kept values when its host call fails.
pub(crate) type FailFn = fn(&mut Interp, &[Value]);
/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to
/// `resume` with `keep`, at once when the host answers at once. When the host waits
/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on
/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it.
/// When the host call fails, `failed` is given `keep` before the error is thrown at the call.
pub(crate) struct Pause {
pub(crate) host: Value,
pub(crate) args: Vec<Value>,
pub(crate) keep: Vec<Value>,
pub(crate) resume: ResumeFn,
pub(crate) failed: Option<FailFn>,
}
/// A [`Pause`] whose host call waits for its answer.
@@ -369,6 +376,10 @@ pub(crate) struct Interp {
/// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before
/// the next instruction runs.
pub(crate) resuming: Option<Resumption>,
/// The next host call a resume function asks for ([`ResumeFn`]).
pub(crate) again: Option<Pause>,
/// ScriptUI's `Window` and its controls, when the host added them.
pub(crate) script_ui: Option<crate::scriptui::Classes>,
/// The message of the uncatchable error a host function ended the run with.
pub(crate) host_abort: Option<String>,
/// How much a value passed to or from a host function may carry.
@@ -671,6 +682,8 @@ impl Interp {
waiting_hosted: false,
constructing: false,
resuming: None,
again: None,
script_ui: None,
host_abort: None,
data_limits: crate::DataLimits::default(),
source_tag: crate::realm::UNKNOWN_SOURCE,
@@ -919,6 +932,7 @@ impl Interp {
roots.values.extend(self.stack.iter());
roots.values.extend(self.temp_roots.iter());
roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter()));
roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host))));
roots.values.push(&self.last_thrown);
roots.values.push(&self.last_error);
roots.values.push(&self.passing);
@@ -937,6 +951,7 @@ impl Interp {
roots.objects.push(self.global);
roots.objects.extend(self.intrinsics.all());
roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects));
roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects));
roots.objects.extend(self.xmp.iter().flat_map(crate::xmp_classes::Classes::objects));
roots.objects.extend(self.host_classes.iter().flat_map(crate::host_classes::Entry::objects));
roots.values.extend(self.symbols.root_values());
@@ -3378,35 +3393,64 @@ impl Interp {
/// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host
/// function is called as the script's own code calls it, so it may wait; then the resume
/// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands
/// in for that answer is the call's result for now.
/// in for that answer is the call's result for now. A resume function that asks [`Self::again`]
/// makes that call next, in this loop, so a built-in may ask any number of times.
fn ask(&mut self, p: Pause) -> JsResult<Value> {
let Pause { host, args, keep, resume } = p;
let mark = self.temp_roots.len();
self.temp_roots.push(host.clone());
self.temp_roots.extend(args.iter().cloned());
self.temp_roots.extend(keep.iter().cloned());
let was_waiting = self.waiting;
let answer = match self.func_of(&host) {
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
_ => self.call(&host, &Value::Undefined, &args),
};
self.temp_roots.truncate(mark);
let answer = answer?;
let r = Resumption { resume, keep };
if self.waiting && !was_waiting {
self.resuming = Some(r);
return Ok(answer);
let mut p = p;
loop {
let Pause { host, args, keep, resume, failed } = p;
let mark = self.temp_roots.len();
self.temp_roots.push(host.clone());
self.temp_roots.extend(args.iter().cloned());
self.temp_roots.extend(keep.iter().cloned());
let was_waiting = self.waiting;
let answer = match self.func_of(&host) {
Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read),
_ => self.call(&host, &Value::Undefined, &args),
};
if let Err(e) = &answer
&& let Some(failed) = failed
{
// The thrown value stays kept from collection while `failed` runs.
if let Abrupt::Throw(v) = e {
self.temp_roots.push(v.clone());
}
failed(self, &keep);
}
self.temp_roots.truncate(mark);
let answer = answer?;
let r = Resumption { resume, keep };
if self.waiting && !was_waiting {
self.resuming = Some(r);
return Ok(answer);
}
let v = self.resume_once(r, answer)?;
match self.again.take() {
Some(next) => p = next,
None => return Ok(v),
}
}
self.resume(r, answer)
}
/// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function.
/// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and
/// makes the host call it asks for next, if any.
fn resume(&mut self, r: Resumption, answer: Value) -> JsResult<Value> {
let v = self.resume_once(r, answer)?;
match self.again.take() {
Some(next) => self.ask(next),
None => Ok(v),
}
}
fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult<Value> {
let mark = self.temp_roots.len();
self.temp_roots.push(answer.clone());
self.temp_roots.extend(r.keep.iter().cloned());
let v = (r.resume)(self, &r.keep, answer);
self.temp_roots.truncate(mark);
if v.is_err() {
self.again = None;
}
v
}
+4
View File
@@ -134,6 +134,8 @@ mod reflect;
mod regexp;
mod regexp_builtins;
mod regexp_vm;
pub mod scriptui;
mod scriptui_resource;
mod string_builtins;
mod symbol;
mod token;
@@ -316,6 +318,8 @@ mod promise_tests;
#[cfg(test)]
mod reflect_tests;
#[cfg(test)]
mod scriptui_tests;
#[cfg(test)]
mod symbol_tests;
#[cfg(test)]
mod tests;
+17
View File
@@ -305,6 +305,8 @@ impl Realm {
interp.waiting_hosted = false;
interp.constructing = false;
interp.resuming = None;
interp.again = None;
crate::scriptui::end_run(interp);
interp.error_tag = UNKNOWN_SOURCE;
interp.thrown_mark = None;
interp.finally_marks.clear();
@@ -363,6 +365,8 @@ impl Realm {
interp.waiting_hosted = false;
interp.constructing = false;
interp.resuming = None;
interp.again = None;
crate::scriptui::end_run(interp);
interp.passing = Value::Undefined;
interp.end_jobs(result.is_ok());
if let Some(es2015) = interp.next_es2015.take() {
@@ -601,6 +605,19 @@ impl Realm {
}
}
/// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host
/// functions in `items` show: `open` and `wait`, each given the dialog's description, and
/// `end`, given the result of `show()` and whether `show()` ended normally. A run that ends
/// while `show()` waits for `wait`'s answer, because it is stopped or the host does not resume
/// it, ends without a call to `end`: the host releases what it holds for the dialog when the run
/// ends, and does not wait for `end`.
pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> {
match crate::scriptui::install(&mut self.interp, items) {
Ok(()) => Ok(()),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
/// Adds the global constructors `File` and `Folder`, whose file system work the host functions
/// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`,
/// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`,
File diff suppressed because it is too large. Load diff
+371
View File
@@ -0,0 +1,371 @@
//! The reader of ScriptUI resource specifications, as the help page
//! <https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/> describes
//! them: a type, then braces holding property definitions, where a property whose value is a
//! control class followed by braces defines a control the container holds.
//!
//! `[name:] Type { name: value, ... }` is read into a [`Spec`]. A value is `null`, `true`, `false`,
//! a string in single or double quotes, a number, an inline array `[value, ...]`, an inline object
//! `{name: value, ...}`, or, directly in a window's or control's braces, a control `Class { ... }`.
//! A name is an identifier or a quoted string. The commas between properties may be left out, and
//! a comma may end a list. A string longer than [`MAX_BYTES`] or values nested more than
//! [`MAX_NESTING`] deep are refused; these are VectorCraft's own limits.
/// The most bytes (UTF-8) of a resource specification.
pub const MAX_BYTES: usize = 1 << 20;
/// How deeply braces and brackets nest in a resource specification.
pub const MAX_NESTING: usize = 64;
/// A value in a resource specification.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Res {
Null,
Bool(bool),
Number(f64),
String(String),
Array(Vec<Res>),
Object(Vec<(String, Res)>),
Control(Spec),
}
/// A window or control: its class as written and its properties in order.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Spec {
pub(crate) class: String,
pub(crate) props: Vec<(String, Res)>,
}
/// Why a resource specification could not be read.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Fault {
/// The text is not a resource specification; the message says where.
Syntax(String),
/// The text passes [`MAX_BYTES`] or [`MAX_NESTING`].
Limit(String),
}
/// Reads `text`, which is `[name:] Type { ... }` with nothing after it but white space.
pub(crate) fn parse(text: &str) -> Result<Spec, Fault> {
if text.len() > MAX_BYTES {
return Err(Fault::Limit(format!("a resource specification is longer than {} MiB", MAX_BYTES >> 20)));
}
let mut r = Reader { chars: text.chars().collect(), at: 0 };
r.space();
let quoted = matches!(r.peek(), Some('\'' | '"'));
let first = r.name()?;
r.space();
let class = if r.eat(':') {
r.space();
r.ident()?
} else if quoted {
return Err(r.expected(": after the name"));
} else {
first
};
r.space();
if !r.eat('{') {
return Err(r.expected("{ after the type"));
}
let props = r.props(true, 1)?;
r.space();
if r.at < r.chars.len() {
return Err(r.expected("the end of the resource specification"));
}
Ok(Spec { class, props })
}
struct Reader {
chars: Vec<char>,
at: usize,
}
impl Reader {
fn peek(&self) -> Option<char> {
self.chars.get(self.at).copied()
}
fn eat(&mut self, c: char) -> bool {
if self.peek() == Some(c) {
self.at += 1;
true
} else {
false
}
}
fn space(&mut self) {
while self.peek().is_some_and(char::is_whitespace) {
self.at += 1;
}
}
fn expected(&self, what: &str) -> Fault {
match self.peek() {
Some(c) => Fault::Syntax(format!("expected {what} at character {}, found {c:?}", self.at + 1)),
None => Fault::Syntax(format!("expected {what} at character {}, the end of the resource specification", self.at + 1)),
}
}
fn ident(&mut self) -> Result<String, Fault> {
let start = self.at;
while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') {
self.at += 1;
}
if self.at == start || self.chars[start].is_ascii_digit() {
self.at = start;
return Err(self.expected("a name"));
}
Ok(self.chars[start..self.at].iter().collect())
}
/// A property name: an identifier or a quoted string.
fn name(&mut self) -> Result<String, Fault> {
match self.peek() {
Some('\'' | '"') => self.string(),
_ => self.ident(),
}
}
/// The properties after an opening brace, up to and including its closing brace. Controls are
/// allowed among them when `controls`.
fn props(&mut self, controls: bool, depth: usize) -> Result<Vec<(String, Res)>, Fault> {
if depth > MAX_NESTING {
return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep")));
}
let mut props = Vec::new();
loop {
self.space();
if self.eat('}') {
return Ok(props);
}
let name = self.name()?;
self.space();
if !self.eat(':') {
return Err(self.expected(": after a property name"));
}
self.space();
let value = self.value(controls, depth)?;
props.push((name, value));
self.space();
self.eat(',');
}
}
fn value(&mut self, controls: bool, depth: usize) -> Result<Res, Fault> {
match self.peek() {
Some('\'' | '"') => Ok(Res::String(self.string()?)),
Some('[') => {
self.at += 1;
if depth + 1 > MAX_NESTING {
return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep")));
}
let mut items = Vec::new();
loop {
self.space();
if self.eat(']') {
return Ok(Res::Array(items));
}
items.push(self.value(false, depth + 1)?);
self.space();
if !self.eat(',') && self.peek() != Some(']') {
return Err(self.expected(", or ] in an array"));
}
}
}
Some('{') => {
self.at += 1;
Ok(Res::Object(self.props(false, depth + 1)?))
}
Some(c) if c.is_ascii_digit() || matches!(c, '-' | '+' | '.') => self.number(),
Some(_) => {
let start = self.at;
let word = self.ident()?;
match word.as_str() {
"null" => return Ok(Res::Null),
"true" => return Ok(Res::Bool(true)),
"false" => return Ok(Res::Bool(false)),
_ => {}
}
self.space();
if self.peek() != Some('{') {
self.at = start;
return Err(self.expected("a value"));
}
if !controls {
self.at = start;
return Err(self.expected("a value (a control can only be a property of a window or a container)"));
}
self.at += 1;
Ok(Res::Control(Spec { class: word, props: self.props(true, depth + 1)? }))
}
None => Err(self.expected("a value")),
}
}
fn number(&mut self) -> Result<Res, Fault> {
let start = self.at;
while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.')) {
self.at += 1;
}
let text: String = self.chars[start..self.at].iter().collect();
let plain = text.strip_prefix(['-', '+']).unwrap_or(&text);
// Rust also reads words such as inf and nan, which are not numbers here.
let n = if plain.starts_with(|c: char| c.is_ascii_digit() || c == '.') { text.parse::<f64>().ok() } else { None };
match n {
Some(n) if n.is_finite() => Ok(Res::Number(n)),
_ => {
self.at = start;
Err(self.expected("a number"))
}
}
}
/// The number that the `digits` hex digits at `at` write; `None` when they are not all there.
fn hex(&self, at: usize, digits: usize) -> Option<u32> {
let hex: String = self.chars.iter().skip(at).take(digits).collect();
// `from_str_radix` also takes a sign, which an escape does not have.
let valid = hex.len() == digits && hex.chars().all(|c| c.is_ascii_hexdigit());
u32::from_str_radix(&hex, 16).ok().filter(|_| valid)
}
fn string(&mut self) -> Result<String, Fault> {
let Some(quote) = self.peek() else { return Err(self.expected("a string")) };
let start = self.at;
self.at += 1;
let mut s = String::new();
loop {
let Some(c) = self.peek() else {
self.at = start;
return Err(Fault::Syntax(format!("the string at character {} has no closing quote", start + 1)));
};
self.at += 1;
if c == quote {
return Ok(s);
}
if c != '\\' {
s.push(c);
continue;
}
let Some(e) = self.peek() else { continue };
self.at += 1;
match e {
'n' => s.push('\n'),
't' => s.push('\t'),
'r' => s.push('\r'),
'b' => s.push('\u{8}'),
'f' => s.push('\u{c}'),
'v' => s.push('\u{b}'),
'0' => s.push('\0'),
'\n' => {}
'u' | 'x' => {
let escape = self.at - 1;
let digits = if e == 'u' { 4 } else { 2 };
let code = self.hex(self.at, digits);
// A high surrogate and the `\u` escape of a low one after it are one character.
let low = code.filter(|c| (0xD800..0xDC00).contains(c)).and_then(|_| {
let next = self.chars.get(self.at + digits..self.at + digits + 2)?;
(next == ['\\', 'u']).then(|| self.hex(self.at + digits + 2, 4)).flatten().filter(|c| (0xDC00..0xE000).contains(c))
});
let (code, len) = match (code, low) {
(Some(high), Some(low)) => (Some(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)), digits + 6),
(code, _) => (code, digits),
};
match code.and_then(char::from_u32) {
Some(c) => {
s.push(c);
self.at += len;
}
None => return Err(Fault::Syntax(format!("the escape at character {escape} is not valid"))),
}
}
e => s.push(e),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn spec(class: &str, props: Vec<(&str, Res)>) -> Spec {
Spec { class: class.into(), props: props.into_iter().map(|(k, v)| (k.into(), v)).collect() }
}
#[test]
fn a_resource_specification_reads_its_controls_and_values() {
let got = parse(
"p: Panel { text: 'Messages', alignChildren: ['right', \"top\"], \
g: Group { st: StaticText { text: 'a\\'b' } } \
e: EditText { properties: {multiline: true, name: null}, characters: -3.5e1, }, }",
);
let want = spec(
"Panel",
vec![
("text", Res::String("Messages".into())),
("alignChildren", Res::Array(vec![Res::String("right".into()), Res::String("top".into())])),
("g", Res::Control(spec("Group", vec![("st", Res::Control(spec("StaticText", vec![("text", Res::String("a'b".into()))])))]))),
(
"e",
Res::Control(spec(
"EditText",
vec![
("properties", Res::Object(vec![("multiline".into(), Res::Bool(true)), ("name".into(), Res::Null)])),
("characters", Res::Number(-35.0)),
],
)),
),
],
);
assert_eq!(got, Ok(want));
assert_eq!(parse(" dialog{} "), Ok(spec("dialog", vec![])));
}
#[test]
fn a_malformed_resource_specification_is_a_syntax_fault() {
for text in [
"dialog",
"dialog {",
"dialog { b: }",
"dialog { b: Button { } } x",
"dialog { b Button {} }",
"dialog { t: 'open }",
"dialog { n: inf }",
"dialog { n: 1.2.3 }",
"dialog { a: [1 2] }",
"dialog { o: { b: Button {} } }",
"dialog { a: [Button {}] }",
"dialog { v: orange }",
"dialog { t: '\\u12' }",
"dialog { t: '\\x+A' }",
"dialog { t: '\\u+00A' }",
"{ }",
] {
assert!(matches!(parse(text), Err(Fault::Syntax(_))), "{text}: {:?}", parse(text));
}
assert_eq!(parse("dialog { t: '\\x0A\\u0041' }"), Ok(spec("dialog", vec![("t", Res::String("\nA".into()))])));
}
#[test]
fn a_surrogate_pair_of_escapes_is_one_character_and_a_lone_surrogate_is_a_syntax_fault() {
assert_eq!(parse("dialog { t: '\\uD83D\\uDE00!' }"), Ok(spec("dialog", vec![("t", Res::String("\u{1F600}!".into()))])));
for text in ["dialog { t: '\\uD83D' }", "dialog { t: '\\uD83Dx' }", "dialog { t: '\\uD83D\\u0041' }", "dialog { t: '\\uDE00' }"] {
assert_eq!(parse(text), Err(Fault::Syntax("the escape at character 14 is not valid".into())), "{text}");
}
}
#[test]
fn a_resource_specification_that_ends_early_says_at_which_character() {
assert_eq!(parse("dialog {"), Err(Fault::Syntax("expected a name at character 9, the end of the resource specification".into())));
assert_eq!(parse("dialog"), Err(Fault::Syntax("expected { after the type at character 7, the end of the resource specification".into())));
}
#[test]
fn a_resource_specification_past_the_limits_is_refused() {
let deep = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING), "]".repeat(MAX_NESTING));
assert!(matches!(parse(&deep), Err(Fault::Limit(_))), "{:?}", parse(&deep));
let fits = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING - 1), "]".repeat(MAX_NESTING - 1));
assert!(parse(&fits).is_ok());
let long = format!("dialog {{ t: '{}' }}", "x".repeat(MAX_BYTES));
assert!(matches!(parse(&long), Err(Fault::Limit(_))));
}
}
File diff suppressed because it is too large. Load diff
+4
View File
@@ -1448,6 +1448,10 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
{
return wrap(r);
}
// A script's ScriptUI dialog gives the script an event and stays open.
if let Some(r) = crate::dialogs::script_window::dialog_method(app, method, &params) {
return wrap(r);
}
// `ui.dialog.set {action}` answers the dialog after setting its fields: the app's own key, which the
// framework's method does not take.
let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None };
+1
View File
@@ -139,6 +139,7 @@ pub(crate) mod saved_names;
pub(crate) mod screen_formats;
pub mod script_check;
pub mod script_run;
pub mod script_window;
pub mod shape_builder_options;
pub(crate) mod shapes;
pub mod shortcut_import;
+39 -9
View File
@@ -1,6 +1,7 @@
//! File › Scripts › Other Script…: choosing a JavaScript file and the warning before it runs
//! (`script.run` runs it), the question a run that keeps adding art asks, the question quitting
//! asks while a script runs, and the dialogs a script opens with `alert`, `confirm` and `prompt`.
//! A script's ScriptUI dialog is in [`script_window`]; these questions and dialogs open over it.
//!
//! `ui.runScript {path? | source?, name?}` shows the warning for that script; without either it
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
@@ -50,6 +51,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text};
use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker};
use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog};
use super::script_window::{self, ScriptWindow};
use crate::VectorcraftApp;
use crate::file_asks::{self, Owner};
@@ -435,6 +437,25 @@ pub(crate) fn busy(app: &VectorcraftApp) -> bool {
app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false)
}
/// Whether the run's question can open now: over nothing, or over the script's ScriptUI dialog
/// while nothing, neither a dialog nor a popup, is open over it.
pub(crate) fn can_ask(app: &VectorcraftApp) -> bool {
!busy(app) || script_window::uncovered(app)
}
/// Opens `dialog` over the script's ScriptUI dialog when that is the top dialog, so the ScriptUI
/// dialog keeps its queued events and typed text under it; otherwise over nothing.
fn open_over_window<D: StackDialog>(app: &VectorcraftApp, dialog: D) {
with_host(app, |host, _| match host.get::<ScriptWindow>().map(StackDialog::id).filter(|id| host.stack().is_top(*id)) {
Some(parent) => {
host.open_child(dialog, parent);
}
None => {
host.open(dialog);
}
});
}
/// Closes the open `D` the run no longer waits at, and drops its result: only answers the person
/// or automation gave reach [`pump`]. A quit question asked over it stays, now over nothing, so
/// its Cancel does not show the dialog again.
@@ -519,34 +540,41 @@ fn close_question() -> CloseQuestion {
)
}
/// Asks whether to continue a run that has added a great deal; Stop is its Cancel button.
/// Asks whether to continue a run that has added a great deal; Stop is its Cancel button. Over the
/// script's ScriptUI dialog, Continue shows that dialog again with its queued events and typed
/// text.
pub(crate) fn open_growth(app: &VectorcraftApp) {
with_host(app, |host, _| host.open(growth_question()));
open_over_window(app, growth_question());
}
/// Shows the dialog the running script waits at.
pub(crate) fn open_notice(app: &VectorcraftApp, d: &ScriptDialog) {
with_host(app, |host, _| host.open(ScriptNotice::new(d)));
open_over_window(app, ScriptNotice::new(d));
}
/// Shows the file dialog the running script waits at.
pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) {
with_host(app, |host, _| host.open(ScriptFiles::new(p)));
open_over_window(app, ScriptFiles::new(p));
}
/// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which
/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet.
/// Cancel shows again as it was, with the events a ScriptUI dialog has not given the script yet and
/// the text typed in its fields. Any other open dialog stays, and quitting asks nothing yet.
pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
with_host(app, |host, _| {
let own = host.get::<ScriptNotice>().map(StackDialog::id).or_else(|| host.get::<ScriptFiles>().map(StackDialog::id));
match own {
Some(parent) if host.stack().is_top(parent) => {
let own = [
host.get::<ScriptNotice>().map(StackDialog::id),
host.get::<ScriptFiles>().map(StackDialog::id),
host.get::<ScriptWindow>().map(StackDialog::id),
];
match own.into_iter().flatten().find(|id| host.stack().is_top(*id)) {
Some(parent) => {
host.open_child(close_question(), parent);
}
None if host.is_empty() => {
host.open(close_question());
}
_ => {}
None => {}
}
});
}
@@ -606,6 +634,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
if with_host(app, |host, _| host.get_mut::<ScriptFiles>().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) {
choose(app);
}
script_window::pump(app);
}
/// Takes the answer to the quit question given between two queued runs, before the next run
@@ -636,6 +665,7 @@ fn answer_close(app: &mut VectorcraftApp, close: Option<DialogResult<<CloseQuest
}
forget::<ScriptNotice>(app);
forget::<ScriptFiles>(app);
forget::<ScriptWindow>(app);
app.sync_views();
}
}
+859
View File
@@ -0,0 +1,859 @@
//! A dialog a script builds with ScriptUI's `new Window("dialog")` and shows with `show()`
//! (kind `scriptWindow`). It draws the controls the running script's dialog holds, at the places
//! the engine laid them out, and gives the script each click and change.
//!
//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`,
//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its
//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or
//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open, giving the
//! text still typed in its fields first when the event is a click or a close; an event the dialog
//! cannot take is an error. An edit field gives its text when it loses the keyboard focus, when
//! Enter is pressed in a one-line field, or before a click on another control or a close. Events
//! given in one frame reach the script one at a time, in order. Enter outside a field clicks the
//! default button, and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog
//! when it has none. Stop ends the run and puts back everything it did.
//!
//! The dialog lives on the window's dialog host. Its body has no app, so it keeps what the person
//! did and [`pump`] gives it to the run, and [`sync`] pushes the dialog the run waits at into it.
use std::collections::{BTreeMap, VecDeque};
use craft::automation::protocol::Params;
use craft::behavior::{Selection, SelectionChange, keyed};
use craft::theme::Variant;
use craft::ui::buttons::Button;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, RowHeight, Scroll, Show as _, ShowCollection as _, ShowContainer as _, clicked};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft::ui::display::{Progress, Text};
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow};
use craft::ui::pickers::Select;
use craft::ui::runtime::env::Env;
use craft::ui::runtime::focus::Initial;
use craft::ui::runtime::keys::take_submit;
use craft::ui::runtime::overlay;
use craft::ui::sections::{DialogRole, FooterButton, GroupBox};
use craft::ui::style::StyleCx;
use craft::ui::text::TextField;
use craft::ui::value_drag::Slider;
use egui::Ui;
use serde_json::{Value, json};
use vectorcraft_engine::script::dialogs::{cut_to, shown_text};
use vectorcraft_engine::script::scriptui::{MAX_TEXT_BYTES, UiNode, check_event, list_index};
use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue};
use super::script_run::with_host;
use crate::VectorcraftApp;
/// The dialog kind of a script's ScriptUI dialog.
pub const KIND: &str = "scriptWindow";
/// The most of the dialog's content shown at once; a larger dialog scrolls.
const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0);
/// The room the engine's layout adds around a list box's rows.
const LIST_PAD: f32 = 6.0;
/// How many rows `row` tall a list box `height` tall shows; it scrolls the rest, inside the
/// dialog's own scroll.
fn list_rows(height: f32, row: f32) -> u16 {
let rows = ((height - LIST_PAD) / row).floor();
if rows.is_finite() { rows.clamp(1.0, f32::from(u16::MAX)) as u16 } else { 1 }
}
/// An event the script has not had yet, with its control by its id ([`UiNode::id`]), which stays
/// with the control while a handler adds or removes controls before it.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Queued {
Click(u64),
/// A change, and for a list's, the list's items as the person saw them and how many times the
/// script had replaced them.
Change(u64, UiValue, Option<(Vec<String>, u64)>),
Close,
/// Escape or `ui.dialog.cancel` while a handler ran: the click on the cancel button of the
/// dialog the run waits at next, or its close box.
Cancel,
}
/// The ScriptUI dialog on the window's dialog host; at most one is open.
pub(crate) struct ScriptWindow {
/// The dialog the run waits at, or while one of its handlers runs, the one it last waited at.
window: ScriptUiDialog,
/// The run waits at the dialog; while a handler runs, every control is disabled.
waiting: bool,
/// The text typed in each edit field that the script has not had yet, by the field's id.
drafts: BTreeMap<u64, String>,
/// The events the person gave that the script has not had yet; the script takes one each time
/// it waits.
queue: VecDeque<Queued>,
/// The event `ui.dialog.set` set: `event`, `control` and `value`.
event: Option<String>,
control: Option<Value>,
value: Option<Value>,
open: bool,
/// Stop was clicked.
stop: bool,
/// Escape or the close box asked for the dialog's cancel.
cancel: bool,
/// An error for the status bar.
status: Option<String>,
/// The overlay layer the dialog's body was last drawn in.
layer: Option<egui::Id>,
}
impl ScriptWindow {
fn new(window: ScriptUiDialog) -> Self {
ScriptWindow {
window,
waiting: true,
drafts: BTreeMap::new(),
queue: VecDeque::new(),
event: None,
control: None,
value: None,
open: true,
stop: false,
cancel: false,
status: None,
layer: None,
}
}
/// Which `show()` of the run the dialog is for.
pub(crate) fn shown(&self) -> u64 {
self.window.shown
}
/// The text typed in edit field `i` that the script has not had yet.
#[cfg(test)]
pub(crate) fn typed(&self, i: usize) -> Option<&str> {
self.window.nodes.get(i).and_then(|n| self.drafts.get(&n.id)).map(String::as_str)
}
/// Types `text` in edit field `i`, as the person does before the field loses the focus.
#[cfg(test)]
pub(crate) fn type_text(&mut self, i: usize, text: &str) {
if let Some(n) = self.window.nodes.get(i) {
self.drafts.insert(n.id, text.to_string());
}
}
/// The events the script has not had yet.
#[cfg(test)]
pub(crate) fn queued(&self) -> &VecDeque<Queued> {
&self.queue
}
/// Adds `event` after the events the script has not had yet.
pub(crate) fn queue(&mut self, event: &UiEvent) {
if let Some(q) = queued(&self.window, event) {
self.queue.push_back(q);
}
}
/// The dialog the run waits at now (`None` while one of its handlers runs). A typed text whose
/// field the dialog no longer has is dropped.
fn sync(&mut self, waiting: Option<ScriptUiDialog>) {
self.waiting = waiting.is_some();
if let Some(w) = waiting {
self.window = w;
let fields: Vec<u64> = self.window.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect();
self.drafts.retain(|id, _| fields.contains(id));
}
}
/// Before a click or a close, gives the script the text typed in each edit field that has not
/// left the field yet, so the handler of a button that closes the dialog, or `onClose`, reads
/// it. A disabled or hidden field keeps its text for later. Each text is checked as the script
/// in `w` would check it first; when one is refused, every field keeps its text, `events` stays
/// as it was and the error is returned.
pub(crate) fn commit_drafts(&mut self, w: &ScriptUiDialog, events: &mut Vec<UiEvent>) -> Result<(), String> {
let mut given = Vec::new();
let mut changes = Vec::new();
for (i, n) in w.nodes.iter().enumerate() {
if n.kind != UiKind::EditText
|| n.readonly
|| !n.enabled
|| !n.visible
|| events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i))
{
continue;
}
if let Some(text) = self.drafts.get(&n.id) {
if *text != n.text {
changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?);
}
given.push(n.id);
}
}
for id in given {
self.drafts.remove(&id);
}
let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close);
events.sort_by_key(closing);
let at = events.iter().position(closing).unwrap_or(events.len());
events.splice(at..at, changes);
Ok(())
}
/// Takes out of `events` each text an edit field gave as it lost the focus that the script
/// would refuse, and puts it back in its field, so the person can fix it. → the error of the
/// last one.
pub(crate) fn keep_refused_texts(&mut self, events: &mut Vec<UiEvent>) -> Option<String> {
let mut refused = None;
let (w, drafts) = (&self.window, &mut self.drafts);
events.retain(|e| {
let UiEvent::Change(i, UiValue::Text(text)) = e else { return true };
match check_event(w, e.clone()) {
Ok(_) => true,
Err(error) => {
if let Some(n) = w.nodes.get(*i) {
drafts.insert(n.id, text.clone());
}
refused = Some(error);
false
}
}
});
refused
}
/// The next queued event the dialog `w` can still take, with its control's index in `w` now.
/// An event whose control or list items a handler removed since it was given is dropped.
fn next_event(&mut self, w: &ScriptUiDialog) -> Option<UiEvent> {
while let Some(next) = self.queue.pop_front() {
if let Some(event) = resolved(w, next) {
return Some(event);
}
}
None
}
/// The events the person gave in this pass, after the ones before them: the typed texts the
/// script would refuse go back in their fields, and a click gives the typed texts first, or
/// waits while one of them is refused.
fn take_events(&mut self, mut events: Vec<UiEvent>) {
if let Some(e) = self.keep_refused_texts(&mut events) {
self.status = Some(e);
}
if events.iter().any(|e| matches!(e, UiEvent::Click(_))) {
let w = self.window.clone();
if let Err(e) = self.commit_drafts(&w, &mut events) {
// A refused text stays in its field, and the click waits for the person to fix it.
events.retain(|e| !matches!(e, UiEvent::Click(_)));
self.status = Some(e);
}
}
for e in &events {
self.queue(e);
}
}
}
/// `event` in the dialog `w`, with its control by its id.
fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option<Queued> {
let id = |i: usize| w.nodes.get(i).map(|n| n.id);
Some(match event {
UiEvent::Click(i) => Queued::Click(id(*i)?),
UiEvent::Change(i, v) => {
let items = matches!(v, UiValue::Index(_)).then(|| w.nodes.get(*i).map(|n| (n.items.clone(), n.items_revision))).flatten();
Queued::Change(id(*i)?, v.clone(), items)
}
UiEvent::Close => Queued::Close,
})
}
/// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now.
/// `None` when `w` no longer has the control, or for a list's change, when the list's items are no
/// longer those the person chose from.
fn resolved(w: &ScriptUiDialog, q: Queued) -> Option<UiEvent> {
match q {
Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)),
Queued::Change(id, v, items) => {
let i = index_of(w, id)?;
if items.is_some_and(|(items, revision)| items != w.nodes[i].items || revision != w.nodes[i].items_revision) {
return None;
}
Some(UiEvent::Change(i, v))
}
Queued::Close => Some(UiEvent::Close),
Queued::Cancel => Some(cancel_event(w)),
}
}
/// The dialog `w`'s cancel: a click on its cancel button, or its close box when it has none or the
/// button cannot be clicked.
fn cancel_event(w: &ScriptUiDialog) -> UiEvent {
w.cancel_element.map(UiEvent::Click).filter(|e| check_event(w, e.clone()).is_ok()).unwrap_or(UiEvent::Close)
}
/// The index of the control whose id ([`UiNode::id`]) is `id` in the dialog `w`, if it has one.
fn index_of(w: &ScriptUiDialog, id: u64) -> Option<usize> {
w.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0)
}
impl StackDialog for ScriptWindow {
type Result = ();
fn id(&self) -> DialogId {
dialog_id(KIND)
}
fn key(&self) -> Option<&str> {
Some(KIND)
}
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<()>> {
let top = stack.is_top(self.id());
let heading = match self.window.title() {
"" => tl!("Script Alert").to_string(),
title => shown_text(title, false),
};
let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)];
let ScriptWindow { window, waiting, drafts, open, .. } = self;
let (window, waiting, drafts) = (&*window, *waiting, &*drafts);
// The dialog opens with the focus on its default button, so Enter clicks it until the
// person moves the focus into a field; without one that can be clicked, on its first control.
let focus_default = window.default_element.and_then(|i| window.nodes.get(i)).is_some_and(|n| n.visible && n.enabled);
let initial = if focus_default { Initial::Default } else { Initial::First };
let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open));
// The body can run twice in a pass (measure, then paint), so it only reports what the
// person did; the dialog applies the last run's report after the container.
let shown = dialog.show(ui, |ui, _| {
let (width, height) = window.size();
let size = egui::vec2(width.max(1.0), height.max(1.0));
let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() };
ui.scope(|ui| {
ui.set_max_size(MAX_SHOWN);
Stack::new().scroll(Scroll::both()).show(ui, |ui, _| {
let origin = ui.cursor().min;
ui.set_min_size(size);
// Each container comes before the controls it holds.
let mut containers: Vec<Option<egui::Id>> = vec![None; window.nodes.len()];
for (i, n) in window.nodes.iter().enumerate().skip(1) {
if !n.visible {
continue;
}
let parent = containers.get(n.parent).copied().flatten();
let place = Place { origin, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent };
let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i)));
if let Some(slot) = containers.get_mut(i) {
*slot = shown.container;
}
pass.typing |= shown.typing;
pass.events.extend(shown.event);
pass.drafts.extend(shown.draft.map(|d| (n.id, d)));
}
});
});
pass
});
let pass = shown.inner.unwrap_or_default();
if pass.layer.is_some() {
self.layer = pass.layer;
}
for (id, draft) in pass.drafts {
match draft {
Some(text) => self.drafts.insert(id, text),
None => self.drafts.remove(&id),
};
}
let (mut events, typing) = (pass.events, pass.typing);
// An Enter the focused control left untaken (a slider, a check box, a button) is the
// dialog's, unless a question is open over it or a field has the focus.
let submit = top && !typing && take_submit(ui.ctx());
if shown.output.picked == Some(0) {
self.stop = true;
return None;
}
// Escape and the close box click the cancel button: the dialog stays open until the script
// closes it.
if shown.output.closed.is_some() {
self.open = true;
self.cancel = true;
return None;
}
// Enter in a field belongs to the field; with the focus on any other control, it clicks the
// default button.
if events.is_empty() && self.waiting && submit {
events.extend(self.window.default_element.map(UiEvent::Click));
}
if !events.is_empty() {
self.take_events(events);
}
None
}
fn json_fields(&self) -> Option<Value> {
Some(json!({
"title": self.window.title(),
"event": self.event,
"control": self.control,
"value": self.value,
}))
}
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: Value) -> Result<(), String> {
match field {
"event" => {
let event = match &value {
Value::Null => None,
Value::String(e) if matches!(e.as_str(), "click" | "change" | "close") => Some(e.clone()),
_ => return Err("`event` must be click, change or close".into()),
};
self.event = event;
}
"control" => {
if !matches!(value, Value::Null | Value::Number(_) | Value::String(_)) {
return Err("`control` must be a control's index, name or text".into());
}
self.control = Some(value).filter(|v| !v.is_null());
}
"value" => self.value = Some(value),
"title" => return Err(FieldRefusal::ReadOnly.message(field)),
_ => return Err(FieldRefusal::Unknown.message(field)),
}
Ok(())
}
}
/// Where a control is drawn: from `origin`, enabled or not, whether it is the default button, and
/// the accessibility node of the group or panel that holds it.
struct Place {
origin: egui::Pos2,
enabled: bool,
default: bool,
parent: Option<egui::Id>,
}
/// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus,
/// a group's or a panel's accessibility node, and an edit field's typed text to keep (`Some`) or
/// forget (`None`).
#[derive(Default)]
struct Shown {
event: Option<UiEvent>,
typing: bool,
container: Option<egui::Id>,
draft: Option<Option<String>>,
}
/// What one run of the dialog's body gave: the events, whether an edit field has the keyboard
/// focus, the typed texts to keep or forget, by field id, and the overlay layer it was drawn in.
#[derive(Default)]
struct Pass {
events: Vec<UiEvent>,
typing: bool,
drafts: Vec<(u64, Option<String>)>,
layer: Option<egui::Id>,
}
/// The text of the visible static text just before control `i` in its container: the visible
/// prompt of an edit field, a list box or a drop-down list, which screen readers call one without a
/// name by. Empty when there is none.
pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str {
let Some(parent) = w.nodes.get(i).map(|n| n.parent) else { return "" };
match w.nodes[..i].iter().skip(1).rev().find(|n| n.parent == parent && n.visible) {
Some(n) if n.kind == UiKind::StaticText => &n.text,
_ => "",
}
}
/// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place.
fn control(ui: &mut Ui, drafts: &BTreeMap<u64, String>, place: &Place, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
let rect = egui::Rect::from_min_size(place.origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h));
let mut shown = Shown::default();
let enabled = place.enabled;
let salt = (KIND, n.id);
// A control in a group or a panel is that container's child in the accessibility tree.
let builder = egui::UiBuilder::new().id_salt(n.id).max_rect(rect);
let builder = match place.parent {
Some(parent) => builder.accessibility_parent(parent),
None => builder,
};
ui.scope_builder(builder, |ui| match n.kind {
UiKind::Dialog => {}
UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)),
UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)),
UiKind::StaticText => {
Text::new(n.text.clone()).show_at(ui, rect);
}
UiKind::Button => {
let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled);
if place.default {
button = button.variant(Variant::PRIMARY).default_stop();
}
if clicked(&button.show_at(ui, rect)) {
shown.event = Some(UiEvent::Click(i));
}
}
UiKind::CheckBox => {
// A check box is shown in the flow of its place, which draws its text after the box.
let out = Checkbox::new(Bind::given(n.checked)).label(n.text.clone()).id_salt(salt).enabled(enabled).show(ui);
if out.events.committed().is_some() {
shown.event = Some(UiEvent::Click(i));
}
}
UiKind::RadioButton => {
let mut picked = false;
let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show_at(ui, rect, |ui, _| {
picked = clicked(&Radio::new(true).label(n.text.clone()).enabled(enabled).show(ui));
});
if picked || out.events.committed().is_some() {
shown.event = Some(UiEvent::Click(i));
}
}
UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)),
UiKind::DropDownList => {
let entries: Vec<Entry<Option<usize>>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect();
let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect);
if let Some(k) = out.events.committed().copied().filter(|k| *k != n.selection) {
shown.event = Some(UiEvent::Change(i, UiValue::Index(k)));
}
}
UiKind::ListBox => {
let keys: Vec<usize> = (0..n.items.len()).collect();
let source = keyed(&keys, |k: &usize| *k);
let selection = n.selection.map(Selection::single).unwrap_or_default();
// Screen readers read the box as a list box, by its name or the static text before
// it, with the selected item as its value. The box has no opener to keep the keyboard
// focus, so a press on a row gives it the focus and the arrow keys go on from that row.
// The rows it shows are as many as fit in its height at the height the list draws them.
let row = RowHeight::Control.of(&StyleCx::of_env(ui.ctx(), &Env::of(ui)));
let out = List::<usize>::options(list_name(n, prompt))
.focus_on_press(true)
.id_salt(salt)
.enabled(enabled)
.max_rows(list_rows(n.rect.h, row))
.selection(Bind::given(selection))
.show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default()));
// A click activates a row; the arrow keys and typed letters select one.
for event in out.events {
let picked = match event {
CollectionEvent::Activate(k) => Some(k),
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(),
_ => None,
};
if let Some(k) = picked.filter(|k| n.selection != Some(*k)) {
shown.event = Some(UiEvent::Change(i, UiValue::Index(Some(k))));
}
}
}
UiKind::Slider => {
let out = Slider::new(Bind::given(n.value), n.min..=n.max)
.label(screen_reader_name(n, prompt))
.id_salt(salt)
.enabled(enabled)
.show_at(ui, rect);
if let Some(v) = out.events.committed().copied().filter(|v| *v != n.value) {
shown.event = Some(UiEvent::Change(i, UiValue::Number(v)));
}
}
UiKind::ProgressBar => {
Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show_at(ui, rect);
}
});
shown
}
/// A panel: a group box titled by its text over the panel's place; screen readers read it as a
/// group, disabled when the panel is. → the id of its node in the accessibility tree.
fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id {
let shown = GroupBox::new(n.text.clone(), None).id_salt((KIND, n.id)).enabled(enabled).show_at(ui, rect, |_, _| ());
shown.output.response.id
}
/// A group, which draws nothing; screen readers read it as a group called by the name the script
/// gave it, disabled when the group is.
/// → the id of its node in the accessibility tree.
fn group(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id {
let (enabled, name) = (enabled && ui.is_enabled(), n.name.clone());
let r = ui.interact(rect, ui.scope_id().with("group"), egui::Sense::hover());
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name));
r.id
}
/// The name screen readers call a list box or a drop-down list `n` by: the visible static text
/// just before it, or else the name the script gave it, or else "Value".
fn list_name(n: &UiNode, prompt: &str) -> String {
match (prompt, n.name.as_str()) {
("", "") => tl!("Value").to_string(),
("", name) => name.to_string(),
(prompt, _) => prompt.to_string(),
}
}
/// The name screen readers call a control with no visible label of its own (an edit field, a
/// slider or a progress bar) by: the visible static text just before it in its container, or else
/// the name the script gave it, or else a slider's or progress bar's text, or else "Text" for an
/// edit field and "Value" for the others.
pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String {
let name = if !prompt.is_empty() {
prompt
} else if !n.name.is_empty() || n.kind == UiKind::EditText {
&n.name
} else {
&n.text
};
match name {
"" if n.kind == UiKind::EditText => tl!("Text").to_string(),
"" => tl!("Value").to_string(),
name => name.to_string(),
}
}
/// The most characters an edit field takes while it is typed: twice the longest text a script
/// accepts, so that a text that is too long can still be typed, refused and shortened.
pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES;
/// An edit field: its text is kept in the dialog while it is typed and given to the script when
/// the field loses the focus, or at Enter in a one-line field.
fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap<u64, String>, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown {
let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone());
let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text))
.limit(DRAFT_CHARS)
.id_salt((KIND, n.id))
.enabled(enabled)
.read_only(n.readonly);
if n.multiline {
field = field.lines(3);
}
let out = field.show_at(ui, rect);
let focused = out.response.has_focus();
let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone()));
let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus();
if committed && text != n.text && !n.readonly {
return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) };
}
// A text the script refused stays in the field until the person changes it.
if !focused && text == n.text {
draft = Some(None);
}
Shown { event: None, typing: focused || committed, container: None, draft }
}
/// The event in the dialog's fields, for the dialog `w`.
fn event_of(w: &ScriptUiDialog, d: &ScriptWindow) -> Result<UiEvent, String> {
// A close names no control, so a `control` left from an earlier event does not stop it.
if d.event.as_deref() == Some("close") {
return Ok(UiEvent::Close);
}
let control = match &d.control {
Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?,
Some(Value::String(s)) => w.find(s).ok_or_else(|| format!("the dialog has no control named {}", cut_to(s, 64)))?,
_ => 0,
};
let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox));
match (d.event.as_deref(), &d.value) {
(Some("click"), _) => Ok(UiEvent::Click(control)),
(Some("change"), Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))),
(Some("change"), Some(Value::Number(v))) if list => match list_index(v) {
Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(k)))),
None => Err("a list's `value` must be an item index or null".into()),
},
(Some("change"), Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))),
(Some("change"), Some(Value::Null) | None) if list => Ok(UiEvent::Change(control, UiValue::Index(None))),
(Some("change"), _) => Err("a change's `value` must be a string, a number or null".into()),
_ => Err("`event` must be click, change or close".into()),
}
}
/// Runs `f` on the open ScriptUI dialog; `None` when none is open.
pub(crate) fn with_window<R>(app: &VectorcraftApp, f: impl FnOnce(&mut ScriptWindow) -> R) -> Option<R> {
with_host(app, |host, _| host.get_mut::<ScriptWindow>().map(f)).flatten()
}
/// Whether the ScriptUI dialog is open and no other dialog is open over it.
pub(crate) fn is_top(app: &VectorcraftApp) -> bool {
with_host(app, |host, _| host.get::<ScriptWindow>().is_some_and(|d| host.stack().is_top(d.id()))).unwrap_or(false)
}
/// Whether the ScriptUI dialog is the top dialog and no popup or modal layer, its own drop-down
/// lists' included, is open over it.
pub(crate) fn uncovered(app: &VectorcraftApp) -> bool {
let Some(layer) = with_window(app, |d| d.layer) else { return false };
let top = app.ui_ctx.as_ref().and_then(overlay::top);
is_top(app) && top.is_none_or(|top| Some(top) == layer)
}
/// Opens, keeps or closes the ScriptUI dialog as the run's `show()` stands: it opens when a
/// `show()` waits, follows the dialog while the run waits at it (its heading follows a title a
/// handler changed), stays open while one of its handlers runs and closes when `show()` ends. A
/// dialog the script showed after closing the one that is open replaces it.
pub(crate) fn sync(app: &mut VectorcraftApp) {
let Some(showing) = app.session.script_window_showing() else {
super::script_run::forget::<ScriptWindow>(app);
return;
};
let open_for = with_window(app, |d| d.shown());
if open_for.is_some_and(|shown| shown != showing.shown) {
super::script_run::forget::<ScriptWindow>(app);
}
let waiting = app.session.script_window();
if open_for == Some(showing.shown) {
with_window(app, |d| d.sync(waiting));
} else if let Some(w) = waiting
&& !super::script_run::busy(app)
{
with_host(app, |host, _| host.open(ScriptWindow::new(w)));
}
}
/// Takes what the person did in the dialog, once per frame, and gives the run its next event while
/// it waits at the dialog.
pub(crate) fn pump(app: &mut VectorcraftApp) {
let Some((stop, cancel_asked, status)) = with_window(app, |d| (std::mem::take(&mut d.stop), std::mem::take(&mut d.cancel), d.status.take()))
else {
return;
};
if let Some(e) = status {
app.status(e);
}
if stop {
app.session.script_request_stop();
super::script_run::forget::<ScriptWindow>(app);
return;
}
if cancel_asked && let Err(e) = cancel(app) {
app.status(e);
}
// Events wait in the queue while another dialog, such as the quit question, is open over it.
if !is_top(app) {
return;
}
let Some(w) = app.session.script_window() else { return };
if with_window(app, |d| d.shown()) != Some(w.shown) {
return;
}
if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() {
// A typed text the script refuses (an earlier handler disabled its field, say) goes back
// in its field, so the person does not have to type it again.
let typed = match &event {
UiEvent::Change(i, UiValue::Text(t)) => w.nodes.get(*i).map(|n| (n.id, t.clone())),
_ => None,
};
if let Err(e) = give(app, &w, event) {
if let Some((id, text)) = typed {
with_window(app, |d| d.drafts.insert(id, text));
}
app.status(e);
}
}
}
/// Gives the run `event` in the dialog `w` it waits at. Before a click or a close, the script is
/// given the text still typed in the dialog's fields first, and the click or close waits for its
/// next wait.
fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result<(), String> {
let mut events = vec![check_event(w, event)?];
if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) {
with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?;
}
let mut events = events.into_iter();
if let Some(first) = events.next() {
app.session.script_window_answer(first)?;
}
let later: Vec<Queued> = events.filter_map(|e| queued(w, &e)).collect();
with_window(app, |d| {
for q in later.into_iter().rev() {
d.queue.push_front(q);
}
});
Ok(())
}
/// `ui.dialog.confirm`: gives the running script the event in the dialog's fields. The dialog stays
/// open for the script's next wait; an event it cannot take is an error.
pub(crate) fn confirm(app: &mut VectorcraftApp) -> Result<Value, String> {
let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) };
let event = with_window(app, |d| event_of(&w, d)).ok_or("no script dialog waits")??;
if with_window(app, |d| d.queue.is_empty()).unwrap_or(true) {
give(app, &w, event)?;
} else {
// Events the script has not had yet come first; this one, and the typed texts before a
// click or a close, go after them.
let mut events = vec![check_event(&w, event)?];
if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) {
with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?;
}
let later: Vec<Queued> = events.iter().filter_map(|e| queued(&w, e)).collect();
with_window(app, |d| d.queue.extend(later));
}
with_window(app, |d| (d.event, d.control, d.value) = (None, None, None));
Ok(Value::Null)
}
/// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog
/// has none or it cannot be clicked, after the text still typed in its fields. Events the script
/// has not had yet go after the ones before them. A typed text the script would refuse is an
/// error, and the dialog is left as it was. While a handler runs, the cancel waits for the dialog
/// the run waits at next.
pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> {
let Some(w) = app.session.script_window() else {
return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string());
};
let mut events = vec![cancel_event(&w)];
with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?;
let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true);
// A cancel after other events goes last, and is a click on the cancel button of the dialog the
// run waits at when its turn comes, or its close box.
let deferred = !empty || events.len() > 1;
if deferred {
events.pop();
}
let mut events = events.into_iter();
if empty && let Some(first) = events.next() {
app.session.script_window_answer(first)?;
}
let mut later: Vec<Queued> = events.filter_map(|e| queued(&w, &e)).collect();
if deferred {
later.push(Queued::Cancel);
}
with_window(app, |d| d.queue.extend(later));
Ok(())
}
/// `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` (`method`, with `params` naming the
/// dialog) when they name the ScriptUI dialog; `None` for any other dialog. `ui.dialog.set` sets
/// the fields as the host does, then answers with its `action`.
pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Value) -> Option<Result<Value, String>> {
let ours = with_host(app, |host, _| craft::automation::dialogs::dialog_id(host, params).is_ok_and(|id| id == dialog_id(KIND)))?;
if !ours {
return None;
}
// The parameters each method takes, checked before anything is set or given.
let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] };
if let Err(e) = Params(params).only(None, keys) {
return Some(Err(e));
}
let mut params = params.clone();
let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None };
let answer = match (method, action.as_ref().map(Value::as_str)) {
("ui.dialog.confirm", _) | (_, Some(Some("confirm"))) => Some(true),
("ui.dialog.cancel", _) | (_, Some(Some("cancel"))) => Some(false),
(_, None) => None,
(_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())),
};
// A dialog open over it, such as the quit question, takes its answer first.
if answer == Some(true) && with_host(app, |host, _| host.stack().has_child(dialog_id(KIND))).unwrap_or(false) {
return Some(Err("the dialog refuses OK while a dialog open over it waits for its answer".into()));
}
// A set without an action sets a field, which the host's setter asks for when none is given.
if method == "ui.dialog.set" && (answer.is_none() || params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog"))) {
let set = with_host(app, |host, ctx| craft::automation::dialogs::dialog_method(host, ctx, method, &params)).flatten();
if let Some(Err(e)) = set {
return Some(Err(e));
}
}
Some(match answer {
Some(true) => confirm(app),
Some(false) => cancel(app).map(|()| Value::Null),
// A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do.
None => Ok(with_host(app, |host, _| {
let id = dialog_id(KIND).value().to_string();
craft::automation::dialogs::inspect(host).as_array().and_then(|open| open.iter().find(|d| d["id"] == id.as_str()).cloned())
})
.flatten()
.unwrap_or(Value::Null)),
})
}
+3 -1
View File
@@ -6623,7 +6623,9 @@ liquify-list-end {0}, {1} {0} i {1}
@msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false
@msg is longer than 16 KiB ocupa més de 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null
@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt
@msg must have `kind` alert, confirm, prompt or window ha de tenir `kind` alert, confirm, prompt o window
@msg is a window's answer, whose `value` must be a list of steps és la resposta d’una finestra, el `value` de la qual ha de ser una llista de passos
@msg has a step {i} that is not a valid click, change or close té un pas {i} que no és un clic, un canvi ni un tancament vàlid
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells
Can't render this file because it is too large.
+3 -1
View File
@@ -9999,7 +9999,9 @@ breakText Glyphs Glyfy
@msg more than {MAX_IMPORT} presets více než {MAX_IMPORT} přednastavení
@msg moved must be [[x,y]…] moved musí být [[x,y]…]
@msg must be an object with `kind` and `value` musí být objekt s `kind` a `value`
@msg must have `kind` alert, confirm or prompt musí mít `kind` alert, confirm nebo prompt
@msg must have `kind` alert, confirm, prompt or window musí mít `kind` alert, confirm, prompt nebo window
@msg is a window's answer, whose `value` must be a list of steps je odpověď okna, jejíž `value` musí být seznam kroků
@msg has a step {i} that is not a valid click, change or close má krok {i}, který není platné kliknutí, změna ani zavření
@msg must have exactly `kind` and `value` musí mít právě `kind` a `value`
@msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné
@msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec
Can't render this file because it is too large.
+3 -1
View File
@@ -235,7 +235,9 @@ liquify-list-end {0}, {1} {0} og {1}
@msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false
@msg is longer than 16 KiB er længere end 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null
@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt
@msg must have `kind` alert, confirm, prompt or window skal have `kind` alert, confirm, prompt eller window
@msg is a window's answer, whose `value` must be a list of steps er et vindues svar, hvis `value` skal være en liste over trin
@msg has a step {i} that is not a valid click, change or close har et trin {i}, der ikke er et gyldigt klik, en gyldig ændring eller en gyldig lukning
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt
Can't render this file because it is too large.
+3 -1
View File
@@ -8755,7 +8755,9 @@ breakText Glyphs Glyphen
@msg missing `picks` `picks` fehlt
@msg missing `word` `word` fehlt
@msg must be an object with `kind` and `value` muss ein Objekt mit `kind` und `value` sein
@msg must have `kind` alert, confirm or prompt muss `kind` alert, confirm oder prompt haben
@msg must have `kind` alert, confirm, prompt or window muss `kind` alert, confirm, prompt oder window haben
@msg is a window's answer, whose `value` must be a list of steps ist die Antwort auf ein Fenster, deren `value` eine Liste von Schritten sein muss
@msg has a step {i} that is not a valid click, change or close hat einen Schritt {i}, der kein gültiger Klick, keine gültige Änderung und kein gültiges Schließen ist
@msg must have exactly `kind` and `value` muss genau `kind` und `value` haben
@msg needs a closing quote after the name braucht ein schließendes Anführungszeichen nach dem Namen
@msg needs a name braucht einen Namen
Can't render this file because it is too large.
+3 -1
View File
@@ -2815,7 +2815,9 @@ liquify-list-end {0}, {1} {0} και {1}
@msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false
@msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null
@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt
@msg must have `kind` alert, confirm, prompt or window πρέπει να έχει `kind` alert, confirm, prompt ή window
@msg is a window's answer, whose `value` must be a list of steps είναι απάντηση παραθύρου, της οποίας το `value` πρέπει να είναι λίστα βημάτων
@msg has a step {i} that is not a valid click, change or close έχει ένα βήμα {i} που δεν είναι έγκυρο κλικ, αλλαγή ή κλείσιμο
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου
@msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1}
@msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων
Can't render this file because it is too large.
+3 -1
View File
@@ -5093,7 +5093,9 @@ liquify-list-end {0}, {1} {0}, {1}
@msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false
@msg is longer than 16 KiB ocupa más de 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null
@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt
@msg must have `kind` alert, confirm, prompt or window debe tener `kind` alert, confirm, prompt o window
@msg is a window's answer, whose `value` must be a list of steps es la respuesta de una ventana, cuyo `value` debe ser una lista de pasos
@msg has a step {i} that is not a valid click, change or close tiene un paso {i} que no es un clic, un cambio ni un cierre válido
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles
Can't render this file because it is too large.
+3 -1
View File
@@ -5336,7 +5336,9 @@ liquify-list-end {0}, {1} {0} ja {1}
@msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false
@msg is longer than 16 KiB on pidempi kuin 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null
@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt
@msg must have `kind` alert, confirm, prompt or window `kind`-arvon on oltava alert, confirm, prompt tai window
@msg is a window's answer, whose `value` must be a list of steps on ikkunan vastaus, jonka `value`-arvon on oltava luettelo vaiheista
@msg has a step {i} that is not a valid click, change or close sisältää vaiheen {i}, joka ei ole kelvollinen napsautus, muutos tai sulkeminen
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä
Can't render this file because it is too large.
+3 -1
View File
@@ -9859,7 +9859,9 @@ breakText Glyphs Glyphes
@msg more than {MAX_IMPORT} presets plus de {MAX_IMPORT} paramètres prédéfinis
@msg moved must be [[x,y]…] moved doit être [[x,y]…]
@msg must be an object with `kind` and `value` doit être un objet avec `kind` et `value`
@msg must have `kind` alert, confirm or prompt doit avoir `kind` alert, confirm ou prompt
@msg must have `kind` alert, confirm, prompt or window doit avoir `kind` alert, confirm, prompt ou window
@msg is a window's answer, whose `value` must be a list of steps est la réponse d’une fenêtre, dont la `value` doit être une liste d’étapes
@msg has a step {i} that is not a valid click, change or close a une étape {i} qui n’est ni un clic, ni une modification, ni une fermeture valide
@msg must have exactly `kind` and `value` doit avoir exactement `kind` et `value`
@msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est obligatoire
@msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne
Can't render this file because it is too large.
+3 -1
View File
@@ -7826,7 +7826,9 @@ liquify-list-end {0}, {1} {0} और {1}
@msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए
@msg is longer than 16 KiB 16 KiB से लंबा है
@msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए
@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए
@msg must have `kind` alert, confirm, prompt or window `kind` alert, confirm, prompt या window होना चाहिए
@msg is a window's answer, whose `value` must be a list of steps एक window का उत्तर है, जिसका `value` चरणों की सूची होना चाहिए
@msg has a step {i} that is not a valid click, change or close में चरण {i} मान्य क्लिक, बदलाव या बंद करना नहीं है
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए
@msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है
Can't render this file because it is too large.
+3 -1
View File
@@ -9869,7 +9869,9 @@ breakText Glyphs Glifák
@msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás
@msg moved must be [[x,y]…] moved: [[x,y]…] kell
@msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell
@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen
@msg must have `kind` alert, confirm, prompt or window a `kind` értéke alert, confirm, prompt vagy window kell legyen
@msg is a window's answer, whose `value` must be a list of steps egy ablak válasza, amelynek `value` értéke lépések listája kell legyen
@msg has a step {i} that is not a valid click, change or close {i}. lépése nem érvényes kattintás, módosítás vagy bezárás
@msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia
@msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező
@msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell
Can't render this file because it is too large.
+3 -1
View File
@@ -141,7 +141,9 @@
@msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false
@msg is longer than 16 KiB lebih panjang dari 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null
@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt
@msg must have `kind` alert, confirm, prompt or window harus memiliki `kind` alert, confirm, prompt, atau window
@msg is a window's answer, whose `value` must be a list of steps adalah jawaban jendela, yang `value`-nya harus berupa daftar langkah
@msg has a step {i} that is not a valid click, change or close memiliki langkah {i} yang bukan klik, perubahan, atau penutupan yang valid
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat
Can't render this file because it is too large.
+3 -1
View File
@@ -8804,7 +8804,9 @@ breakText Glyphs Glifi
@msg missing `picks` `picks` mancante
@msg missing `word` `word` mancante
@msg must be an object with `kind` and `value` deve essere un oggetto con `kind` e `value`
@msg must have `kind` alert, confirm or prompt deve avere `kind` alert, confirm o prompt
@msg must have `kind` alert, confirm, prompt or window deve avere `kind` alert, confirm, prompt o window
@msg is a window's answer, whose `value` must be a list of steps è la risposta di una finestra, il cui `value` deve essere un elenco di passaggi
@msg has a step {i} that is not a valid click, change or close ha un passaggio {i} che non è un clic, una modifica o una chiusura validi
@msg must have exactly `kind` and `value` deve avere esattamente `kind` e `value`
@msg needs a closing quote after the name richiede una virgoletta di chiusura dopo il nome
@msg needs a name richiede un nome
Can't render this file because it is too large.
+3 -1
View File
@@ -7618,7 +7618,9 @@ axis Y Axis Y 軸
@msg missing `picks` `picks` がありません
@msg missing `word` `word` がありません
@msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください
@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください
@msg must have `kind` alert, confirm, prompt or window の `kind` には alert、confirm、prompt、window のいずれかを指定してください
@msg is a window's answer, whose `value` must be a list of steps は window の回答で、`value` には手順のリストを指定してください
@msg has a step {i} that is not a valid click, change or close の手順 {i} は有効なクリック、変更、閉じる操作のいずれでもありません
@msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください
@msg needs a closing quote after the name 名前の後に閉じ引用符が必要です
@msg needs a name 名前が必要です
Can't render this file because it is too large.
+3 -1
View File
@@ -1088,7 +1088,9 @@
@msg more than {MAX_IMPORT} presets {MAX_IMPORT}-ზე მეტი პრესეტი
@msg moved must be [[x,y]…] moved უნდა იყოს [[x,y]…]
@msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ით და `value`-თი
@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt
@msg must have `kind` alert, confirm, prompt or window `kind` უნდა იყოს alert, confirm, prompt ან window
@msg is a window's answer, whose `value` must be a list of steps არის ფანჯრის პასუხი, რომლის `value` უნდა იყოს ნაბიჯების სია
@msg has a step {i} that is not a valid click, change or close შეიცავს ნაბიჯს {i}, რომელიც არ არის სწორი დაწკაპუნება, ცვლილება ან დახურვა
@msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value`
@msg name (a toolbar's name) is required საჭიროა name (ხელსაწყოთა ზოლის სახელი)
@msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) უნდა იყოს სტრიქონი
Can't render this file because it is too large.
+3 -1
View File
@@ -9637,7 +9637,9 @@ breakText Glyphs 글리프
@msg more than {MAX_IMPORT} presets 사전 설정이 {MAX_IMPORT}개보다 많습니다
@msg moved must be [[x,y]…] moved는 [[x,y]…]여야 합니다
@msg must be an object with `kind` and `value` `kind`와 `value`가 있는 개체여야 합니다
@msg must have `kind` alert, confirm or prompt `kind`가 alert, confirm 또는 prompt여야 합니다
@msg must have `kind` alert, confirm, prompt or window `kind`가 alert, confirm, prompt 또는 window여야 합니다
@msg is a window's answer, whose `value` must be a list of steps 창의 답이며, `value`는 단계 목록이어야 합니다
@msg has a step {i} that is not a valid click, change or close 단계 {i}이(가) 올바른 클릭, 변경 또는 닫기가 아닙니다
@msg must have exactly `kind` and `value` `kind`와 `value`만 있어야 합니다
@msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다
@msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다
Can't render this file because it is too large.
+3 -1
View File
@@ -7503,7 +7503,9 @@ imageTrace Outline Contour
@msg more than {MAX_IMPORT} presets meer dan {MAX_IMPORT} voorinstellingen
@msg moved must be [[x,y]…] moved moet [[x,y]…] zijn
@msg must be an object with `kind` and `value` moet een object met `kind` en `value` zijn
@msg must have `kind` alert, confirm or prompt moet `kind` alert, confirm of prompt hebben
@msg must have `kind` alert, confirm, prompt or window moet `kind` alert, confirm, prompt of window hebben
@msg is a window's answer, whose `value` must be a list of steps is het antwoord van een venster, waarvan `value` een lijst met stappen moet zijn
@msg has a step {i} that is not a valid click, change or close heeft een stap {i} die geen geldige klik, wijziging of sluiting is
@msg must have exactly `kind` and `value` moet precies `kind` en `value` hebben
@msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist
@msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn
Can't render this file because it is too large.
+3 -1
View File
@@ -9008,7 +9008,9 @@ breakText Glyphs Glify
@msg missing `picks` brak `picks`
@msg missing `word` brak `word`
@msg must be an object with `kind` and `value` musi być obiektem z `kind` i `value`
@msg must have `kind` alert, confirm or prompt `kind` musi mieć wartość alert, confirm lub prompt
@msg must have `kind` alert, confirm, prompt or window `kind` musi mieć wartość alert, confirm, prompt lub window
@msg is a window's answer, whose `value` must be a list of steps jest odpowiedzią okna, której `value` musi być listą kroków
@msg has a step {i} that is not a valid click, change or close ma krok {i}, który nie jest prawidłowym kliknięciem, zmianą ani zamknięciem
@msg must have exactly `kind` and `value` musi mieć dokładnie `kind` i `value`
@msg needs a closing quote after the name wymaga zamykającego cudzysłowu po nazwie
@msg needs a name wymaga nazwy
Can't render this file because it is too large.
+3 -1
View File
@@ -10061,7 +10061,9 @@ swatch Yellow Green Verde-amarelado
@msg more than {MAX_IMPORT} presets mais de {MAX_IMPORT} predefinições
@msg moved must be [[x,y]…] moved deve ser [[x,y]…]
@msg must be an object with `kind` and `value` deve ser um objeto com `kind` e `value`
@msg must have `kind` alert, confirm or prompt deve ter `kind` alert, confirm ou prompt
@msg must have `kind` alert, confirm, prompt or window deve ter `kind` alert, confirm, prompt ou window
@msg is a window's answer, whose `value` must be a list of steps é a resposta de uma janela, cujo `value` deve ser uma lista de etapas
@msg has a step {i} that is not a valid click, change or close tem uma etapa {i} que não é um clique, uma alteração nem um fechamento válido
@msg must have exactly `kind` and `value` deve ter exatamente `kind` e `value`
@msg name (a toolbar's name) is required name (o nome de uma barra de ferramentas) é obrigatório
@msg name (a toolbar's name) must be a string name (o nome de uma barra de ferramentas) deve ser uma string
Can't render this file because it is too large.
+3 -1
View File
@@ -5118,7 +5118,9 @@ liquify-list-end {0}, {1} {0} и {1}
@msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false
@msg is longer than 16 KiB длиннее 16 КиБ
@msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null
@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt
@msg must have `kind` alert, confirm, prompt or window должен иметь `kind` alert, confirm, prompt или window
@msg is a window's answer, whose `value` must be a list of steps является ответом окна, `value` которого должен быть списком шагов
@msg has a step {i} that is not a valid click, change or close содержит шаг {i}, который не является допустимым щелчком, изменением или закрытием
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней
Can't render this file because it is too large.
+3 -1
View File
@@ -4991,7 +4991,9 @@ liquify-list-end {0}, {1} {0} och {1}
@msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false
@msg is longer than 16 KiB är längre än 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null
@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt
@msg must have `kind` alert, confirm, prompt or window måste ha `kind` alert, confirm, prompt eller window
@msg is a window's answer, whose `value` must be a list of steps är ett fönsters svar, vars `value` måste vara en lista med steg
@msg has a step {i} that is not a valid click, change or close har ett steg {i} som inte är ett giltigt klick, en giltig ändring eller en giltig stängning
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt
Can't render this file because it is too large.
+3 -1
View File
@@ -7996,7 +7996,9 @@ axis Y Axis Y ekseni
@msg missing `picks` `picks` eksik
@msg missing `word` `word` eksik
@msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır
@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır
@msg must have `kind` alert, confirm, prompt or window `kind` değeri alert, confirm, prompt veya window olmalıdır
@msg is a window's answer, whose `value` must be a list of steps bir pencerenin yanıtıdır ve `value` değeri bir adım listesi olmalıdır
@msg has a step {i} that is not a valid click, change or close içindeki {i}. adım geçerli bir tıklama, değişiklik veya kapatma değil
@msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir
@msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir
@msg needs a name bir ad gerekir
Can't render this file because it is too large.
+3 -1
View File
@@ -9638,7 +9638,9 @@ breakText Glyphs Гліфи
@msg more than {MAX_IMPORT} presets понад {MAX_IMPORT} наборів
@msg moved must be [[x,y]…] moved має бути [[x,y]…]
@msg must be an object with `kind` and `value` має бути об’єктом із `kind` і `value`
@msg must have `kind` alert, confirm or prompt повинен мати `kind` зі значенням alert, confirm або prompt
@msg must have `kind` alert, confirm, prompt or window повинен мати `kind` зі значенням alert, confirm, prompt або window
@msg is a window's answer, whose `value` must be a list of steps є відповіддю вікна, `value` якої має бути списком кроків
@msg has a step {i} that is not a valid click, change or close має крок {i}, який не є допустимим клацанням, зміною або закриттям
@msg must have exactly `kind` and `value` повинен мати рівно `kind` і `value`
@msg name (a toolbar's name) is required name (ім’я панелі інструментів) є обов’язковим
@msg name (a toolbar's name) must be a string name (ім’я панелі інструментів) має бути рядком
Can't render this file because it is too large.
+3 -1
View File
@@ -5617,7 +5617,9 @@ liquify-list-end {0}, {1} {0} và {1}
@msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false
@msg is longer than 16 KiB dài hơn 16 KiB
@msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null
@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt
@msg must have `kind` alert, confirm, prompt or window phải có `kind` là alert, confirm, prompt hoặc window
@msg is a window's answer, whose `value` must be a list of steps là câu trả lời của một cửa sổ, có `value` phải là danh sách các bước
@msg has a step {i} that is not a valid click, change or close có bước {i} không phải là một lần nhấp, thay đổi hoặc đóng hợp lệ
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1}
@msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp
Can't render this file because it is too large.
+3 -1
View File
@@ -9016,7 +9016,9 @@ breakText Glyphs 字形
@msg missing `picks` 缺少 `picks`
@msg missing `word` 缺少 `word`
@msg must be an object with `kind` and `value` 必须是包含 `kind` 和 `value` 的对象
@msg must have `kind` alert, confirm or prompt `kind` 必须是 alert、confirm 或 prompt
@msg must have `kind` alert, confirm, prompt or window `kind` 必须是 alert、confirm、prompt 或 window
@msg is a window's answer, whose `value` must be a list of steps 是窗口的回答,其 `value` 必须是步骤列表
@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的点击、更改或关闭
@msg must have exactly `kind` and `value` 必须只包含 `kind` 和 `value`
@msg needs a closing quote after the name 名称后需要右引号
@msg needs a name 需要名称
Can't render this file because it is too large.
+3 -1
View File
@@ -8950,7 +8950,9 @@ breakText Glyphs 字符
@msg missing `picks` 未提供 `picks`
@msg missing `word` 未提供 `word`
@msg must be an object with `kind` and `value` 必須是包含 `kind` 和 `value` 的物件
@msg must have `kind` alert, confirm or prompt `kind` 必須是 alert、confirm 或 prompt
@msg must have `kind` alert, confirm, prompt or window `kind` 必須是 alert、confirm、prompt 或 window
@msg is a window's answer, whose `value` must be a list of steps 是視窗的回答,其 `value` 必須是步驟清單
@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的點按、變更或關閉
@msg must have exactly `kind` and `value` 只能有 `kind` 和 `value`
@msg needs a closing quote after the name 名稱之後需要結尾引號
@msg needs a name 需要名稱
Can't render this file because it is too large.
+15 -8
View File
@@ -1,13 +1,15 @@
//! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to
//! its end, while the app goes on drawing the documents as they were before the run. The status bar
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer.
//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog,
//! waits for the person's answer.
use serde_json::{Value, json};
use vectorcraft_engine::WindowView;
use crate::VectorcraftApp;
use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice};
use crate::dialogs::script_window;
/// Advances the running script by one slice, or asks what its growth needs asked.
pub fn poll(app: &mut VectorcraftApp) {
@@ -38,6 +40,7 @@ pub fn poll(app: &mut VectorcraftApp) {
};
script_run::forget::<GrowthQuestion>(app);
script_run::settle_close(app);
script_window::sync(app);
match result {
// The commands it ran are journaled now: a recording they no longer fit in names its limit.
Ok(_) => {
@@ -148,32 +151,36 @@ fn show_notes(app: &mut VectorcraftApp, notes: Vec<String>) {
}
}
/// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the
/// question about its growth. Closes the script's dialog when the run no longer waits at it.
/// → true while the run waits.
/// Opens what the run waits at, once no other dialog is open, or over the script's ScriptUI dialog:
/// the script's own dialog, or the question about its growth. Closes the script's dialog when the
/// run no longer waits at it, and the ScriptUI dialog when its `show()` ends. → true while the run
/// waits.
fn ask(app: &mut VectorcraftApp) -> bool {
script_window::sync(app);
if let Some(picker) = app.session.script_picker() {
if !script_run::busy(app) {
if script_run::can_ask(app) {
script_run::open_picker(app, picker);
}
return true;
}
script_run::forget::<ScriptFiles>(app);
if let Some(dialog) = app.session.script_dialog() {
if !script_run::busy(app) {
if script_run::can_ask(app) {
script_run::open_notice(app, &dialog);
}
return true;
}
// A run asked to stop no longer waits at its dialog.
script_run::forget::<ScriptNotice>(app);
// A run past its growth allowance asks about it first, also when its ScriptUI dialog waits
// again.
if app.session.script_waiting() {
if !script_run::busy(app) {
if script_run::can_ask(app) {
script_run::open_growth(app);
}
return true;
}
false
app.session.script_window().is_some()
}
/// Runs the script of `params` (`script.run`'s) that the person chose from File › Scripts, after
+1
View File
@@ -44,6 +44,7 @@ mod screenmode;
mod script_check;
mod script_dialogs;
mod script_run;
mod script_window;
mod scripts_menu;
mod scrub;
mod selectall;
File diff suppressed because it is too large. Load diff
+133 -4
View File
@@ -3258,10 +3258,12 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess
- `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as
text.
- `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for
`alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}`
for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the
run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and
`dialogsTruncated` is true when the list stopped at its limit.
`alert`, `{kind, message, title, noAsDefault, answer}` for `confirm`, `{kind, message, title, preset, answer}`
for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`).
`answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"`
for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a
`show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list
stopped at its limit.
```json
{"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}}
@@ -3312,6 +3314,133 @@ empty object are the same.
vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}'
```
The help pages https://extendscript.docsforadobe.dev/user-interface-tools/window-object/,
https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and
https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its
controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it:
- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) throws
an `Error` that says it is not available yet.
- `new Window` and `add` also take a resource specification in place of the type, as
https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/ describes it:
`"dialog { text: 'Settings', g: Group { label: StaticText { text: 'Name:' }, ok: Button { text: 'OK' } } }"`, or
`"[name:] Class { ... }"` for `add`. The other arguments are not read. Inside the braces, `properties` gives the
creation properties, each `name: Class { ... }` adds that control through `add`, with its limits, and sets it as
the container's property `name`, a list's `items` gives its item texts, and every other `name: value` sets that
property. A value is `null`, `true`, `false`, a quoted string, a number, an inline array or an inline object,
and the commas between properties may be left out. A malformed specification throws a `SyntaxError`, and one longer than 1 MiB or nested more than 64
deep throws a `RangeError` (VectorCraft's own limits).
- `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The
types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`,
`listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`,
and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value,
minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes
`properties` right after `bounds`, or fourth when the third argument is not an object, and a list may take
`properties` right after `bounds` in place of its items, with the item texts in `properties.items`; a list given
items both ways throws a `TypeError`. The `alignment` in `properties`,
and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values
(VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`,
`scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an
unknown type throws too. An `edittext` with `noecho` in its `properties` makes `show()` throw that a field that
hides its text is not available yet, before the dialog opens.
- A list's `add("item", text)` adds an item, `find(text)` gives the first item with that text or `null`,
`remove(what)` removes the item given by its index, the item itself or its text, `removeAll()` removes them all,
`items` lists them and `selection` is the selected item or `null`; setting it to an item or an index selects it.
An item has `text`, `index` and `selected`.
- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `size`, `minimumSize`,
`maximumSize`, `alignment`, `parent`, `window`, `show()`, `hide()` and `notify([event])`. Each size starts as an
object whose `width` and `height` are -1, so a script can set one side, as in `preferredSize.width = 100`; a side
of 0 or less is left to the layout (VectorCraft's own starting values). A container also has `children`,
`orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column),
`alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and
`remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item
or a control that is not there does nothing. A removed control has no `parent`, it and the controls it holds have
no `window`, and its events no longer reach the containers it was in, also when a handler removes it while its
event runs; `add`, `remove` and `removeAll` on it, or on a control it holds, throw an `Error`. When a `text`
getter changes the list or container while `remove(text)` looks for a match, `remove` throws an `Error` and
removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])`
and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing.
- Radio buttons added one after another in a container form a set: setting one's `value` to true, or clicking it,
sets the others in the set to false. A control of another kind between two radio buttons starts a new set, as
the JavaScript Tools Guide describes radio buttons
(https://raw.githubusercontent.com/Adobe-CEP/CEP-Resources/master/ExtendScript-Toolkit/Guides/JavaScript%20Tools%20Guide%20CC.pdf).
- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` run the handlers that the person's click or
change would run: a click turns a check box over and turns a radio button on, then runs `onClick` and the
`click` listeners. `notify` does not close the dialog, even for the default or cancel button. `notify()` gives a
click for a button, a check box and a radio button, and a change for the others.
- `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`,
and `removeEventListener` with the same arguments removes it, so that it does not run even when the event it was
waiting for is already running; a function registered twice for the same type and phase runs once. `show` can
be registered only on the dialog, and on a control it throws an `Error`. A window or control takes at most 256
handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own
limit). A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, `cancelable`
(always false), `detail` (1 for a click), `stopPropagation()` and `preventDefault()`, which does nothing. The
containers above the control run their `capture` handlers first, then the control runs its `onClick`,
`onChange` or `onChanging` and its own handlers, then the containers run their other handlers, from the nearest
out, until a handler calls `stopPropagation()`. The other documented event types (`focus`, `mouseover`,
`keydown` and the rest) throw that they are not available yet, and a handler that is not a function throws a
`TypeError`.
- `Window.alert`, `Window.confirm` and `Window.prompt` open the same dialogs as `alert`, `confirm` and `prompt`.
`show()` opens the dialog, runs `onShow` and the `show` handlers, and waits for the person. A click runs the
control's `onClick` and `click` handlers; a check box turns its value over first, and a radio button turns on and
the other radio buttons of its set off. An edit field gives its text when it loses the keyboard focus, at Enter in
a one-line field, or before a click on another control, and a slider gives its value when it is let go: each runs
`onChanging` and then `onChange`. A list's new selection runs `onChange`. Handlers run in the run's instructions,
and a handler that does not end stops the run at its limit. `show()` returns the number given to `close(result)`
(0 when left out), 1 when the default button is clicked and 2 when the cancel button is clicked, and 0 for the
close box. The default or cancel button closes the dialog only when it has no `onClick` and no `click` handler of
its own and no `capture` handler on a container stopped the click; `click` handlers on the containers that do not
capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and
returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the
cancel button is `cancelElement`, else a button named or titled Cancel, in any case; a button found by its name or
title counts only while it is enabled and visible. A `show()` inside a handler while a dialog is showing, or of a
dialog that is showing, throws an `Error`. In the app, a `show()` inside a callback of a built-in function, a handler
that `notify` runs included, also throws an `Error`, and so do `alert`, `confirm`, `prompt` and the file dialogs called
from a handler; in a run with nobody to ask, such a `show()` takes a `window` answer, and `alert`, `confirm` and
`prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes.
`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of
text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws
too, and a slider's minimum above its maximum. When a getter changes a list's items or an item's text after the
list was read, or adds or removes a control after the controls were read, it reads the dialog again, and throws an
`Error` when the dialog changes again. It lays the controls out from each container's `orientation`,
`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that
is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its
container. A control whose `visible` is false, and every control in it, takes no room in the layout. Sizes and places
are kept within 8,192 pixels. These limits are VectorCraft's own.
In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button,
which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()`
returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another
control that Enter does not click. Escape clicks the
cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs,
asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. When a
handler takes the run past the growth limit, the question to continue opens over the dialog, and Continue shows the
dialog again with those events and the text typed in its fields. An event that waits for the script goes to the control
it was given to, and a typed text stays in its field, also after a handler adds controls before that one.
`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name, or
the text of a control without a name) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the
script the text still typed in the dialog's fields. When the dialog holds events the script has not taken yet, the
confirmed event goes after them. When one of those texts is longer than 16 KiB, the script gets
no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action`
return an error, and Escape shows it in the status bar. Such a text stays in its field when the field loses the
focus too, with the error in the status bar. A disabled or hidden control, a value out of a list's range, a
list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays
open.
A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is
`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a
control's `name`, or the text of a control without a name, and `value` is an edit field's text, a slider's number (kept in its range), or a
list's item index (a whole number, such as `2` or `2.0`) or `null`. The dialog takes the next step each time it
waits. The run ends with an error that the script cannot catch, and every document goes back, when no step is
left, when a step names a control the dialog does not have or that cannot take it, or when the dialog closes, or
an error in a handler ends `show()`, with steps it did not use.
```sh
vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}'
```
The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and
https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A
script reads files with them:
+1
View File
@@ -1155,6 +1155,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`).
- Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`).
- Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`.
- Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Palettes and other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`.
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
- Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse.
- Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).