mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Scripts: ScriptUI controls take size objects, event listeners, list find and remove, and Window.alert
- Every element starts with preferredSize, size, minimumSize and
maximumSize objects whose width and height are -1, so a script can
set one side, as in preferredSize.width = 100. A positive side of
size takes the place of preferredSize's, and the layout keeps a
control within its minimum and maximum.
- Controls and the dialog take addEventListener and
removeEventListener for click, change, changing and show. Handlers
run in the capture phase on the containers, on the control after its
onClick, onChange or onChanging, then on the containers again until
one calls stopPropagation(). A button with a click listener no longer
closes the dialog by itself.
- Window.alert, Window.confirm and Window.prompt open the same dialogs
as alert, confirm and prompt.
- A list has find(text) and remove(what), and takes its items in
properties.items; a container has remove(what).
- A group takes its creation properties as the third argument of add(),
and orientation, alignChildren, spacing, margins and alignment given
there are its first values.
- Setting a radio button's value to true turns off the radio buttons
added next to it in its container, and notify("onClick") turns a
radio button on and a check box over before onClick runs.
Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
b8c37560fe
commit
29153af625
8 files changed
+681
-68
No files matched your search
@@ -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|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, else its text)}] (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, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; 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,
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, else its text)}] (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, 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, windows and resource strings throw that they are not available yet); 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 acts as a click or change, addEventListener and removeEventListener take click, change, changing and show (other event types throw that they are not available yet), 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 result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; 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 l
Line truncated
|
||||
always,
|
||||
run
|
||||
),
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
//! 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` and `bounds` (left, top, right
|
||||
//! and bottom in its container). A control's size comes from its text, items and kind, by
|
||||
//! `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.
|
||||
@@ -145,6 +146,8 @@ pub struct UiNode {
|
||||
spacing: f32,
|
||||
margins: [f32; 4],
|
||||
size: [Option<f32>; 2],
|
||||
min_size: [Option<f32>; 2],
|
||||
max_size: [Option<f32>; 2],
|
||||
bounds: Option<UiRect>,
|
||||
}
|
||||
|
||||
@@ -482,7 +485,11 @@ pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
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) }
|
||||
});
|
||||
let size = numbers::<2>(field(f, "size"))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]);
|
||||
// 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,
|
||||
@@ -506,6 +513,8 @@ pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)),
|
||||
margins,
|
||||
size,
|
||||
min_size,
|
||||
max_size,
|
||||
bounds,
|
||||
});
|
||||
}
|
||||
@@ -578,6 +587,12 @@ fn layout(d: &mut ScriptUiDialog) {
|
||||
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];
|
||||
|
||||
@@ -316,6 +316,28 @@ fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() {
|
||||
assert!(w <= MAX_EXTENT && h <= MAX_EXTENT);
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
|
||||
#[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> {
|
||||
|
||||
@@ -44,8 +44,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// change anything outside it.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder Window alert confirm localize prompt toSource"),
|
||||
("Window.", "length prototype"),
|
||||
("Window.prototype.", "add center close constructor findElement hide show"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"),
|
||||
("Object.prototype.", "toSource"),
|
||||
("localize.", "length"),
|
||||
("toSource.", "length"),
|
||||
|
||||
+485
-45
@@ -9,8 +9,21 @@
|
||||
//! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item
|
||||
//! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum).
|
||||
//! The other documented control types throw an `Error` that says they are not available yet. A
|
||||
//! list's `add("item", text)` adds an item; its `selection` is an item or `null`, and takes an
|
||||
//! item, an index or `null`.
|
||||
//! group takes its creation properties as the third argument, and a list takes them there in place
|
||||
//! of its items, with the items in `properties.items`. A list's `add("item", text)` adds an item,
|
||||
//! `find(text)` finds one and `remove(what)` removes one; its `selection` is an item or `null`, and
|
||||
//! takes an item, an index or `null`. A container's `remove(what)` removes a control. Each element
|
||||
//! starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose `width` and
|
||||
//! `height` are -1, which leaves the size to the layout. Setting a radio button's `value` to true
|
||||
//! sets the other radio buttons next to it in its container to false, as a click does.
|
||||
//!
|
||||
//! `addEventListener(type, handler[, capture])` and `removeEventListener` register handlers for
|
||||
//! the events `show()` runs: `click`, `change`, `changing` and `show`. A handler gets an event
|
||||
//! object, in the capture phase on the containers above the control, then on the control after its
|
||||
//! `onClick`, `onChange` or `onChanging`, then in the bubbling phase on the containers again, until
|
||||
//! one calls `stopPropagation()`. `notify(event)` runs the same handlers, and `notify("onClick")`
|
||||
//! turns a check box over and turns a radio button on first. `Window.alert`, `Window.confirm` and
|
||||
//! `Window.prompt` are the global functions of those names, when the host defines them.
|
||||
//!
|
||||
//! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the
|
||||
//! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the
|
||||
@@ -33,8 +46,8 @@
|
||||
//! and a list that changes again throws an `Error`.
|
||||
|
||||
use crate::HostItem;
|
||||
use crate::builtins::{arg, constructor, method, native, pausable_method};
|
||||
use crate::heap::{Class, ENUMERABLE, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key};
|
||||
use crate::builtins::{arg, constructor, data, method, native, pausable_method};
|
||||
use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key};
|
||||
use crate::host::Data;
|
||||
use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause};
|
||||
use crate::value::{Value, index_key};
|
||||
@@ -66,6 +79,32 @@ const CLOSING: &str = "__vcClosing";
|
||||
const ITEMS: &str = "__vcItems";
|
||||
const SELECTION: &str = "__vcSelection";
|
||||
const LIST: &str = "__vcList";
|
||||
const VALUE: &str = "__vcValue";
|
||||
const LISTENERS: &str = "__vcListeners";
|
||||
const STOPPED: &str = "__vcStopped";
|
||||
const PREVENTED: &str = "__vcPrevented";
|
||||
|
||||
/// The size properties every element starts with, as objects with `width` and `height`.
|
||||
const SIZES: [&str; 4] = ["preferredSize", "size", "minimumSize", "maximumSize"];
|
||||
/// The events `addEventListener` takes, which `show()` and `notify` run.
|
||||
const EVENTS: [&str; 4] = ["click", "change", "changing", "show"];
|
||||
/// The other documented events, which nothing runs yet.
|
||||
const EVENTS_LATER: [&str; 14] = [
|
||||
"move",
|
||||
"moving",
|
||||
"resize",
|
||||
"resizing",
|
||||
"enterKey",
|
||||
"focus",
|
||||
"blur",
|
||||
"mousedown",
|
||||
"mouseup",
|
||||
"mousemove",
|
||||
"mouseover",
|
||||
"mouseout",
|
||||
"keyup",
|
||||
"keydown",
|
||||
];
|
||||
|
||||
/// The objects of `Window`, kept by the realm, and the dialog that is showing.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -73,17 +112,31 @@ pub(crate) struct Classes {
|
||||
window_proto: ObjId,
|
||||
control_proto: ObjId,
|
||||
item_proto: ObjId,
|
||||
event_proto: ObjId,
|
||||
layout: ObjId,
|
||||
host: ObjId,
|
||||
selection_get: ObjId,
|
||||
selection_set: ObjId,
|
||||
radio_get: ObjId,
|
||||
radio_set: ObjId,
|
||||
showing: Option<ObjId>,
|
||||
}
|
||||
|
||||
impl Classes {
|
||||
/// The objects a collection keeps.
|
||||
pub(crate) fn objects(&self) -> Vec<ObjId> {
|
||||
let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set];
|
||||
let mut all = vec![
|
||||
self.window_proto,
|
||||
self.control_proto,
|
||||
self.item_proto,
|
||||
self.event_proto,
|
||||
self.layout,
|
||||
self.host,
|
||||
self.selection_get,
|
||||
self.selection_set,
|
||||
self.radio_get,
|
||||
self.radio_set,
|
||||
];
|
||||
all.extend(self.showing);
|
||||
all
|
||||
}
|
||||
@@ -254,7 +307,12 @@ fn new_element(
|
||||
set_open(i, o, "bounds", bounds.clone())?;
|
||||
}
|
||||
set_open(i, o, "layout", Value::Object(layout))?;
|
||||
if matches!(kind, "dialog" | "group" | "panel") {
|
||||
for name in SIZES {
|
||||
let d = dimension(i, -1.0, -1.0)?;
|
||||
set_open(i, o, name, d)?;
|
||||
}
|
||||
let container = matches!(kind, "dialog" | "group" | "panel");
|
||||
if container {
|
||||
let kids = list(i, &[], false)?;
|
||||
set_slot(i, o, KIDS, Value::Object(kids))?;
|
||||
let children = list(i, &[], true)?;
|
||||
@@ -264,9 +322,28 @@ fn new_element(
|
||||
set_open(i, o, "spacing", Value::Number(10.0))?;
|
||||
set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?;
|
||||
}
|
||||
// Layout properties given with the creation properties start the element with those values.
|
||||
let layout_names: &[&str] = if container { &["alignment", "orientation", "alignChildren", "spacing", "margins"] } else { &["alignment"] };
|
||||
for name in layout_names {
|
||||
let v = i.get_value(&props, &key(name))?;
|
||||
if !matches!(v, Value::Undefined) {
|
||||
set_open(i, o, name, v)?;
|
||||
}
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// A new size object with `width` and `height`.
|
||||
fn dimension(i: &mut Interp, width: f64, height: f64) -> JsResult<Value> {
|
||||
i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(2)))?;
|
||||
let o = i.new_object();
|
||||
i.rooted(&[Value::Object(o)], |i| {
|
||||
set_open(i, o, "width", Value::Number(width))?;
|
||||
set_open(i, o, "height", Value::Number(height))?;
|
||||
Ok(Value::Object(o))
|
||||
})
|
||||
}
|
||||
|
||||
/// `new Window(type[, title, bounds, properties])`.
|
||||
fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let kind = i.to_str(&arg(args, 0))?.to_rust_string();
|
||||
@@ -330,19 +407,44 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
|
||||
if count as usize >= MAX_CONTROLS {
|
||||
return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls")));
|
||||
}
|
||||
let props = arg(args, 3);
|
||||
let list_kind = ty == "dropdownlist" || ty == "listbox";
|
||||
if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() {
|
||||
return Err(error(i, "add: a list box that selects several items is not available yet"));
|
||||
}
|
||||
let third = arg(args, 2);
|
||||
let is_array = |i: &Interp, v: &Value| -> JsResult<bool> {
|
||||
Ok(match v.as_object() {
|
||||
Some(a) => matches!(i.object(a)?.class, Class::Array { .. }),
|
||||
None => false,
|
||||
})
|
||||
};
|
||||
// A group takes its creation properties third, and so may a list in place of its items.
|
||||
let props_third = ty == "group" || (list_kind && third.as_object().is_some() && !is_array(i, &third)?);
|
||||
let props = if props_third { third.clone() } else { arg(args, 3) };
|
||||
let proto = classes(i)?.control_proto;
|
||||
let mark = i.temp_roots.len();
|
||||
let r = (|| {
|
||||
let mut given_items = if list_kind && !props_third { third.clone() } else { Value::Undefined };
|
||||
if list_kind && props.as_object().is_some() {
|
||||
let listed = i.get_value(&props, &key("items"))?;
|
||||
i.temp_roots.push(listed.clone());
|
||||
if !matches!(listed, Value::Undefined | Value::Null) {
|
||||
if !matches!(given_items, Value::Undefined | Value::Null) {
|
||||
return Err(i.type_error("add: give a list's items as the third argument or in properties.items, not both"));
|
||||
}
|
||||
given_items = listed;
|
||||
}
|
||||
}
|
||||
if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() {
|
||||
return Err(error(i, "add: a list box that selects several items is not available yet"));
|
||||
}
|
||||
let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() };
|
||||
let text = if list_kind || matches!(ty, "slider" | "progressbar") { Value::Undefined } else { arg(args, 2) };
|
||||
let text = if list_kind || matches!(ty, "group" | "slider" | "progressbar") { Value::Undefined } else { third.clone() };
|
||||
let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?;
|
||||
match ty {
|
||||
"checkbox" | "radiobutton" => set_open(i, c, "value", Value::Bool(false))?,
|
||||
"checkbox" => set_open(i, c, "value", Value::Bool(false))?,
|
||||
"radiobutton" => {
|
||||
set_slot(i, c, VALUE, Value::Bool(false))?;
|
||||
let cl = classes(i)?;
|
||||
i.define(c, key("value"), Prop::Accessor { get: Some(cl.radio_get), set: Some(cl.radio_set), flags: ENUMERABLE })?;
|
||||
}
|
||||
"slider" | "progressbar" => {
|
||||
let (value, min, max) =
|
||||
if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) };
|
||||
@@ -368,7 +470,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
|
||||
// A new list's items take their places in the dialog only once the list is added.
|
||||
let mut staged = 0usize;
|
||||
if list_kind {
|
||||
match arg(args, 2) {
|
||||
match given_items.clone() {
|
||||
Value::Undefined | Value::Null => {}
|
||||
Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => {
|
||||
let length = match &i.object(a)?.class {
|
||||
@@ -566,7 +668,202 @@ fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult<Option<Value>> {
|
||||
i.call(&f, &Value::Object(o), &[]).map(Some)
|
||||
}
|
||||
|
||||
/// `notify([event])`: runs the control's `onClick`, `onChange` or `onChanging`.
|
||||
/// The radio buttons that form a set with `c`: it and the radio buttons next to it in its
|
||||
/// container, up to the first control of another kind on each side.
|
||||
fn radio_set_of(i: &Interp, c: ObjId) -> JsResult<Vec<ObjId>> {
|
||||
let Some(parent) = object_slot(i, c, PARENT)? else { return Ok(vec![c]) };
|
||||
let kids = kids_of(i, parent)?;
|
||||
let Some(at) = kids.iter().position(|k| same(k, &Value::Object(c))) else { return Ok(vec![c]) };
|
||||
let radio = |v: &Value| -> JsResult<Option<ObjId>> {
|
||||
Ok(match kind_of(i, v)? {
|
||||
Some((o, k)) if k == "radiobutton" => Some(o),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
let mut set = vec![c];
|
||||
for k in kids[..at].iter().rev() {
|
||||
let Some(o) = radio(k)? else { break };
|
||||
set.push(o);
|
||||
}
|
||||
for k in &kids[at + 1..] {
|
||||
let Some(o) = radio(k)? else { break };
|
||||
set.push(o);
|
||||
}
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
fn radio_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = element(i, &this, "value")?;
|
||||
Ok(Value::Bool(slot(i, o, VALUE)?.truthy()))
|
||||
}
|
||||
|
||||
/// A radio button's `value`: true turns the other radio buttons of its set off.
|
||||
fn radio_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = element(i, &this, "value")?;
|
||||
let on = arg(args, 0).truthy();
|
||||
if on {
|
||||
for other in radio_set_of(i, o)? {
|
||||
if other != o {
|
||||
set_slot(i, other, VALUE, Value::Bool(false))?;
|
||||
}
|
||||
}
|
||||
}
|
||||
set_slot(i, o, VALUE, Value::Bool(on))?;
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// The listeners registered on `o`: each event type, handler and capture flag.
|
||||
fn listeners_of(i: &Interp, o: ObjId) -> JsResult<Vec<(Value, Value, bool)>> {
|
||||
let flat = match object_slot(i, o, LISTENERS)? {
|
||||
Some(a) => list_values(i, a)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
Ok(flat.as_chunks::<3>().0.iter().map(|[t, f, c]| (t.clone(), f.clone(), c.truthy())).collect())
|
||||
}
|
||||
|
||||
fn set_listeners(i: &mut Interp, o: ObjId, all: &[(Value, Value, bool)]) -> JsResult<()> {
|
||||
let flat: Vec<Value> = all.iter().flat_map(|(t, f, c)| [t.clone(), f.clone(), Value::Bool(*c)]).collect();
|
||||
i.rooted(&flat.clone(), |i| {
|
||||
let kept = list(i, &flat, false)?;
|
||||
set_slot(i, o, LISTENERS, Value::Object(kept))
|
||||
})
|
||||
}
|
||||
|
||||
/// Is the stored event type `t` the type `ty`?
|
||||
fn is_type(t: &Value, ty: &str) -> bool {
|
||||
matches!(t, Value::String(s) if s.to_rust_string() == ty)
|
||||
}
|
||||
|
||||
/// The event type `addEventListener` and `removeEventListener` were given, checked.
|
||||
fn event_type(i: &mut Interp, v: &Value, what: &str) -> JsResult<&'static str> {
|
||||
let text = i.to_str(v)?.to_rust_string();
|
||||
if let Some(name) = EVENTS.iter().find(|e| **e == text) {
|
||||
return Ok(name);
|
||||
}
|
||||
if EVENTS_LATER.contains(&text.as_str()) {
|
||||
return Err(error(i, &format!("{what}: the event {text} is not available yet")));
|
||||
}
|
||||
Err(error(i, &format!("{what}: there is no event {}", text.chars().take(64).collect::<String>())))
|
||||
}
|
||||
|
||||
/// `addEventListener(type, handler[, capture])`.
|
||||
fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = element(i, &this, "addEventListener")?;
|
||||
let ty = event_type(i, &arg(args, 0), "addEventListener")?;
|
||||
let f = arg(args, 1);
|
||||
if !i.is_callable(&f) {
|
||||
return Err(i.type_error("addEventListener: give the handler as a function"));
|
||||
}
|
||||
let capture = arg(args, 2).truthy();
|
||||
let mut all = listeners_of(i, o)?;
|
||||
if !all.iter().any(|(t, g, c)| is_type(t, ty) && same(g, &f) && *c == capture) {
|
||||
all.push((Value::str(ty), f, capture));
|
||||
set_listeners(i, o, &all)?;
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// `removeEventListener(type, handler[, capture])`.
|
||||
fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, _) = element(i, &this, "removeEventListener")?;
|
||||
let ty = event_type(i, &arg(args, 0), "removeEventListener")?;
|
||||
let f = arg(args, 1);
|
||||
let capture = arg(args, 2).truthy();
|
||||
let mut all = listeners_of(i, o)?;
|
||||
let before = all.len();
|
||||
all.retain(|(t, g, c)| !(is_type(t, ty) && same(g, &f) && *c == capture));
|
||||
if all.len() != before {
|
||||
set_listeners(i, o, &all)?;
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
if let Some(o) = this.as_object() {
|
||||
set_slot(i, o, STOPPED, Value::Bool(true))?;
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
fn event_prevent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult<Value> {
|
||||
if let Some(o) = this.as_object() {
|
||||
set_slot(i, o, PREVENTED, Value::Bool(true))?;
|
||||
}
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// Runs the listeners for `ty` on `at` (only those for `capture` unless it is `None`), with `event`.
|
||||
fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option<bool>, event: ObjId, phase: f64) -> JsResult<bool> {
|
||||
let wanted: Vec<Value> =
|
||||
listeners_of(i, at)?.into_iter().filter(|(t, _, c)| is_type(t, ty) && capture.is_none_or(|want| *c == want)).map(|(_, f, _)| f).collect();
|
||||
if wanted.is_empty() {
|
||||
return Ok(false);
|
||||
}
|
||||
i.rooted(&wanted.clone(), |i| {
|
||||
set_open(i, event, "currentTarget", Value::Object(at))?;
|
||||
set_open(i, event, "eventPhase", Value::Number(phase))?;
|
||||
for f in &wanted {
|
||||
i.call(f, &Value::Object(at), &[Value::Object(event)])?;
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs the event `ty` on the element `target`: the listeners of the containers above it that
|
||||
/// capture, its `callback`, its own listeners, then the listeners of the containers that do not
|
||||
/// capture, until one stops it. → whether the element had a callback or a listener for it.
|
||||
fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult<bool> {
|
||||
let mut above = Vec::new();
|
||||
let mut at = object_slot(i, target, PARENT)?;
|
||||
while let Some(p) = at {
|
||||
i.use_fuel()?;
|
||||
above.push(p);
|
||||
at = object_slot(i, p, PARENT)?;
|
||||
}
|
||||
let proto = classes(i)?.event_proto;
|
||||
i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?;
|
||||
let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto)));
|
||||
i.rooted(&[Value::Object(event)], |i| {
|
||||
let bubbles = ty != "show";
|
||||
set_open(i, event, "type", Value::str(ty))?;
|
||||
set_open(i, event, "target", Value::Object(target))?;
|
||||
set_open(i, event, "bubbles", Value::Bool(bubbles))?;
|
||||
set_open(i, event, "cancelable", Value::Bool(false))?;
|
||||
set_open(i, event, "detail", Value::Number(if ty == "click" { 1.0 } else { 0.0 }))?;
|
||||
let stopped = |i: &Interp| -> JsResult<bool> { Ok(slot(i, event, STOPPED)?.truthy()) };
|
||||
for p in above.iter().rev() {
|
||||
run_listeners(i, *p, ty, Some(true), event, 1.0)?;
|
||||
if stopped(i)? {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
let had = handler(i, target, callback)?.is_some();
|
||||
let heard = run_listeners(i, target, ty, None, event, 2.0)?;
|
||||
if bubbles && !stopped(i)? {
|
||||
for p in &above {
|
||||
run_listeners(i, *p, ty, Some(false), event, 3.0)?;
|
||||
if stopped(i)? {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(had || heard)
|
||||
})
|
||||
}
|
||||
|
||||
/// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then
|
||||
/// the click runs. → whether the control had a callback or a listener for it.
|
||||
fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult<bool> {
|
||||
if kind == "checkbox" {
|
||||
let on = i.get_value(&Value::Object(c), &key("value"))?.truthy();
|
||||
i.put(c, key("value"), Value::Bool(!on), true)?;
|
||||
} else if kind == "radiobutton" {
|
||||
i.put(c, key("value"), Value::Bool(true), true)?;
|
||||
}
|
||||
dispatch(i, c, "click", "onClick")
|
||||
}
|
||||
|
||||
/// `notify([event])`: simulates the control's `onClick`, `onChange` or `onChanging`.
|
||||
fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, kind) = element(i, &this, "notify")?;
|
||||
let event = match arg(args, 0) {
|
||||
@@ -574,10 +871,112 @@ fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Valu
|
||||
Value::Undefined => "onChange".to_string(),
|
||||
v => i.to_str(&v)?.to_rust_string(),
|
||||
};
|
||||
if !matches!(event.as_str(), "onClick" | "onChange" | "onChanging") {
|
||||
return Err(error(i, "notify: give onClick, onChange or onChanging"));
|
||||
match event.as_str() {
|
||||
"onClick" => click_control(i, o, &kind)?,
|
||||
"onChange" => dispatch(i, o, "change", "onChange")?,
|
||||
"onChanging" => dispatch(i, o, "changing", "onChanging")?,
|
||||
_ => return Err(error(i, "notify: give onClick, onChange or onChanging")),
|
||||
};
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
/// The index in `values` that `what` names: an index, one of the values, or a text that an
|
||||
/// element's `text` equals. A text is converted before the values are read.
|
||||
fn index_named(i: &mut Interp, what: &Value, values: impl Fn(&Interp) -> JsResult<Vec<Value>>) -> JsResult<(Vec<Value>, Option<usize>)> {
|
||||
match what {
|
||||
Value::Number(n) => {
|
||||
let all = values(i)?;
|
||||
let at = (*n >= 0.0 && n.fract() == 0.0 && (*n as usize) < all.len()).then_some(*n as usize);
|
||||
Ok((all, at))
|
||||
}
|
||||
Value::Object(_) => {
|
||||
let all = values(i)?;
|
||||
let at = all.iter().position(|v| same(v, what));
|
||||
Ok((all, at))
|
||||
}
|
||||
v => {
|
||||
let want = i.to_str(v)?;
|
||||
let all = values(i)?;
|
||||
i.rooted(&all.clone(), |i| {
|
||||
for (n, item) in all.iter().enumerate() {
|
||||
i.use_fuel()?;
|
||||
let t = i.get_value(item, &key("text"))?;
|
||||
if matches!(&t, Value::String(s) if *s == want) {
|
||||
return Ok((all.clone(), Some(n)));
|
||||
}
|
||||
}
|
||||
Ok((all.clone(), None))
|
||||
})
|
||||
}
|
||||
}
|
||||
handler(i, o, &event)?;
|
||||
}
|
||||
|
||||
/// `list.find(text)`: the first item whose text is `text`, or `null`.
|
||||
fn find(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let o = list_of(i, &this, "find")?;
|
||||
let text = Value::String(i.to_str(&arg(args, 0))?);
|
||||
let (items, at) = index_named(i, &text, |i| items_of(i, o))?;
|
||||
Ok(at.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
/// The controls in `c` and in the containers it holds, `c` included, and their list items.
|
||||
fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> {
|
||||
let (mut controls, mut items) = (0.0, 0.0);
|
||||
let mut stack = vec![c.clone()];
|
||||
while let Some(v) = stack.pop() {
|
||||
i.use_fuel()?;
|
||||
let Some(o) = v.as_object() else { continue };
|
||||
controls += 1.0;
|
||||
items += items_of(i, o)?.len() as f64;
|
||||
stack.extend(kids_of(i, o)?);
|
||||
}
|
||||
Ok((controls, items))
|
||||
}
|
||||
|
||||
/// `remove(what)`: removes a list's item, or a container's control, given by its index, the
|
||||
/// object itself or its text. Nothing happens when there is no such item or control.
|
||||
fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
|
||||
let (o, kind) = element(i, &this, "remove")?;
|
||||
let what = arg(args, 0);
|
||||
let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("an element without its window".into())) };
|
||||
if kind == "dropdownlist" || kind == "listbox" {
|
||||
let (mut items, at) = index_named(i, &what, |i| items_of(i, o))?;
|
||||
let Some(at) = at else { return Ok(Value::Undefined) };
|
||||
items.remove(at);
|
||||
i.rooted(&items.clone(), |i| {
|
||||
let kept = list(i, &items, false)?;
|
||||
set_slot(i, o, ITEMS, Value::Object(kept))?;
|
||||
let copy = list(i, &items, true)?;
|
||||
set_open(i, o, "items", Value::Object(copy))
|
||||
})?;
|
||||
let count = number_slot(i, win, ITEM_COUNT)?;
|
||||
set_slot(i, win, ITEM_COUNT, Value::Number((count - 1.0).max(0.0)))?;
|
||||
match selection_index(i, o)? {
|
||||
Some(n) if n == at => set_slot(i, o, SELECTION, Value::Number(-1.0))?,
|
||||
Some(n) if n > at => set_slot(i, o, SELECTION, Value::Number((n - 1) as f64))?,
|
||||
_ => {}
|
||||
}
|
||||
return Ok(Value::Undefined);
|
||||
}
|
||||
if !matches!(kind.as_str(), "dialog" | "group" | "panel") {
|
||||
return Err(error(i, &format!("remove: a {kind} holds no controls or items")));
|
||||
}
|
||||
let (mut kids, at) = index_named(i, &what, |i| kids_of(i, o))?;
|
||||
let Some(at) = at else { return Ok(Value::Undefined) };
|
||||
let gone = kids.remove(at);
|
||||
i.rooted(std::slice::from_ref(&gone), |i| {
|
||||
i.rooted(&kids.clone(), |i| {
|
||||
let kept = list(i, &kids, false)?;
|
||||
set_slot(i, o, KIDS, Value::Object(kept))?;
|
||||
let copy = list(i, &kids, true)?;
|
||||
set_open(i, o, "children", Value::Object(copy))
|
||||
})?;
|
||||
let (controls, items) = subtree_counts(i, &gone)?;
|
||||
let count = number_slot(i, win, COUNT)?;
|
||||
set_slot(i, win, COUNT, Value::Number((count - controls).max(0.0)))?;
|
||||
let total = number_slot(i, win, ITEM_COUNT)?;
|
||||
set_slot(i, win, ITEM_COUNT, Value::Number((total - items).max(0.0)))
|
||||
})?;
|
||||
Ok(Value::Undefined)
|
||||
}
|
||||
|
||||
@@ -723,7 +1122,7 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu
|
||||
fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult<Value> {
|
||||
guarded(i, keep, |i| {
|
||||
let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) };
|
||||
handler(i, win, "onShow")?;
|
||||
dispatch(i, win, "show", "onShow")?;
|
||||
next(i, win)
|
||||
})
|
||||
}
|
||||
@@ -756,22 +1155,7 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult<Value> {
|
||||
let value = slot(i, ev, "value")?;
|
||||
match event.as_str() {
|
||||
"click" => {
|
||||
if kind == "checkbox" {
|
||||
let on = i.get_value(&Value::Object(c), &key("value"))?.truthy();
|
||||
i.put(c, key("value"), Value::Bool(!on), true)?;
|
||||
} else if kind == "radiobutton" {
|
||||
let parent = object_slot(i, c, PARENT)?;
|
||||
for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() {
|
||||
if !same(&other, &Value::Object(c))
|
||||
&& let Some((o, k)) = kind_of(i, &other)?
|
||||
&& k == "radiobutton"
|
||||
{
|
||||
i.put(o, key("value"), Value::Bool(false), true)?;
|
||||
}
|
||||
}
|
||||
i.put(c, key("value"), Value::Bool(true), true)?;
|
||||
}
|
||||
if handler(i, c, "onClick")?.is_none() && kind == "button" {
|
||||
if !click_control(i, c, &kind)? && kind == "button" {
|
||||
let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64);
|
||||
if is(2) {
|
||||
set_slot(i, win, CLOSING, Value::Number(1.0))?;
|
||||
@@ -784,11 +1168,11 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult<Value> {
|
||||
match kind.as_str() {
|
||||
"edittext" => {
|
||||
i.put(c, key("text"), value, true)?;
|
||||
handler(i, c, "onChanging")?;
|
||||
dispatch(i, c, "changing", "onChanging")?;
|
||||
}
|
||||
"slider" => {
|
||||
i.put(c, key("value"), value, true)?;
|
||||
handler(i, c, "onChanging")?;
|
||||
dispatch(i, c, "changing", "onChanging")?;
|
||||
}
|
||||
_ => {
|
||||
let n = match value {
|
||||
@@ -806,7 +1190,7 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult<Value> {
|
||||
set_slot(i, c, SELECTION, Value::Number(n))?;
|
||||
}
|
||||
}
|
||||
handler(i, c, "onChange")?;
|
||||
dispatch(i, c, "change", "onChange")?;
|
||||
}
|
||||
_ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))),
|
||||
}
|
||||
@@ -889,6 +1273,21 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult<Data> {
|
||||
numbers(i, v, &["left", "top", "right", "bottom"], "bounds")
|
||||
}
|
||||
|
||||
/// `base`'s width and height, each replaced by `over`'s when that is above 0.
|
||||
fn overridden(base: Data, over: Data) -> Data {
|
||||
let Data::Array(over) = over else { return base };
|
||||
let mut out = match base {
|
||||
Data::Array(b) => b,
|
||||
_ => vec![Data::Number(-1.0), Data::Number(-1.0)],
|
||||
};
|
||||
for (o, v) in out.iter_mut().zip(over) {
|
||||
if matches!(v, Data::Number(n) if n > 0.0) {
|
||||
*o = v;
|
||||
}
|
||||
}
|
||||
Data::Array(out)
|
||||
}
|
||||
|
||||
fn margins(i: &mut Interp, v: &Value) -> JsResult<Data> {
|
||||
if v.as_object().is_some() {
|
||||
return numbers(i, v, &["left", "top", "right", "bottom"], "margins");
|
||||
@@ -977,8 +1376,16 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<Option<Described>> {
|
||||
// A value a getter gives is kept from collection while its own properties are read.
|
||||
let b = get_kept(i, o, "bounds")?;
|
||||
d.push(("bounds".into(), bounds(i, &b)?));
|
||||
let size = get_kept(i, o, "preferredSize")?;
|
||||
d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?));
|
||||
// `size` set to a positive width or height takes the place of `preferredSize`'s.
|
||||
let preferred = get_kept(i, o, "preferredSize")?;
|
||||
let preferred = numbers(i, &preferred, &["width", "height"], "preferredSize")?;
|
||||
let set = get_kept(i, o, "size")?;
|
||||
let set = numbers(i, &set, &["width", "height"], "size")?;
|
||||
d.push(("size".into(), overridden(preferred, set)));
|
||||
for (name, field) in [("minimumSize", "min"), ("maximumSize", "max")] {
|
||||
let v = get_kept(i, o, name)?;
|
||||
d.push((field.into(), numbers(i, &v, &["width", "height"], name)?));
|
||||
}
|
||||
let a = get_kept(i, o, "alignment")?;
|
||||
d.push(("alignment".into(), alignment(i, &a)?));
|
||||
if matches!(kind.as_str(), "dialog" | "group" | "panel") {
|
||||
@@ -1066,7 +1473,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul
|
||||
let host = i.host_object("Window", items)?;
|
||||
let object_proto = i.intrinsics.object_proto;
|
||||
i.rooted(&[Value::Object(host)], |i| {
|
||||
i.reserve_heap(OBJECT_BYTES.saturating_mul(4))?;
|
||||
i.reserve_heap(OBJECT_BYTES.saturating_mul(5))?;
|
||||
let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
|
||||
i.temp_roots.push(Value::Object(window_proto));
|
||||
let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
|
||||
@@ -1079,21 +1486,54 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul
|
||||
i.temp_roots.push(Value::Object(selection_get));
|
||||
let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?;
|
||||
i.temp_roots.push(Value::Object(selection_set));
|
||||
i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None });
|
||||
let event_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto)));
|
||||
i.temp_roots.push(Value::Object(event_proto));
|
||||
let radio_get = native(i, "value", radio_get, 0, NativeKind::Plain, false)?;
|
||||
i.temp_roots.push(Value::Object(radio_get));
|
||||
let radio_set = native(i, "value", radio_set, 1, NativeKind::Plain, false)?;
|
||||
i.temp_roots.push(Value::Object(radio_set));
|
||||
i.script_ui = Some(Classes {
|
||||
window_proto,
|
||||
control_proto,
|
||||
item_proto,
|
||||
event_proto,
|
||||
layout,
|
||||
host,
|
||||
selection_get,
|
||||
selection_set,
|
||||
radio_get,
|
||||
radio_set,
|
||||
showing: None,
|
||||
});
|
||||
let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?;
|
||||
constructor(i, "Window", window, window_proto)?;
|
||||
method(i, window_proto, "add", add, 4)?;
|
||||
method(i, window_proto, "findElement", find_element, 1)?;
|
||||
// `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions.
|
||||
let global = i.global;
|
||||
for name in ["alert", "confirm", "prompt"] {
|
||||
if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))?
|
||||
&& i.is_callable(&value)
|
||||
{
|
||||
data(i, window, name, value, HIDDEN)?;
|
||||
}
|
||||
}
|
||||
for proto in [window_proto, control_proto] {
|
||||
method(i, proto, "add", add, 4)?;
|
||||
method(i, proto, "findElement", find_element, 1)?;
|
||||
method(i, proto, "remove", remove, 1)?;
|
||||
method(i, proto, "addEventListener", add_event_listener, 3)?;
|
||||
method(i, proto, "removeEventListener", remove_event_listener, 3)?;
|
||||
}
|
||||
method(i, window_proto, "close", close, 1)?;
|
||||
method(i, window_proto, "hide", hide, 0)?;
|
||||
method(i, window_proto, "center", nothing, 1)?;
|
||||
pausable_method(i, window_proto, "show", show, 0)?;
|
||||
method(i, control_proto, "add", add, 4)?;
|
||||
method(i, control_proto, "findElement", find_element, 1)?;
|
||||
method(i, control_proto, "removeAll", remove_all, 0)?;
|
||||
method(i, control_proto, "find", find, 1)?;
|
||||
method(i, control_proto, "notify", notify, 1)?;
|
||||
method(i, control_proto, "show", control_show, 0)?;
|
||||
method(i, control_proto, "hide", control_hide, 0)?;
|
||||
method(i, event_proto, "stopPropagation", event_stop, 0)?;
|
||||
method(i, event_proto, "preventDefault", event_prevent, 0)?;
|
||||
method(i, item_proto, "toString", item_to_string, 0)?;
|
||||
let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?;
|
||||
i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?;
|
||||
|
||||
@@ -385,3 +385,112 @@ fn findelement_items_and_selection_follow_the_list() {
|
||||
.unwrap();
|
||||
assert_eq!(v, JsValue::String("true,b,,,0,b".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_control_s_sizes_can_be_set_a_side_at_a_time_and_reach_the_description() {
|
||||
let (mut r, seen, _) = realm(vec![click(1)]);
|
||||
let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \
|
||||
b.preferredSize.width = 100; b.minimumSize.height = 30; b.maximumSize.width = 90; w.size.height = 200; w.show()";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0));
|
||||
let seen = seen.borrow();
|
||||
let first = nodes(&seen.descriptions[0]);
|
||||
let numbers = |v: &[f64]| Data::Array(v.iter().map(|n| Data::Number(*n)).collect());
|
||||
assert_eq!(field(&first[1], "size"), &numbers(&[100.0, -1.0]), "the side left alone stays to the layout");
|
||||
assert_eq!(field(&first[1], "min"), &numbers(&[-1.0, 30.0]));
|
||||
assert_eq!(field(&first[1], "max"), &numbers(&[90.0, -1.0]));
|
||||
assert_eq!(field(&first[0], "size"), &numbers(&[-1.0, 200.0]), "size takes the place of preferredSize");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listeners_run_in_the_capture_target_and_bubbling_phases_until_one_stops() {
|
||||
let (mut r, _, _) = realm(vec![click(2)]);
|
||||
let source = "var w = new Window('dialog'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var log = []; \
|
||||
w.addEventListener('click', function (e) { log.push('capture ' + e.eventPhase); }, true); \
|
||||
b.onClick = function () { log.push('onClick'); }; \
|
||||
b.addEventListener('click', function (e) { log.push(e.type + ' ' + (e.target === b) + ' ' + (this === b)); }); \
|
||||
g.addEventListener('click', function (e) { log.push('group ' + (e.currentTarget === g)); }); \
|
||||
w.addEventListener('click', function () { log.push('dialog'); w.close(3); }); \
|
||||
[w.show(), log.join()].join('|')";
|
||||
assert_eq!(r.run(source).unwrap(), JsValue::String("3|capture 1,onClick,click true true,group true,dialog".into()));
|
||||
let (mut r, _, _) = realm(vec![click(1), close(), click(1), close()]);
|
||||
let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); var log = []; \
|
||||
function count() { log.push('count'); } b.addEventListener('click', count); b.addEventListener('click', count); \
|
||||
b.addEventListener('click', function (e) { e.stopPropagation(); }); \
|
||||
w.addEventListener('click', function () { log.push('dialog'); }); \
|
||||
w.addEventListener('show', function (e) { log.push('show ' + e.bubbles); }); \
|
||||
var first = w.show(); b.removeEventListener('click', count); var second = w.show(); [first, second, log.join()].join('|')";
|
||||
assert_eq!(
|
||||
r.run(source).unwrap(),
|
||||
JsValue::String("0|0|show false,count,show false".into()),
|
||||
"a button with a click listener does not close the dialog by itself, and the same listener is added once"
|
||||
);
|
||||
for (source, want) in [
|
||||
("new Window('dialog').addEventListener('mouseover', function () {})", "addEventListener: the event mouseover is not available yet"),
|
||||
("new Window('dialog').addEventListener('wobble', function () {})", "addEventListener: there is no event wobble"),
|
||||
("new Window('dialog').addEventListener('click', 'code')", "addEventListener: give the handler as a function"),
|
||||
] {
|
||||
let (mut r, _, _) = realm(Vec::new());
|
||||
let e = r.run(&format!("try {{ {source}; 'added' }} catch (e) {{ e.message }}")).unwrap();
|
||||
assert_eq!(e, JsValue::String(want.into()), "{source}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_find_and_remove_items_and_take_their_items_in_the_creation_properties() {
|
||||
let (mut r, _, _) = realm(Vec::new());
|
||||
let v = r
|
||||
.run(
|
||||
"var w = new Window('dialog'); var d = w.add('dropdownlist', undefined, undefined, {items: ['a', 'b', 'c']}); \
|
||||
var x = w.add('listbox', undefined, {items: ['x'], name: 'xs'}); \
|
||||
d.selection = 2; var b = d.find('b'); d.remove('b'); d.remove(0); d.remove('zzz'); d.remove(7); \
|
||||
[d.items.length, d.items[0].text, d.selection.text, b.index, d.find('q'), x.items[0].text, x.name].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(v, JsValue::String("1,c,c,-1,,x,xs".into()));
|
||||
let both = r.run("try { new Window('dialog').add('listbox', undefined, ['a'], {items: ['b']}); 'made' } catch (e) { e.name }").unwrap();
|
||||
assert_eq!(both, JsValue::String("TypeError".into()));
|
||||
let freed = r
|
||||
.run(
|
||||
"var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1024; n++) l.add('item', 'i'); \
|
||||
l.remove(0); l.add('item', 'again'); var g = w.add('group'); g.add('button', undefined, 'A'); g.add('button', undefined, 'B'); \
|
||||
g.remove('A'); g.remove(g.children[0]); w.remove(l); var m = w.add('listbox'); \
|
||||
for (var k = 0; k < 1024; k++) m.add('item', 'j'); for (var i = 0; i < 510; i++) w.add('button'); \
|
||||
[g.children.length, w.children.length, m.items.length].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(freed, JsValue::String("0,512,1024".into()), "a removed item or control frees its place");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_takes_its_creation_properties_third() {
|
||||
let (mut r, seen, _) = realm(vec![close()]);
|
||||
let v = r
|
||||
.run(
|
||||
"var w = new Window('dialog'); var g = w.add('group', undefined, {orientation: 'column', alignChildren: 'left', name: 'g'}); \
|
||||
var p = w.add('panel', undefined, 'Title', {margins: 4}); w.show(); [g.orientation, g.alignChildren, g.name, g.text, p.text, p.margins].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(v, JsValue::String("column,left,g,,Title,4".into()));
|
||||
let seen = seen.borrow();
|
||||
assert_eq!(field(&nodes(&seen.descriptions[0])[1], "orientation"), &Data::String("column".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_radio_button_turned_on_turns_off_the_others_of_its_set() {
|
||||
let (mut r, _, _) = realm(Vec::new());
|
||||
let v = r
|
||||
.run(
|
||||
"var w = new Window('dialog'); var r1 = w.add('radiobutton', undefined, 'A'); var r2 = w.add('radiobutton', undefined, 'B'); \
|
||||
var r3 = w.add('radiobutton', undefined, 'C'); w.add('statictext', undefined, 'Other'); var r4 = w.add('radiobutton', undefined, 'D'); \
|
||||
var c = w.add('checkbox', undefined, 'E'); var clicks = 0; r3.onClick = function () { clicks++; }; \
|
||||
r1.value = true; r2.value = true; var set = [r1.value, r2.value, r3.value]; r4.value = true; \
|
||||
r3.notify('onClick'); r3.notify(); c.notify('onClick'); \
|
||||
set.concat([r1.value, r2.value, r3.value, r4.value, c.value, clicks]).join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
v,
|
||||
JsValue::String("false,true,false,false,false,true,true,true,2".into()),
|
||||
"a radio button after another kind of control starts a new set"
|
||||
);
|
||||
}
|
||||
+43
-16
@@ -2908,26 +2908,52 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s
|
||||
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 `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.
|
||||
- A list's `add("item", text)` adds an item, `removeAll()` removes them, `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`, `alignment`, `parent`,
|
||||
`window`, `show()` and `hide()`. 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) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`,
|
||||
`close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing.
|
||||
minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes
|
||||
`properties` right after `bounds`, and a list may take `properties` there 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.
|
||||
- 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. 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")` act as the person's click or change would:
|
||||
a click turns a check box over and turns a radio button on, then runs `onClick` and the `click` listeners.
|
||||
`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; a function registered twice for the same type and
|
||||
phase runs once. A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`,
|
||||
`detail` (1 for a click), `stopPropagation()` and `preventDefault()`. 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()`;
|
||||
`show` runs only on the dialog. 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 waits for the person. A click runs the control's `onClick`; a check
|
||||
box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An
|
||||
`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, while they have no `onClick`, and 0 for the close box. `onClose` runs before the dialog
|
||||
cancel button is clicked, while they have no `onClick` and no `click` handler of their own, and 0 for the close box. `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 `show()` inside
|
||||
a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in
|
||||
@@ -2937,8 +2963,9 @@ function. A shown dialog can be shown again after it closes.
|
||||
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 after the list was read, it
|
||||
reads the dialog again, and throws an `Error` when a list changes again. It lays the controls out from each container's `orientation`,
|
||||
`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places
|
||||
it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own.
|
||||
`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. 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()`
|
||||
|
||||
@@ -1066,7 +1066,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, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings 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`.
|
||||
- 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, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button. Controls also take `addEventListener` for clicks, changes and `show`, `notify`, size objects a script can set one side of, and lists' `find` and `remove`, and `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. Palettes, other control types and resource strings 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`).
|
||||
|
||||
Reference in new issue
Block a user