Scripts: ScriptUI dialogs keep to their limits and steps under reentrant handlers

- A show() that a handler's error ended with steps left in `answers` now
  ends the run and rolls it back, even when the script catches the error.
- A list step's value written as a whole float (1.0) is an item index,
  in `answers` and in ui.dialog.confirm; a fraction is still refused.
- A progress bar's fraction stays finite across the widest range.
- add() checks the control and item counts again after the getters and
  conversions it runs, refuses an initial item array longer than the
  items left before reading it, and counts a new list's items only once
  the list is added.
- show() keeps the values a getter gives while their properties are
  read, and reads the dialog again when a getter changes a list after
  it was read; a list that changes again throws an Error.
- A click or close from ui.dialog.confirm gives the text still typed in
  the dialog's fields first.
- Quitting while a handler runs keeps the dialog and its queued events,
  so Cancel shows it again with them.
- Screen readers call an edit field without a name by the visible static
  text just before it in its container.
- The dialog's heading follows a title a handler changed while the
  dialog is open.
- A list box gives screen readers a list box node named by its name or
  the static text before it, with the selected item as its value, and a
  drop-down list is named the same way.
- The dialog closes when show() returns, also when the script goes on
  running.
- Enter clicks the default button while the keyboard focus is on a
  control other than an edit field, such as a slider.
This commit is contained in:
dotCooCoo committed 2026-11-22 04:00:21 -08:00
1 parent c3ea4e2f9c
commit 3745b14db4
11 files changed
+564 -76

No files matched your search

