diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index f4aeea23d9..a55af85287 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "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 { 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))?; diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index c635db0585..16c8458957 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -211,6 +211,9 @@ pub(crate) struct Dialogs { waiting: RefCell>, /// The error that ended the run when an answer could not reach the script. failed: RefCell>, + /// 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, records: RefCell>, record_bytes: Cell, count: Cell, @@ -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); } } diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e02e4727f1..b811c623b8 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -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, waiting: VecDeque, 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, + /// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its + /// run takes inside it (`update()`). + taken_inline: Option>, /// The event the run that starts next handles ([`Session::script_palette_start`]). pub(crate) starting: Option, } @@ -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 { - 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 { - 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())) + }) } } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 2618cd9083..0a253f0961 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -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())); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 596ac62671..770f34957c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -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), } } diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 131db628db..bc05f207b8 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -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 { fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { 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 { _ => 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))?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index f3ef2c7840..2163026393 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -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))]); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f984d0eeec..2b6091c4d9 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -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 => {} diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 074b2a5567..48401c4b57 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -239,6 +239,9 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap 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 = 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 = events.filter_map(|e| queued(&w, &e)).collect(); if deferred { diff --git a/docs/mcp.md b/docs/mcp.md index b05820412e..ecdcd662bf 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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();"}'