Scripts: ScriptUI dialogs refuse look-alike containers, noecho fields and stale descriptions

- An answer step with an empty control matches only an unnamed control whose
  text is empty, not the first unnamed control.
- add() and add("item") on an object made to look like a container or list
  throw a TypeError and charge nothing to the dialog's limits.
- A new list's initial items are read through ordinary property access, so an
  index getter gives its value.
- findElement() keeps the controls it has still to look at rooted while a
  name getter runs, and skips a control the element no longer holds.
- A close() that onClose calls before it returns false belongs to the close it
  refuses; the dialog waits for the next event.
- show() throws for an edittext with noecho before the dialog opens.
- show() reads the dialog again when a getter adds or removes a control after
  the controls were read, and throws when it changes again.
- An edit field takes at most 32,768 characters while it is typed.
This commit is contained in:
dotCooCoo committed 2026-11-25 14:41:28 -08:00
1 parent 3ede7a59f4
commit 9dc197b4e4
7 files changed
+200 -32

No files matched your search

+1 -1
View File
@@ -198,7 +198,7 @@ impl ScriptUiDialog {
/// whose text is `control`.
pub fn find(&self, control: &str) -> Option<usize> {
let by = |name: bool| {
let hit = |n: &UiNode| if name { n.name == control } else { n.name.is_empty() && n.text == control };
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))
@@ -131,6 +131,13 @@ fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() {
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]
+90 -25
View File
@@ -8,7 +8,8 @@
//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`,
//! `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
//! The other documented control types throw an `Error` that says they are not available yet, and
//! `show()` throws one for an `edittext` whose `properties` have `noecho`. A
//! group takes its creation properties as the third argument (or the fourth when the third is not
//! an object), 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
@@ -52,8 +53,9 @@
//! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`]
//! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a
//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These and [`MAX_LISTENERS`] are
//! VectorCraft's own limits. A getter that changes a list's items after the list was read makes
//! `show()` read the dialog again, and a list that changes again throws an `Error`. A `text` getter
//! VectorCraft's own limits. A getter that changes a list's items after the list was read, or adds
//! or removes a control after the dialog's controls were read, makes `show()` read the dialog
//! again, and a dialog that changes again throws an `Error`. A `text` getter
//! that changes a list or a container while `remove(text)` looks for an item or a control makes
//! `remove` throw an `Error`.
@@ -557,10 +559,12 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
if length > MAX_ITEMS.saturating_sub(number_slot(i, win, ITEM_COUNT)? as usize) {
return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all")));
}
let values = list_values(i, a)?;
i.temp_roots.extend(values.iter().cloned());
for item in &values {
let text = text_arg(i, item)?;
// Each item is read as a script reads it, so an index getter gives its value.
for n in 0..length {
let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?;
let item = i.get_value(&Value::Object(a), &index_key(n))?;
i.temp_roots.push(item.clone());
let text = text_arg(i, &item)?;
new_item(i, c, text)?;
staged += 1;
}
@@ -569,8 +573,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value>
}
}
// A getter or a conversion above may have added controls or items itself, or removed the
// container from its dialog.
window_of(i, o, "add")?;
// container from its dialog. An object made to look like a container is not in the dialog,
// so it charges nothing to the dialog's controls.
window_in(i, o, "add")?;
let count = number_slot(i, win, COUNT)?;
if count as usize >= MAX_CONTROLS {
return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls")));
@@ -593,7 +598,7 @@ fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult<Value> {
// The conversion runs first: it may add or remove items itself.
let text = text_arg(i, text)?;
i.rooted(std::slice::from_ref(&text), |i| {
let win = window_of(i, o, "add")?;
let win = window_in(i, o, "add")?;
let count = number_slot(i, win, ITEM_COUNT)?;
if count as usize >= MAX_ITEMS {
return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all")));
@@ -725,17 +730,50 @@ fn kids_of(i: &Interp, o: ObjId) -> JsResult<Vec<Value>> {
fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult<Value> {
let (o, _) = element(i, &this, "findElement")?;
let want = i.to_str(&arg(args, 0))?;
let mut stack: Vec<Value> = kids_of(i, o)?.into_iter().rev().collect();
while let Some(v) = stack.pop() {
i.use_fuel()?;
let Some(c) = v.as_object() else { continue };
let name = i.get_value(&v, &key("name"))?;
if matches!(&name, Value::String(s) if *s == want) {
return Ok(v);
let mark = i.temp_roots.len();
let r = (|| {
// The controls still to look at stay rooted while a `name` getter runs, and each one is
// looked at only while the element still holds it.
let mut stack: Vec<Value> = kids_of(i, o)?.into_iter().rev().collect();
i.temp_roots.extend(stack.iter().cloned());
while let Some(v) = stack.pop() {
i.use_fuel()?;
let Some(c) = v.as_object() else { continue };
if !holds(i, o, c)? {
continue;
}
let name = i.get_value(&v, &key("name"))?;
if !holds(i, o, c)? {
continue;
}
if matches!(&name, Value::String(s) if *s == want) {
return Ok(v);
}
let kids = kids_of(i, c)?;
i.temp_roots.extend(kids.iter().cloned());
stack.extend(kids.into_iter().rev());
}
stack.extend(kids_of(i, c)?.into_iter().rev());
Ok(Value::Null)
})();
i.temp_roots.truncate(mark);
r
}
/// Does the element `top` hold the control `c`: does each container from `c`'s up to `top` hold
/// the one below?
fn holds(i: &Interp, top: ObjId, c: ObjId) -> JsResult<bool> {
let mut at = c;
for _ in 0..=MAX_DEPTH {
let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) };
if !kids_of(i, p)?.iter().any(|k| same(k, &Value::Object(at))) {
return Ok(false);
}
if p == top {
return Ok(true);
}
at = p;
}
Ok(Value::Null)
Ok(false)
}
/// Calls the element's handler `name` when it has one. → its result, or `None` without one.
@@ -1261,9 +1299,14 @@ fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult<Value> {
Ok(Value::Number(result))
}
/// Runs `onClose`. → false when it returned `false`.
/// Runs `onClose`. → false when it returned `false`. A `close()` that `onClose` calls belongs to
/// the close it decides on, so after `false` the dialog waits for the next event.
fn may_close(i: &mut Interp, win: ObjId) -> JsResult<bool> {
Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false))))
let closes = !matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)));
if !closes {
set_slot(i, win, CLOSING, Value::Undefined)?;
}
Ok(closes)
}
/// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next.
@@ -1480,8 +1523,9 @@ fn margins(i: &mut Interp, v: &Value) -> JsResult<Data> {
/// The dialog's description: its elements in order, each after the container that holds it, as
/// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of
/// its default and cancel elements (-1 for none), and each element's array of list items as it
/// was described (`undefined` for an element that is not a list). When a getter changes a list
/// after it was read, the dialog is read again once; a list that changes again throws an `Error`.
/// was described (`undefined` for an element that is not a list). When a getter changes a list,
/// or adds or removes a control, after it was read, the dialog is read again once; a dialog that
/// changes again throws an `Error`.
fn describe(i: &mut Interp, win: ObjId) -> JsResult<Described> {
for _ in 0..2 {
let mark = i.temp_roots.len();
@@ -1491,7 +1535,7 @@ fn describe(i: &mut Interp, win: ObjId) -> JsResult<Described> {
return Ok(d);
}
}
Err(error(i, "show: a list's items changed while the dialog was read"))
Err(error(i, "show: a list's items or a container's controls changed while the dialog was read"))
}
/// A description, the elements in its order, the default and cancel elements, and the lists' items.
@@ -1507,8 +1551,20 @@ fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value
Ok(true)
}
/// Has each element in `order` the array of controls it had when the dialog was read?
fn tree_unchanged(i: &Interp, order: &[(ObjId, String, f64)], tree: &[Value]) -> JsResult<bool> {
for ((o, ..), kept) in order.iter().zip(tree) {
let now = slot(i, *o, KIDS)?;
if !(same(&now, kept) || matches!((&now, kept), (Value::Undefined, Value::Undefined))) {
return Ok(false);
}
}
Ok(true)
}
fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<Option<Described>> {
let mut order: Vec<(ObjId, String, f64)> = Vec::new();
let mut tree = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)];
while let Some((v, parent, depth)) = stack.pop() {
@@ -1525,6 +1581,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<Option<Described>> {
}
let index = order.len() as f64;
order.push((o, kind, parent));
// Each container's array of controls as it is read; a change to it means a later getter
// added or removed a control.
let held = slot(i, o, KIDS)?;
i.temp_roots.push(held.clone());
tree.push(held);
for kid in kids_of(i, o)?.into_iter().rev() {
stack.push((kid, index, depth + 1));
}
@@ -1595,6 +1656,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<Option<Described>> {
Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()),
_ => (false, false),
};
// The dialog cannot hide what is typed, so a field meant to hide it is refused before it shows.
if props.as_object().is_some() && i.get_value(&props, &key("noecho"))?.truthy() {
return Err(error(i, "show: an edit field that hides its text (noecho) is not available yet"));
}
d.push(("multiline".into(), Data::Bool(multiline)));
d.push(("readonly".into(), Data::Bool(readonly)));
}
@@ -1634,7 +1699,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<Option<Described>> {
};
let def = target(i, "defaultElement", "ok")?;
let cancel = target(i, "cancelElement", "cancel")?;
if !lists_unchanged(i, &order, &snapshot)? {
if !lists_unchanged(i, &order, &snapshot)? || !tree_unchanged(i, &order, &tree)? {
return Ok(None);
}
let desc = Data::Object(vec![
+69 -1
View File
@@ -340,7 +340,75 @@ fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() {
let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \
Object.defineProperty(b, 'text', {get: function () { l.removeAll(); l.add('item', 'B'); return 'OK'; }}); \
try { w.show(); } catch (e) { e.message }";
assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items changed while the dialog was read".into()));
assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into()));
}
#[test]
fn a_control_a_later_getter_removes_is_not_in_the_description() {
let (mut r, seen, _) = realm(vec![click(1)]);
let source = "var w = new Window('dialog'); var ok = w.add('button', undefined, 'OK'); var b = w.add('button', undefined, 'Go'); \
var gone = false; Object.defineProperty(b, 'text', {get: function () { if (!gone) { gone = true; w.remove(ok); } return 'Go'; }}); \
var went = 0; b.onClick = function () { went++; w.close(5); }; ok.onClick = function () { went = -1; }; [w.show(), went].join()";
assert_eq!(r.run(source).unwrap(), JsValue::String("5,1".into()), "the click at index 1 reaches Go, which the dialog still holds");
let seen = seen.borrow();
let first = nodes(&seen.descriptions[0]);
assert_eq!(first.len(), 2, "the removed OK button is not described");
assert_eq!(field(&first[1], "text"), &Data::String("Go".into()));
let (mut r, _, _) = realm(Vec::new());
let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \
Object.defineProperty(b, 'text', {get: function () { w.add('statictext', undefined, 'more'); return 'Go'; }}); \
try { w.show(); } catch (e) { e.message }";
assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into()));
}
#[test]
fn a_list_s_initial_items_are_read_through_their_getters() {
let (mut r, seen, _) = realm(vec![close()]);
let source = "var a = ['x']; Object.defineProperty(a, 0, {get: function () { return 'A'; }}); \
var w = new Window('dialog'); w.add('listbox', undefined, a); w.show()";
assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0));
let seen = seen.borrow();
assert_eq!(field(&nodes(&seen.descriptions[0])[1], "items"), &Data::Array(vec![Data::String("A".into())]));
}
#[test]
fn an_object_made_to_look_like_a_container_charges_nothing_to_the_dialog() {
let (mut r, _, _) = realm(Vec::new());
let source = format!(
"var w = new Window('dialog'); var fake = {{__vcKind: 'group', __vcWindow: w, __vcDepth: 0, __vcKids: []}}; \
fake.add = w.add; var e = ''; try {{ fake.add('button'); }} catch (x) {{ e = x.name; }} \
var l = w.add('listbox'); var fl = {{__vcKind: 'listbox', __vcWindow: w, __vcItems: []}}; fl.add = l.add; \
var f = ''; try {{ fl.add('item', 'A'); }} catch (x) {{ f = x.name; }} \
for (var n = 1; n < {}; n++) w.add('statictext'); [e, f, w.children.length].join()",
scriptui::MAX_CONTROLS
);
assert_eq!(r.run(&source).unwrap(), JsValue::String(format!("TypeError,TypeError,{}", scriptui::MAX_CONTROLS)));
}
#[test]
fn find_element_skips_a_control_a_name_getter_removes() {
let (mut r, _, _) = realm(Vec::new());
let source = "function heavy() { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); } \
var w = new Window('dialog'); var a = w.add('button'); var b = w.add('button', undefined, 'B', {name: 'b'}); \
Object.defineProperty(a, 'name', {get: function () { w.remove(b); b = null; heavy(); return 'a'; }}); \
String(w.findElement('b'))";
assert_eq!(r.run(source).unwrap(), JsValue::String("null".into()));
}
#[test]
fn a_close_that_on_close_asks_for_is_part_of_the_close_it_refuses() {
let (mut r, _, _) = realm(vec![close(), click(1)]);
let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var asked = 0; \
w.onClose = function () { asked++; if (asked == 1) { w.close(7); return false; } }; [w.show(), asked].join()";
assert_eq!(r.run(source).unwrap(), JsValue::String("1,2".into()), "the refused close waits for the click on OK");
}
#[test]
fn an_edit_field_that_hides_its_text_is_refused_when_shown() {
let (mut r, seen, _) = realm(Vec::new());
let source = "var w = new Window('dialog'); w.add('edittext', undefined, 'secret', {noecho: true}); try { w.show(); } catch (e) { e.message }";
assert_eq!(r.run(source).unwrap(), JsValue::String("show: an edit field that hides its text (noecho) is not available yet".into()));
assert!(seen.borrow().descriptions.is_empty(), "the dialog never opens");
}
#[test]
+6 -2
View File
@@ -35,7 +35,7 @@ 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::{UiNode, check_event, list_index};
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;
@@ -533,12 +533,16 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> 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, drafts: &mut 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(None)
.limit(DRAFT_CHARS)
.id_salt((KIND, n.id))
.enabled(enabled)
.read_only(n.readonly);
+22
View File
@@ -413,6 +413,28 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t
assert!(!until_window(&mut app));
}
#[test]
fn an_edit_field_takes_at_most_its_draft_limit_while_it_is_typed() {
let mut app = app();
start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, ''); w.add('button', undefined, 'OK'); vc.log(w.show());");
assert!(until_window(&mut app));
step(&mut app, Vec::new());
access_nodes(&app);
let nodes = access_nodes(&app);
let b = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput).and_then(egui::accesskit::Node::bounds);
let b = b.unwrap_or_else(|| panic!("no edit field"));
let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5);
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
step(&mut app, vec![egui::Event::PointerMoved(at)]);
step(&mut app, vec![button(true)]);
step(&mut app, vec![button(false)]);
step(&mut app, vec![egui::Event::Paste("x".repeat(script_window::DRAFT_CHARS + 100))]);
let typed_now = typed(&app, 1).expect("the pasted text is kept while the field has the focus");
assert_eq!(typed_now.chars().count(), script_window::DRAFT_CHARS, "the draft stops at its limit");
app.session.script_request_stop();
assert!(!until_window(&mut app));
}
#[test]
fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() {
let mut app = app();
+5 -3
View File
@@ -3000,7 +3000,8 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s
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.
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.
@@ -3058,8 +3059,9 @@ nobody to ask, `alert`, `confirm` and `prompt` in a handler take their answers f
`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 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`,
too, and a slider's minimum above its maximum. When a getter changes a list's items 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