+17 -3
View File
@@ -21,7 +21,7 @@ use std::collections::VecDeque;
use std::rc::Rc;
use serde_json::{Map, Value, json};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError};
use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind};
use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep};
use super::{Host, console};
@@ -258,6 +258,11 @@ impl Dialogs {
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs.
pub(crate) fn showing_window(&self) -> Option<ScriptUiDialog> {
self.window.borrow().as_ref().map(|s| s.dialog.clone())
}
/// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog.
pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> {
if !self.window_waiting.get() {
@@ -347,10 +352,19 @@ impl Dialogs {
self.window_waiting.set(false);
let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) };
let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len);
let steps = if left == 1 { "step" } else { "steps" };
let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use");
if normal && left > 0 {
self.push_record(showing.record(json!("missing")));
let steps = if left == 1 { "step" } else { "steps" };
return Err(HostError::Abort(format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use")));
return Err(HostError::Abort(unused));
}
// A show that a handler's error ended still ends the run when steps are left: the script
// can catch that error, and the run must not finish as if it took every step.
if left > 0 {
let mut failed = self.failed.borrow_mut();
if failed.is_none() {
*failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false });
}
}
let answer = match result {
_ if !normal => json!("error"),
+15
View File
@@ -1833,6 +1833,15 @@ impl Session {
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten()
}
/// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs
/// one of its handlers. A run asked to stop is in none.
pub fn script_window_showing(&self) -> Option<ScriptUiDialog> {
if self.script_stop.is_set() {
return None;
}
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten()
}
/// Gives the ScriptUI dialog the running script waits at `event`; the next
/// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still
/// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]).
@@ -2158,6 +2167,12 @@ impl Session {
}
job.host.calls_this_slice.set(0);
let outcome = run_slice(self, &mut job);
// A failure a dialog recorded in the slice (steps a show left unused) ends the run, even
// when the script went on.
let outcome = match (outcome, job.host.dialogs.take_failure()) {
(Ok(Ok(_)), Some(e)) => Ok(Err(e)),
(outcome, _) => outcome,
};
match outcome {
Err(panic) => {
let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false };
+31 -2
View File
@@ -148,6 +148,23 @@ pub struct UiNode {
bounds: Option<UiRect>,
}
impl UiNode {
/// How much of a progress bar is done, from 0 to 1.
pub fn fraction(&self) -> f32 {
if self.max <= self.min || self.value <= self.min {
return 0.0;
}
if self.value >= self.max {
return 1.0;
}
let span = self.max - self.min;
// A range wider than the largest number is measured at half scale.
let part =
if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) };
part.clamp(0.0, 1.0) as f32
}
}
/// A dialog a run shows, checked and laid out.
#[derive(Clone, Debug, PartialEq)]
pub struct ScriptUiDialog {
@@ -302,8 +319,8 @@ pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEve
let event = match (step.event.as_str(), &step.value) {
("click", _) => UiEvent::Click(id),
(_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match n.as_u64() {
Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))),
(_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) {
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
None => return Err("a list's `value` must be an item index or null".into()),
},
(_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))),
@@ -313,6 +330,18 @@ pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result<UiEve
check_event(dialog, event)
}
/// A list's item index written as a JSON number: a whole number of 0 or more, as an integer or as
/// a float such as `1.0`; an index past the end stays past it. `None` for a fraction or a negative
/// number.
pub fn list_index(n: &serde_json::Number) -> Option<usize> {
if let Some(k) = n.as_u64() {
return Some(usize::try_from(k).unwrap_or(usize::MAX));
}
let f = n.as_f64()?;
// `as` saturates a whole number too large for usize at usize::MAX.
(f >= 0.0 && f.fract() == 0.0).then_some(f as usize)
}
fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data {
fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v)
}
+42 -1
View File
@@ -127,6 +127,7 @@ fn window_answers_that_do_not_parse_are_refused_before_the_run() {
#[test]
fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() {
let mut s = one_doc();
let undo_before = art(&s).1;
framed(
&mut s,
&format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"),
@@ -153,7 +154,47 @@ fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() {
let r = pump(&mut s).unwrap().unwrap();
assert_eq!(r["log"], json!([[1, "Ann", 5]]));
assert_eq!(r["dialogs"][0]["events"], 3);
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step");
assert_eq!(art(&s).1, undo_before + 1, "a finished run is one undo step");
assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script");
}
#[test]
fn an_unused_step_after_a_handler_threw_ends_the_run_and_rolls_it_back() {
let mut s = one_doc();
let before = art(&s);
let source = format!(
"{EDIT} var w = new Window('dialog'); var f = w.add('button', undefined, 'Fail'); f.onClick = function () {{ throw new Error('boom'); }}; \
try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"
);
let steps = window(json!([{"control": "Fail", "event": "click"}, {"event": "close"}]));
let e = headless(&mut s, &source, steps).unwrap_err().to_string();
assert!(e.contains("has 1 step the dialog did not use"), "{e}");
assert_eq!(art(&s), before, "the run is rolled back");
}
#[test]
fn a_list_index_written_as_a_whole_float_is_an_index_and_a_fraction_is_refused() {
let mut s = one_doc();
let source = format!("{FORM} vc.log([w.show(), pick.selection.text]);");
let r = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.0}, {"control": "OK", "event": "click"}])))
.unwrap();
assert_eq!(r["log"], json!([[1, "b"]]));
let e = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.5}]))).unwrap_err().to_string();
assert!(e.contains("a list's `value` must be an item index or null"), "{e}");
}
#[test]
fn a_progress_bar_s_fraction_stays_finite_over_the_widest_range() {
let bar = |min: f64, max: f64, value: f64| {
let n =
with(with(with(node("progressbar", 0.0), "minvalue", Data::Number(min)), "maxvalue", Data::Number(max)), "value", Data::Number(value));
scriptui::parse(&description(vec![node("dialog", -1.0), n])).unwrap().nodes[1].fraction()
};
assert_eq!(bar(-1e308, 1e308, 1e308), 1.0);
assert_eq!(bar(-1e308, 1e308, -1e308), 0.0);
assert_eq!(bar(-1e308, 1e308, 0.0), 0.5);
assert_eq!(bar(0.0, 10.0, 3.0), 0.3);
assert_eq!(bar(5.0, 5.0, 5.0), 0.0, "an empty range shows nothing done");
}
#[test]
+109 -27
View File
@@ -28,7 +28,9 @@
//! script cannot change. The description lists the dialog first and every control after the
//! 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 are VectorCraft's own limits.
//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These 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`.
use crate::HostItem;
use crate::builtins::{arg, constructor, method, native, pausable_method};
@@ -363,33 +365,66 @@ 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) {
Value::Undefined | Value::Null => {}
Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => {
for item in list_values(i, a)? {
add_item(i, c, &item)?;
let length = match &i.object(a)?.class {
Class::Array { length, .. } => *length as usize,
_ => 0,
};
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)?;
new_item(i, c, text)?;
staged += 1;
}
}
_ => return Err(i.type_error("add: give a list's items as an array")),
}
}
// A getter or a conversion above may have added controls or items itself.
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")));
}
let items = number_slot(i, win, ITEM_COUNT)?;
if items as usize + staged > MAX_ITEMS {
return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all")));
}
append(i, o, KIDS, "children", Value::Object(c))?;
set_slot(i, win, COUNT, Value::Number(count + 1.0))?;
set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?;
Ok(Value::Object(c))
})();
i.temp_roots.truncate(mark);
r
}
/// Adds an item with `text` to the list `o`.
/// Adds an item with `text` to the list `o`, which the dialog holds.
fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult<Value> {
let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) };
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")));
}
// 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 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")));
}
let item = new_item(i, o, text.clone())?;
i.rooted(std::slice::from_ref(&item), |i| set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0)))?;
Ok(item)
})
}
/// Adds an item with `text` to the end of the list `o`, without counting it in the dialog's items.
fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult<Value> {
let proto = classes(i)?.item_proto;
i.rooted(std::slice::from_ref(&text), |i| {
i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?;
@@ -398,7 +433,6 @@ fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult<Value> {
set_slot(i, item, LIST, Value::Object(o))?;
set_open(i, item, "text", text.clone())?;
append(i, o, ITEMS, "items", Value::Object(item))?;
set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0))?;
Ok(Value::Object(item))
})
})
@@ -610,7 +644,7 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult<Pause> {
set_showing(i, Some(win));
set_slot(i, win, CLOSING, Value::Undefined)?;
let described = describe(i, win);
let (desc, nodes, def, cancel) = match described {
let (desc, nodes, def, cancel, lists) = match described {
Ok(d) => d,
Err(e) => {
set_showing(i, None);
@@ -621,7 +655,7 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult<Pause> {
Ok(Pause {
host: open,
args: vec![desc],
keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)],
keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)],
resume: opened,
failed: Some(failed),
})
@@ -664,12 +698,12 @@ fn next(i: &mut Interp, win: ObjId) -> JsResult<Value> {
}
continue;
}
let (desc, nodes, def, cancel) = describe(i, win)?;
let (desc, nodes, def, cancel, lists) = describe(i, win)?;
let wait = host_fn(i, "wait")?;
i.again = Some(Pause {
host: wait,
args: vec![desc],
keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)],
keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)],
resume: answered,
failed: Some(failed),
});
@@ -761,6 +795,14 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult<Value> {
Value::Number(n) => n,
_ => -1.0,
};
// The index is into the items the person saw.
let shown = match arg(keep, 4).as_object() {
Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined),
None => Value::Undefined,
};
if !same(&slot(i, c, ITEMS)?, &shown) {
return Err(error(i, "show: a list's items changed before the person's choice was taken"));
}
set_slot(i, c, SELECTION, Value::Number(n))?;
}
}
@@ -785,6 +827,13 @@ fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult<Value> {
i.get_value(&Value::Object(o), &key(name))
}
/// [`get`], keeping the value in the roots [`describe`] lets go of when it returns.
fn get_kept(i: &mut Interp, o: ObjId, name: &str) -> JsResult<Value> {
let v = get(i, o, name)?;
i.temp_roots.push(v.clone());
Ok(v)
}
fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult<Data> {
let v = get(i, o, name)?;
Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?))
@@ -850,15 +899,35 @@ 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).
fn describe(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> {
let mark = i.temp_roots.len();
let r = describe_rooted(i, win);
i.temp_roots.truncate(mark);
r
/// 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`.
fn describe(i: &mut Interp, win: ObjId) -> JsResult<Described> {
for _ in 0..2 {
let mark = i.temp_roots.len();
let r = describe_rooted(i, win);
i.temp_roots.truncate(mark);
if let Some(d) = r? {
return Ok(d);
}
}
Err(error(i, "show: a list's items changed while the dialog was read"))
}
fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> {
/// A description, the elements in its order, the default and cancel elements, and the lists' items.
type Described = (Value, ObjId, f64, f64, ObjId);
/// Has each list in `order` the array of items it had when it was described?
fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value]) -> JsResult<bool> {
for ((o, ..), kept) in order.iter().zip(snapshot) {
if !matches!(kept, Value::Undefined) && !same(&slot(i, *o, ITEMS)?, kept) {
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 seen = std::collections::HashSet::new();
let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)];
@@ -885,8 +954,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
let mut nodes = Vec::with_capacity(order.len());
let mut names = Vec::with_capacity(order.len());
let mut items_total = 0usize;
// Each list's array of items as it is read; a change to it means a later getter changed the list.
let mut snapshot = Vec::with_capacity(order.len());
for (o, kind, parent) in &order {
let o = *o;
let mut listed = Value::Undefined;
let name_v = get(i, o, "name")?;
let name = text_of(i, &name_v, "a control's name")?;
let text_v = get(i, o, "text")?;
@@ -902,19 +974,20 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
let visible = get(i, o, "visible")?.truthy();
d.push(("enabled".into(), Data::Bool(enabled)));
d.push(("visible".into(), Data::Bool(visible)));
let b = get(i, o, "bounds")?;
// 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(i, o, "preferredSize")?;
let size = get_kept(i, o, "preferredSize")?;
d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?));
let a = get(i, o, "alignment")?;
let a = get_kept(i, o, "alignment")?;
d.push(("alignment".into(), alignment(i, &a)?));
if matches!(kind.as_str(), "dialog" | "group" | "panel") {
let orientation = get(i, o, "orientation")?;
d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase())));
let ac = get(i, o, "alignChildren")?;
let ac = get_kept(i, o, "alignChildren")?;
d.push(("alignChildren".into(), alignment(i, &ac)?));
d.push(("spacing".into(), number_of(i, o, "spacing")?));
let m = get(i, o, "margins")?;
let m = get_kept(i, o, "margins")?;
d.push(("margins".into(), margins(i, &m)?));
}
match kind.as_str() {
@@ -928,7 +1001,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?));
}
"edittext" => {
let props = get(i, o, "properties")?;
let props = get_kept(i, o, "properties")?;
let (multiline, readonly) = match props {
Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()),
_ => (false, false),
@@ -937,6 +1010,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
d.push(("readonly".into(), Data::Bool(readonly)));
}
"dropdownlist" | "listbox" => {
let kept = slot(i, o, ITEMS)?;
i.temp_roots.push(kept.clone());
listed = kept;
let items = items_of(i, o)?;
items_total = items_total.saturating_add(items.len());
if items_total > MAX_ITEMS {
@@ -954,6 +1030,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
_ => {}
}
nodes.push(Data::Object(d));
snapshot.push(listed);
}
let target = |i: &mut Interp, name: &str, word: &str| -> JsResult<f64> {
let given = get(i, win, name)?;
@@ -968,6 +1045,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
};
let def = target(i, "defaultElement", "ok")?;
let cancel = target(i, "cancelElement", "cancel")?;
if !lists_unchanged(i, &order, &snapshot)? {
return Ok(None);
}
let desc = Data::Object(vec![
("nodes".into(), Data::Array(nodes)),
("defaultElement".into(), Data::Number(def)),
@@ -976,7 +1056,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f
let desc = i.write_data(desc, 0, true)?;
i.temp_roots.push(desc.clone());
let kept = list(i, &objects, false)?;
Ok((desc, kept, def, cancel))
i.temp_roots.push(Value::Object(kept));
let lists = list(i, &snapshot, false)?;
Ok(Some((desc, kept, def, cancel, lists)))
}
/// Adds `Window`, its prototype's methods, and the host functions in `items`.
+78
View File
@@ -265,6 +265,84 @@ fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() {
assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into()));
}
#[test]
fn an_add_that_a_getter_or_a_conversion_reenters_keeps_to_the_limits() {
let (mut r, _, _) = realm(Vec::new());
let controls = r
.run(
"var w = new Window('dialog'); for (var i = 0; i < 511; i++) w.add('button'); \
var props = {}; Object.defineProperty(props, 'name', {get: function () { w.add('button'); return 'n'; }}); \
var e = ''; try { w.add('button', undefined, 'x', props); } catch (x) { e = x.name; } [e, w.children.length].join()",
)
.unwrap();
assert_eq!(controls, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS)), "the getter took the last place");
let items = r
.run(
"var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1023; n++) l.add('item', 'i'); \
var t = {toString: function () { l.add('item', 'inner'); return 'outer'; }}; \
var e = ''; try { l.add('item', t); } catch (x) { e = x.name; } [e, l.items.length].join()",
)
.unwrap();
assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS)), "the conversion took the last place");
}
#[test]
fn a_new_list_s_items_count_only_once_it_is_added_and_too_many_are_refused_unread() {
let (mut r, _, _) = realm(Vec::new());
let failed = r
.run(
"var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1022; n++) l.add('item', 'i'); \
var bad = {toString: function () { throw new Error('no text'); }}; \
var e = ''; try { w.add('dropdownlist', undefined, ['a', bad]); } catch (x) { e = x.message; } \
l.add('item', 'y'); l.add('item', 'z'); [e, l.items.length, w.children.length].join()",
)
.unwrap();
assert_eq!(failed, JsValue::String(format!("no text,{},1", scriptui::MAX_ITEMS)), "the list that was not added took no places");
let long = r
.run(
"var w = new Window('dialog'); var read = false; var a = new Array(5000); a[0] = {toString: function () { read = true; return 'x'; }}; \
var e = ''; try { w.add('listbox', undefined, a); } catch (x) { e = x.name; } [e, read, w.children.length].join()",
)
.unwrap();
assert_eq!(long, JsValue::String("RangeError,false,0".into()), "an array longer than the limit is refused before its items are read");
}
#[test]
fn a_collection_while_a_bounds_or_margins_value_is_read_keeps_that_value() {
let (mut r, seen, _) = realm(vec![close()]);
let source = "function heavy(n) { return {valueOf: function () { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); return n; }}; } \
var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \
Object.defineProperty(b, 'bounds', {get: function () { return {left: heavy(1), top: 2, right: 30, bottom: 40}; }}); \
Object.defineProperty(w, 'margins', {get: function () { return [heavy(3), 4, 5, 6]; }}); \
w.show()";
assert_eq!(r.run(source).unwrap(), JsValue::Number(0.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], "bounds"), &numbers(&[1.0, 2.0, 30.0, 40.0]));
assert_eq!(field(&first[0], "margins"), &numbers(&[3.0, 4.0, 5.0, 6.0]));
}
#[test]
fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() {
let (mut r, seen, _) = realm(vec![change(1, Data::Number(0.0)), click(2)]);
let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \
var swapped = false; Object.defineProperty(b, 'text', {get: function () { if (!swapped) { swapped = true; l.removeAll(); l.add('item', 'B'); } return 'OK'; }}); \
var picked = ''; l.onChange = function () { picked = l.selection.text; }; w.show(); picked";
assert_eq!(r.run(source).unwrap(), JsValue::String("B".into()));
let seen = seen.borrow();
assert_eq!(
field(&nodes(&seen.descriptions[0])[1], "items"),
&Data::Array(vec![Data::String("B".into())]),
"the description shows the list as it is"
);
let (mut r, _, _) = realm(Vec::new());
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()));
}
#[test]
fn a_bounds_value_that_is_not_finite_is_refused_when_shown() {
let (mut r, _, _) = realm(Vec::new());
+10 -2
View File
@@ -209,8 +209,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
}
/// Closes the question quitting asks once the run it asks about has ended, and forgets the
/// script's dialog it was asked over once the run no longer waits at that dialog, so Cancel does
/// not show it again.
/// script's dialog it was asked over once the run no longer waits at that dialog (or, for a
/// ScriptUI dialog, once its `show()` has ended), so Cancel does not show it again.
pub(crate) fn settle_close(app: &mut VectorcraftApp) {
if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == CLOSE_KIND) {
return;
@@ -220,12 +220,20 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) {
} else if app.session.script_dialog().is_none()
&& app.session.script_picker().is_none()
&& app.session.script_window().is_none()
&& !over_running_show(app)
&& let Some(d) = app.ui.dialog.as_mut()
{
d.fields.remove(super::PARENT);
}
}
/// Was the question asked over the ScriptUI dialog of the `show()` the run is still in (one of its
/// handlers runs)? Cancel then shows that dialog again, with the events it has not given yet.
fn over_running_show(app: &VectorcraftApp) -> bool {
let Some(w) = app.session.script_window_showing() else { return false };
app.ui.dialog.as_ref().and_then(super::parent).is_some_and(|p| super::script_window::is_open_for(&p, &w))
}
/// Shows the dialog the running script waits at.
pub(crate) fn open_notice(app: &mut VectorcraftApp, d: &ScriptDialog) {
let fields = json!({
+93 -28
View File
@@ -5,8 +5,9 @@
//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`,
//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its
//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or
//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open; an event the
//! dialog cannot take is an error. An edit field gives its text when it loses the keyboard focus,
//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open, giving the
//! text still typed in its fields first when the event is a click or a close; an event the dialog
//! cannot take is an error. An edit field gives its text when it loses the keyboard focus,
//! when Enter is pressed in a one-line field, or before a click on another control or a close. Events given in
//! one frame reach the script one at a time, in order. Enter outside a field clicks the default button,
//! and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog when it has
@@ -83,7 +84,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc
ui.add_enabled_ui(waiting, |ui| {
for (i, n) in w.nodes.iter().enumerate().skip(1) {
if n.visible
&& let Some(e) = control(ui, d, area.min, i, n, w.default_element == Some(i))
&& let Some(e) = control(ui, d, area.min, (i, n, prompt_of(&w, i)), w.default_element == Some(i))
{
events.push(e);
}
@@ -101,7 +102,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc
app.ui.dialog = None;
return DialogAction::None;
}
let typing = ui.ctx().memory(|m| m.focused().is_some());
// Enter in a field belongs to the field; with the focus on any other control, it clicks the
// default button.
let typing = ui.ctx().memory(egui::Memory::focused).is_some_and(|id| egui::TextEdit::load_state(ui.ctx(), id).is_some());
if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) {
events.extend(w.default_element.map(UiEvent::Click));
}
@@ -158,8 +161,20 @@ fn draft_key(i: usize) -> String {
format!("text{i}")
}
/// Draws control `i` at its place from `origin`. → the event it gives.
fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &UiNode, default: bool) -> Option<UiEvent> {
/// The text of the visible static text just before control `i` in its container: the visible prompt
/// of an edit field, a list box or a drop-down list, which screen readers call one without a name
/// by. Empty when there is none.
pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str {
let Some(parent) = w.nodes.get(i).map(|n| n.parent) else { return "" };
match w.nodes[..i].iter().skip(1).rev().find(|n| n.parent == parent && n.visible) {
Some(n) if n.kind == UiKind::StaticText => &n.text,
_ => "",
}
}
/// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place from `origin`. → the
/// event it gives.
fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt): (usize, &UiNode, &str), default: bool) -> Option<UiEvent> {
let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h));
let t = Tokens::get(ui.ctx());
let mut event = None;
@@ -199,18 +214,23 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &
event = Some(UiEvent::Click(i));
}
}
UiKind::EditText => event = edit(ui, d, rect, i, n),
UiKind::EditText => event = edit(ui, d, rect, (i, n, prompt)),
UiKind::DropDownList => {
let shown = n.selection.and_then(|k| n.items.get(k)).cloned().unwrap_or_default();
let mut picked = None;
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| {
let r = craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| {
for (k, item) in n.items.iter().enumerate() {
if ui.selectable_label(n.selection == Some(k), item).clicked() {
picked = Some(k);
}
}
});
// Screen readers call the drop-down by its name or the static text before it.
let label = list_name(n, prompt);
if !label.is_empty() {
ui.ctx().accesskit_node_builder(r.response.id, |node| node.set_label(label));
}
});
if let Some(k) = picked.filter(|k| n.selection != Some(*k)) {
event = Some(UiEvent::Change(i, UiValue::Index(Some(k))));
@@ -219,6 +239,19 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &
UiKind::ListBox => {
ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(3.0)), |ui| {
// Screen readers read the box as a list box, by its name or the static text
// before it, with the selected item as its value.
let label = list_name(n, prompt);
let selected = n.selection.and_then(|k| n.items.get(k)).cloned();
ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
node.set_role(egui::accesskit::Role::ListBox);
if !label.is_empty() {
node.set_label(label);
}
if let Some(item) = selected {
node.set_value(item);
}
});
egui::ScrollArea::vertical().id_salt(("script-window-listbox", i)).max_height(rect.height() - 6.0).show(ui, |ui| {
for (k, item) in n.items.iter().enumerate() {
if ui.selectable_label(n.selection == Some(k), item).clicked() && n.selection != Some(k) {
@@ -231,16 +264,14 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &
UiKind::Slider => {
let mut v = n.value;
let r = ui.put(rect, egui::Slider::new(&mut v, n.min..=n.max).show_value(false));
name_for_screen_readers(ui, &r, n);
name_for_screen_readers(ui, &r, n, prompt);
if (r.drag_stopped() || (r.changed() && !r.dragged())) && v != n.value {
event = Some(UiEvent::Change(i, UiValue::Number(v)));
}
}
UiKind::ProgressBar => {
let span = n.max - n.min;
let part = if span > 0.0 { ((n.value - n.min) / span) as f32 } else { 0.0 };
let r = ui.put(rect, egui::ProgressBar::new(part));
name_for_screen_readers(ui, &r, n);
let r = ui.put(rect, egui::ProgressBar::new(n.fraction()));
name_for_screen_readers(ui, &r, n, prompt);
}
});
});
@@ -248,28 +279,40 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &
}
/// Screen readers call a control with no visible label of its own (an edit field, a slider or a
/// progress bar) by the name the script gave it, or else a slider or progress bar by its text.
fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode) {
let label = if !n.name.is_empty() {
n.name.clone()
} else if n.kind != UiKind::EditText {
n.text.clone()
} else {
String::new()
};
/// progress bar) by the name the script gave it, or else a slider or progress bar by its text, and
/// an edit field by the visible static text just before it in its container.
fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode, prompt: &str) {
let label = screen_reader_name(n, prompt);
if !label.is_empty() {
ui.ctx().accesskit_node_builder(r.id, |node| node.set_label(label));
}
}
/// The name screen readers call a list box or a drop-down list `n` by: the name the script gave it,
/// or else the visible static text just before it. Empty for none.
fn list_name(n: &UiNode, prompt: &str) -> String {
if n.name.is_empty() { prompt.to_string() } else { n.name.clone() }
}
/// The name [`name_for_screen_readers`] gives control `n`; empty for none.
pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String {
if !n.name.is_empty() {
n.name.clone()
} else if n.kind != UiKind::EditText {
n.text.clone()
} else {
prompt.to_string()
}
}
/// 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 egui::Ui, d: &mut Dialog, rect: egui::Rect, i: usize, n: &UiNode) -> Option<UiEvent> {
fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (usize, &UiNode, &str)) -> Option<UiEvent> {
let key = draft_key(i);
let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string);
let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) };
let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width()));
name_for_screen_readers(ui, &r, n);
name_for_screen_readers(ui, &r, n, prompt);
if r.changed() {
d.fields.insert(key.clone(), json!(text));
}
@@ -310,8 +353,8 @@ fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result<UiEvent, String> {
("close", _) => Ok(UiEvent::Close),
("click", _) => Ok(UiEvent::Click(control)),
("change", Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))),
("change", Some(Value::Number(v))) if list => match v.as_u64() {
Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX))))),
("change", Some(Value::Number(v))) if list => match vectorcraft_engine::script::scriptui::list_index(v) {
Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(k)))),
None => Err("a list's `value` must be an item index or null".into()),
},
("change", Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))),
@@ -322,15 +365,37 @@ fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result<UiEvent, String> {
}
/// Gives the running script the event in the dialog's fields. The dialog stays open for the
/// script's next wait; an event it cannot take is an error.
/// script's next wait; an event it cannot take is an error. Before a click or a close, the script
/// is given the text still typed in the dialog's fields first, and the click or close waits for
/// its next wait.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) };
let event = event_of(&w, d)?;
app.session.script_window_answer(event)?;
vectorcraft_engine::script::scriptui::check_event(&w, event.clone())?;
let mut events = vec![event];
let open = app.ui.dialog.as_mut().filter(|open| open.kind == KIND);
if let Some(open) = open
&& matches!(events[0], UiEvent::Click(_) | UiEvent::Close)
{
commit_drafts(&w, open, &mut events);
}
let mut events = events.into_iter();
if let Some(first) = events.next() {
app.session.script_window_answer(first)?;
}
if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) {
for k in ["event", "control", "value"] {
open.fields.remove(k);
}
let later: Vec<Value> = events.map(|e| event_fields(&e)).collect();
if !later.is_empty() {
let mut queue = match open.fields.remove(QUEUE_KEY) {
Some(Value::Array(queue)) => queue,
_ => Vec::new(),
};
queue.splice(0..0, later);
open.fields.insert(QUEUE_KEY.into(), Value::Array(queue));
}
}
Ok(Value::Null)
}
+9 -3
View File
@@ -85,11 +85,17 @@ fn ask(app: &mut VectorcraftApp) -> bool {
if app.ui.dialog.is_none() {
script_window::open(app, &window);
}
// Its heading follows a title a handler changed.
if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == script_window::KIND) {
d.fields.insert("title".into(), serde_json::Value::from(window.title()));
}
return true;
}
// While a handler runs, the ScriptUI dialog stays open, until the run ends or asks about its
// growth.
if app.session.script_waiting() && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) {
// While a handler runs, the ScriptUI dialog stays open, until its show() ends or the run asks
// about its growth.
if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND)
&& (app.session.script_waiting() || app.session.script_window_showing().is_none())
{
app.ui.dialog = None;
}
if app.session.script_waiting() {
+144
View File
@@ -255,6 +255,150 @@ fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() {
assert_eq!(objects(&app), 0);
}
#[test]
fn quitting_while_a_handler_runs_keeps_the_events_still_queued() {
let mut app = app();
start(&mut app, &format!("{DRAW} {FORM} name.onChange = function () {{ name.text = name.text + '!'; }}; vc.log([w.show(), name.text]);"));
assert!(until_window(&mut app));
app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([{"event": "click", "control": 3, "value": null}]));
give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap();
dialogs::script_run::ask_to_close(&mut app);
assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND));
script_runs::poll(&mut app);
dialogs::cancel(&mut app);
assert!(until_window(&mut app), "the dialog opens again");
assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "with the click still queued");
frame(&mut app, Vec::new());
assert!(!until_window(&mut app), "the queued click on OK closes the dialog");
assert_eq!(log(&app), json!([[1, "Ann!"]]));
}
#[test]
fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() {
let mut app = app();
start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);"));
assert!(until_window(&mut app));
start_typing(&mut app);
give(&mut app, json!({"event": "click", "control": "OK"})).unwrap();
assert!(until_window(&mut app), "the script takes the text and waits again");
assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("text1"), "the text is given once");
frame(&mut app, Vec::new());
assert!(!until_window(&mut app), "the queued click on OK closes the dialog");
assert_eq!(log(&app), json!([[1, "typed"]]));
}
#[test]
fn ui_dialog_confirm_takes_a_whole_float_as_a_list_index_and_refuses_a_fraction() {
let mut app = app();
start(
&mut app,
"var w = new Window('dialog'); var l = w.add('dropdownlist', undefined, ['a', 'b'], {name: 'pick'}); w.add('button', undefined, 'OK'); \
vc.log([w.show(), l.selection.text]);",
);
assert!(until_window(&mut app));
assert!(give(&mut app, json!({"event": "change", "control": "pick", "value": 1.5})).is_err());
give(&mut app, json!({"event": "change", "control": "pick", "value": 1.0})).unwrap();
assert!(until_window(&mut app));
give(&mut app, json!({"event": "click", "control": "OK"})).unwrap();
assert!(!until_window(&mut app));
assert_eq!(log(&app), json!([[1, "b"]]));
}
#[test]
fn an_unnamed_edit_field_is_called_by_the_static_text_before_it() {
let mut app = app();
start(
&mut app,
"var w = new Window('dialog'); var g = w.add('group'); g.add('statictext', undefined, 'Width:'); g.add('edittext', undefined, '5'); \
w.add('edittext', undefined, 'x', {name: 'height'}); w.add('edittext', undefined, 'y'); \
var h = w.add('statictext', undefined, 'Secret'); h.visible = false; w.add('edittext', undefined, 'z'); \
w.add('statictext', undefined, 'Account'); w.add('edittext', undefined, 'a', {name: 'user'}); w.add('button', undefined, 'OK'); w.show();",
);
assert!(until_window(&mut app));
let w = app.session.script_window().unwrap();
let name = |i: usize| script_window::screen_reader_name(&w.nodes[i], script_window::prompt_of(&w, i));
assert_eq!(name(3), "Width:", "the static text before it in its group");
assert_eq!(name(4), "height", "the name the script gave it");
assert_eq!(name(5), "", "the control before it is no static text");
assert_eq!(name(7), "", "a hidden static text is no prompt");
assert_eq!(name(9), "user", "a name the script gave goes before the text before it");
app.session.script_request_stop();
assert!(!until_window(&mut app));
}
#[test]
fn a_title_a_handler_changes_and_a_list_box_reach_the_dialog() {
let mut app = app();
start(
&mut app,
"var w = new Window('dialog', 'First'); w.add('statictext', undefined, 'Fruit:'); var l = w.add('listbox', undefined, ['apple', 'pear']); \
l.selection = 1; w.add('statictext', undefined, 'Size:'); w.add('dropdownlist', undefined, ['small', 'large']); \
var b = w.add('button', undefined, 'Rename'); b.onClick = function () { w.text = 'Renamed'; }; \
w.add('button', undefined, 'OK'); w.show();",
);
assert!(until_window(&mut app));
give(&mut app, json!({"event": "click", "control": "Rename"})).unwrap();
assert!(until_window(&mut app));
assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "Renamed", "the heading follows the handler's title");
let ctx = CTX.with(Clone::clone);
ctx.enable_accesskit();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)));
let mut nodes = Vec::new();
for _ in 0..2 {
let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default();
}
let list = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ListBox && n.label() == Some("Fruit:") && n.value() == Some("pear"));
assert!(list, "screen readers read the list box by its prompt, with its selected item");
let drop = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ComboBox && n.label() == Some("Size:"));
assert!(drop, "screen readers read the drop-down list by its prompt");
app.session.script_request_stop();
assert!(!until_window(&mut app));
}
#[test]
fn enter_with_the_focus_on_a_slider_clicks_the_default_button() {
let mut app = app();
start(&mut app, "var w = new Window('dialog'); w.add('slider', undefined, 2, 0, 5); w.add('button', undefined, 'OK'); vc.log(w.show());");
assert!(until_window(&mut app));
let ctx = CTX.with(Clone::clone);
ctx.enable_accesskit();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0)));
let mut on_slider = false;
for _ in 0..8 {
frame(&mut app, vec![key(egui::Key::Tab)]);
let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx()));
out.textures_delta.clear();
on_slider = out
.platform_output
.accesskit_update
.is_some_and(|u| u.nodes.iter().any(|(id, n)| *id == u.focus && n.role() == egui::accesskit::Role::Slider));
if on_slider {
break;
}
}
assert!(on_slider, "Tab puts the focus on the slider");
frame(&mut app, vec![key(egui::Key::Enter)]);
assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog");
assert_eq!(log(&app), json!([1]));
}
#[test]
fn the_dialog_closes_when_its_show_ends_and_the_script_runs_on() {
let mut app = app();
start(&mut app, "var w = new Window('dialog'); w.add('button', undefined, 'OK'); w.show(); while (true) {}");
assert!(until_window(&mut app));
give(&mut app, json!({"event": "click", "control": "OK"})).unwrap();
for _ in 0..3 {
script_runs::poll(&mut app);
}
assert!(app.session.script_running(), "the script still runs");
assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != KIND), "the dialog its show() ended is closed");
app.session.script_request_stop();
assert!(!until_window(&mut app));
}
#[test]
fn a_large_dialog_draws_in_a_small_window() {
let mut app = app();
+16 -10
View File
@@ -2935,24 +2935,30 @@ function. A shown dialog can be shown again after it closes.
`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of
text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws
too, and a slider's minimum above its maximum. 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, 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.
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. Enter outside a field clicks the default button. Escape clicks the
cancel button, or closes the dialog when it has none. Quitting while it waits asks whether to stop the script, and
Cancel shows it again. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in
the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a disabled or
hidden control, a value out of a list's range and a click on a control that takes none are errors, and the dialog
stays open.
which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()`
returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another
control that Enter does not click. Escape clicks the
cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs,
asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet.
`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or
its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the
script the text still typed in the dialog's fields. A disabled or hidden control, a value out of a list's range, a
list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays
open.
A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is
`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a
control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a
list's item index or `null`. The dialog takes the next step each time it waits. The run ends with an error that
the script cannot catch, and every document goes back, when no step is left, when a step names a control the
dialog does not have or that cannot take it, or when the dialog closes with steps it did not use.
list's item index (a whole number, such as `2` or `2.0`) or `null`. The dialog takes the next step each time it
waits. The run ends with an error that the script cannot catch, and every document goes back, when no step is
left, when a step names a control the dialog does not have or that cannot take it, or when the dialog closes, or
an error in a handler ends `show()`, with steps it did not use.
```sh
vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}'