Scripts: palette events report their own run, and dialogs keep typed texts on a failed handoff

- script.palette.event with nobody to ask answers with the report of the
  run that handled the given event, also when it took the place of an
  earlier waiting event or a run of its engine took it with update(); an
  event dropped without a run is an error, and a later event that cannot
  start leaves the given event's result. An open drag in a document other
  than the active one is refused before the event waits, and the app's
  palette start check uses the same rule.
- A palette event's handler and the refresh after a run take no waiting
  event through update(), so a later event does not run inside them. The
  refresh after a named run spends at most the unbroken-run allowance.
- A click whose button a getter removed during the event runs no handler.
- A window answer that could not reach the script lists the dialog with
  the answer "error" instead of "stop".
- In a ScriptUI dialog, Escape, ui.dialog.cancel and a click keep the typed
  texts when the run does not take the event, and a refused event asks for
  the next frame so the queued events after it go on.
- Quitting while only palettes are open asks whether to stop the run.
This commit is contained in:
dotCooCoo committed 2026-11-30 03:31:54 -08:00
1 parent 48b59a3ccc
commit 7b3690163e
10 files changed
+169 -33

No files matched your search

+3 -3
View File
@@ -77,7 +77,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Script Palette Event",
[],
None,
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends",
"{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; a newer click on the same control, change of it or close of the same palette replaces the most recent waiting event of that kind for that control or palette only when it has the same file access roots; otherwise the new event waits at the end of the line (merged: false); a click or close takes its place only if no change of its palette waits after it, otherwise it waits as a new event (merged: false); a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group or a drag in a document other than the active one is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the waiting events run in order and the answer is the report of the run that handled this event (or its error): its own run, or a run of the same engine whose own code took it with update(), which gives it no report or undo step of its own; an event dropped without a run, because an earlier handler disabled, hid or removed its control or hid or closed its palette, ends with an error",
always,
palette_event
),
@@ -305,8 +305,8 @@ fn palette_event(s: &mut Session, p: &Value) -> Result<Value> {
let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) };
let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?;
// With nobody to ask, the event runs now or not at all: it is not kept for after an open undo
// group, which a run cannot start in.
if !s.script_frames && s.undo_group_open() {
// group or a drag in another document, which a run cannot start in.
if !s.script_frames && s.palette_run_blocked() {
return Err(EngineError::Other(script::OPEN_EDIT.to_string()));
}
let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?;
+11 -3
View File
@@ -211,6 +211,9 @@ pub(crate) struct Dialogs {
waiting: RefCell<Option<ScriptDialog>>,
/// The error that ended the run when an answer could not reach the script.
failed: RefCell<Option<RunError>>,
/// An answer could not reach the script, so a dialog still open when the run ends is listed
/// with the answer `"error"`.
answer_failed: Cell<bool>,
records: RefCell<Vec<Value>>,
record_bytes: Cell<usize>,
count: Cell<u64>,
@@ -234,6 +237,7 @@ impl Dialogs {
answers: RefCell::new(answers.into()),
waiting: RefCell::default(),
failed: RefCell::default(),
answer_failed: Cell::new(false),
records: RefCell::default(),
record_bytes: Cell::new(0),
count: Cell::new(0),
@@ -282,6 +286,7 @@ impl Dialogs {
self.window_waiting.set(false);
if let Err(e) = realm.answer(event.data()) {
*self.failed.borrow_mut() = Some(e);
self.answer_failed.set(true);
}
Ok(())
}
@@ -446,18 +451,21 @@ impl Dialogs {
*waiting = None;
if let Err(e) = realm.answer(answer.data()) {
*self.failed.borrow_mut() = Some(e);
self.answer_failed.set(true);
}
true
}
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or
/// `"error"` when an answer could not reach the script.
pub(crate) fn stopped(&self) {
let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") };
if let Some(d) = self.waiting.borrow_mut().take() {
self.record(&d, json!("stop"));
self.record(&d, answer.clone());
}
self.window_waiting.set(false);
if let Some(showing) = self.window.borrow_mut().take() {
self.end_record(&showing, json!("stop"));
self.end_record(&showing, answer);
}
}
+54 -12
View File
@@ -79,6 +79,9 @@ pub(crate) struct Queued {
/// The file access scope of the request that gave the event, which its run keeps, narrowed to
/// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]).
pub(crate) scope: crate::file_access::ScopeHandle,
/// The number of the request that gave the event last: an event that takes the place of a
/// waiting one takes a new number.
pub(crate) ticket: u64,
}
/// The palettes of a session, and the events that wait for a run.
@@ -87,6 +90,13 @@ pub(crate) struct Palettes {
list: Vec<ScriptPalette>,
waiting: VecDeque<Queued>,
last_id: u64,
/// The number the last event given took ([`Queued::ticket`]).
last_ticket: u64,
/// The number of the event whose run started last.
started_ticket: Option<u64>,
/// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its
/// run takes inside it (`update()`).
taken_inline: Option<Vec<u64>>,
/// The event the run that starts next handles ([`Session::script_palette_start`]).
pub(crate) starting: Option<Queued>,
}
@@ -187,15 +197,19 @@ impl Palettes {
0
};
let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element));
let ticket = self.last_ticket.wrapping_add(1);
if let Some(slot) = at.filter(|q| q.scope.same(&scope)) {
slot.event = event;
slot.list = list;
slot.ticket = ticket;
self.last_ticket = ticket;
return Ok(Waiting::Merged);
}
if self.waiting.len() >= MAX_WAITING {
return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept"));
}
self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope });
self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket });
self.last_ticket = ticket;
Ok(Waiting::Added)
}
@@ -253,7 +267,11 @@ impl Palettes {
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
/// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]).
pub(crate) fn take_for(&mut self, engine: &str) -> Option<Queued> {
self.next_of(engine).map(|(_, q)| q)
let q = self.next_of(engine).map(|(_, q)| q)?;
if let Some(taken) = self.taken_inline.as_mut() {
taken.push(q.ticket);
}
Some(q)
}
/// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`]
@@ -383,10 +401,19 @@ impl Session {
}
/// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event
/// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in
/// progress is not counted, since starting the run settles it.
/// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag
/// in a document other than the active one. A drag in the active document is not counted,
/// since starting the run settles it.
pub fn script_palette_can_start(&self) -> bool {
!self.script_palettes.waiting.is_empty() && !self.script_running() && !self.undo_group_open()
!self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked()
}
/// Whether an open edit keeps a palette event's run from starting: an undo group, the
/// session's or a document's, or a drag in a document other than the active one (starting the
/// run settles a drag in the active one).
pub(crate) fn palette_run_blocked(&self) -> bool {
let active = self.active().map(|d| d.uid);
self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active)
}
/// Whether an undo group is open, the session's or a document's, which a run cannot start in.
@@ -410,6 +437,7 @@ impl Session {
return None;
}
let (palette, mut queued) = self.script_palettes.next()?;
self.script_palettes.started_ticket = Some(queued.ticket);
queued.grants = Some(palette.grants.clone());
let title = palette.dialog.title();
let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() };
@@ -442,15 +470,29 @@ impl Session {
}
/// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn,
/// the one just given last. → that one's report. An event whose run could not begin, for
/// example because the recovery copies could not be saved, ends this with its error, and the
/// events after it keep waiting.
/// in their order in line. → the report of the event just given, wherever it waited, or an
/// error when it was dropped without a run. An event whose run could not begin, for example
/// because the recovery copies could not be saved, ends this, and the events after it keep
/// waiting: with its error, or with the given event's result when that one has run.
pub(crate) fn script_palette_run_waiting(&mut self) -> Result<Value> {
let mut last = Err(EngineError::Other("no script palette event waits".into()));
let want = self.script_palettes.last_ticket;
let mut mine = None;
while let Some(started) = self.script_palette_start() {
started?;
last = self.script_run_to_end();
// A later event whose run cannot begin leaves the given event's result as it is.
if let Err(e) = started {
return mine.unwrap_or(Err(e));
}
self.script_palettes.taken_inline = Some(Vec::new());
let r = self.script_run_to_end();
// A run of the same engine can take the event while it runs (`update()`): its report
// is then the event's.
let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want));
if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) {
mine = Some(r);
}
}
last
mine.unwrap_or_else(|| {
Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into()))
})
}
}
@@ -642,6 +642,19 @@ fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_th
assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"]));
}
#[test]
fn with_nobody_to_ask_an_event_that_replaces_a_waiting_one_answers_with_its_own_report() {
let mut s = one_doc();
run(&mut s, TOOLS).unwrap();
let id = only_palette(&s);
assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added));
assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added));
// The new change takes the waiting change's place, before the click.
let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "z"})).unwrap();
assert_eq!(changed["log"], json!(["change z"]));
assert_eq!(s.script_palette_events_waiting(), 0, "the click after it ran too");
}
#[test]
fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() {
let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id()));
+11 -2
View File
@@ -685,10 +685,19 @@ impl Realm {
/// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as
/// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the
/// run's fuel, and what it throws ends the run.
/// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause
/// does; what it throws ends the run.
pub fn refresh_script_ui(&mut self) -> Result<(), RunError> {
match crate::scriptui::refresh(&mut self.interp) {
let interp = &mut self.interp;
let total = interp.fuel;
let cap = self.unbroken_fuel.min(total);
interp.fuel = cap;
let r = crate::scriptui::refresh(interp);
let used = cap - interp.fuel;
interp.fuel = total - used;
match r {
Ok(()) => Ok(()),
Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop),
Err(e) => self.outcome(Err(e)).map(drop),
}
}
+24 -3
View File
@@ -1784,7 +1784,13 @@ pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> {
if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) {
return Ok(());
}
update_palettes(i)
// An `update()` that a getter calls now takes no waiting event, which waits for a run of its
// own.
let was = i.script_ui.as_ref().is_some_and(|c| c.taking);
set_taking(i, true);
let r = update_palettes(i);
set_taking(i, was);
r
}
/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()`
@@ -1817,7 +1823,13 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult<Value> {
fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult<Value> {
let f = host_fn(i, "paletteEvent")?;
let answer = i.call(&f, &Value::Undefined, &[])?;
deliver(i, answer)?;
// An `update()` that a handler calls while this event runs takes no waiting event, so a later
// event does not run before this one has finished.
let was = i.script_ui.as_ref().is_some_and(|c| c.taking);
set_taking(i, true);
let r = deliver(i, answer);
set_taking(i, was);
r?;
Ok(Value::Undefined)
}
@@ -1872,7 +1884,16 @@ fn deliver(i: &mut Interp, answer: Value) -> JsResult<Value> {
_ => None,
},
};
let Some(at) = at.filter(|&n| n >= 1 && n < held.len()) else {
// A getter read in the description may also have removed the control after the
// description listed it: no handler runs for it.
let gone = match at.filter(|&n| n >= 1 && n < held.len()) {
Some(n) => match held[n].as_object() {
Some(c) => !holds(i, win, c)?,
None => false,
},
None => true,
};
let Some(at) = at.filter(|_| !gone) else {
return Err(error(i, "a palette event names a control the palette no longer holds"));
};
set_slot(i, ev, "id", Value::Number(at as f64))?;
+18
View File
@@ -956,6 +956,24 @@ fn a_palette_event_finds_its_control_by_its_id() {
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0));
}
#[test]
fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() {
// The palette is element 1, the label 2 and the button 3.
let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") };
fields.push(("element".into(), Data::Number(3.0)));
let (mut r, _) = palette_realm(vec![Data::Object(fields)]);
r.run(
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \
var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \
Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();",
)
.unwrap();
// The event reads the label's text for the palette's description, which removes the button.
let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap();
assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into()));
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run");
}
#[test]
fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() {
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]);
+2 -1
View File
@@ -729,7 +729,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
Some(parent) => {
host.open_child(close_question(), parent);
}
None if host.is_empty() => {
// The script's palettes stay open beside the question.
None if host.is_empty() || host.open_dialogs().iter().all(|d| d.key.as_deref() == Some(crate::script_palettes::KIND)) => {
host.open(close_question());
}
None => {}
+22 -4
View File
@@ -239,6 +239,9 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String
for id in given {
drafts.remove(&id);
}
// The events of one pass are listed in the order of the controls, not the order the person
// gave them, so each change goes before the clicks and the close, and a handler that closes
// the dialog reads it.
let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close);
events.sort_by_key(closing);
let at = events.iter().position(closing).unwrap_or(events.len());
@@ -771,6 +774,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
with_window(app, |d| d.drafts.insert(id, text));
}
app.status(e);
// The next frame gives the run the next queued event.
if let Some(ctx) = &app.ui_ctx {
ctx.request_repaint();
}
}
}
}
@@ -781,12 +788,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
/// next wait.
fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result<(), String> {
let mut events = vec![check_event(w, event)?];
// When the run does not take the first event, the typed texts stay in their fields.
let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default();
if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) {
with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?;
}
let mut events = events.into_iter();
if let Some(first) = events.next() {
app.session.script_window_answer(first)?;
if let Some(first) = events.next()
&& let Err(e) = app.session.script_window_answer(first)
{
with_window(app, |d| d.drafts = drafts);
return Err(e);
}
let later: Vec<Queued> = events.filter_map(|e| queued(w, &e)).collect();
with_window(app, |d| {
@@ -828,6 +840,8 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> {
return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string());
};
let mut events = vec![cancel_event(&w)];
// When the run does not take the first event, the typed texts stay in their fields.
let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default();
with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?;
let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true);
// A cancel after other events goes last, and is a click on the cancel button of the dialog the
@@ -837,8 +851,12 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> {
events.pop();
}
let mut events = events.into_iter();
if empty && let Some(first) = events.next() {
app.session.script_window_answer(first)?;
if empty
&& let Some(first) = events.next()
&& let Err(e) = app.session.script_window_answer(first)
{
with_window(app, |d| d.drafts = drafts);
return Err(e);
}
let mut later: Vec<Queued> = events.filter_map(|e| queued(&w, &e)).collect();
if deferred {
+11 -5
View File
@@ -3877,7 +3877,11 @@ the same controls, handlers and limits:
Always. A file allowed once stays with the run whose dialog allowed it, as for any later run.
- Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's
engine, with its own report and, when it changes a document, its own Run Script undo step. While another run
goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a
goes on, the event waits and runs after it; events run one at a time, oldest first. A run of the same engine
whose own code calls `update()` takes a waiting event inside that run instead: the event then has no report or
undo step of its own, and its changes are part of that run's. An `update()` in the handler of a palette event
that waited for a run of its own takes no waiting event, so the event waits until that run ends. With nobody to ask, `script.palette.event` answers
with the report of the run that handled the event it gave. While an event waits, a
newer click on the same control, change of the same control or close of the same palette replaces the most
recent waiting event of that kind for that control or palette only when it has the same file access scope.
Otherwise the new event waits at the end of the line (`merged: false`). A click or close takes its place only if no
@@ -3901,10 +3905,12 @@ visible, controls: [{index, kind, name, text, enabled, visible, value?, items?,
waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gives a shown palette a `click`, a
`change` or a `close`, with `control` and `value` as in a `window` answer's step (`control` can also be a control's
index). In the app it returns `{waiting: true, merged, waitingEvents}`, and the handler's report is later in
`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events and returns the report of this one,
or its error; an event whose run cannot begin ends it with that error, and the events after it keep waiting. A
hidden palette, a disabled or hidden control, and a control that cannot take the event are errors, and with nobody
to ask so is an event while an undo group is open.
`ui.inspect`'s `scriptReport`. With nobody to ask, it runs the waiting events in order and returns the report of
the run that handled this one, or its error, even when it took the place of an earlier waiting event; an event
dropped without a run is an error. An event whose run cannot begin ends it with that error, or with this event's
result when this one has run, and the events after it keep waiting. A hidden palette, a disabled or hidden
control, and a control that cannot take the event are errors, and with nobody to ask so is an event while an undo
group or a drag in a document other than the active one is open.
```sh
vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}'