diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index a63a712918..7d3c2eaf9e 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -236,6 +236,17 @@ impl Palettes { None } + /// Drops the events at the front of the line that [`Palettes::next`] would drop, so that the + /// line is empty or starts with an event that can still run. + fn drop_stale(&mut self) { + while let Some(q) = self.waiting.front() { + if self.resolved(q.clone()).is_some() { + break; + } + self.waiting.pop_front(); + } + } + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other /// engines' palettes keep their places in line. Events whose file access scopes do not cover /// the run's scope wait for runs of their own ([`Queued::scope`]). Eligible events run oldest @@ -252,7 +263,13 @@ impl Palettes { /// The taken event `q` given to its control in its palette, and that palette, or `None` when it /// is dropped ([`Palettes::next`]). - fn checked(&self, mut q: Queued) -> Option<(ScriptPalette, Queued)> { + fn checked(&self, q: Queued) -> Option<(ScriptPalette, Queued)> { + let (p, q) = self.resolved(q)?; + Some((p.clone(), q)) + } + + /// [`Palettes::checked`] without the copy of the palette. + fn resolved(&self, mut q: Queued) -> Option<(&ScriptPalette, Queued)> { let p = self.list.iter().find(|p| p.id == q.palette && p.visible)?; if let Some(c) = control_of(&mut q.event) { *c = p.dialog.index_of(q.element?)?; @@ -271,7 +288,7 @@ impl Palettes { } else { q.event = scriptui::check_event(&p.dialog, q.event).ok()?; } - Some((p.clone(), q)) + Some((p, q)) } /// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()` @@ -414,6 +431,12 @@ impl Session { self.script_palettes.waiting.len() } + /// The number of the last palette event put in line, which an event added, or merged into a + /// waiting one, changes. + pub fn script_palette_last_ticket(&self) -> u64 { + self.script_palettes.last_ticket + } + /// The changes that wait for a run, as (palette id, the id of the control they change). pub fn script_palette_changes_waiting(&self) -> Vec<(u64, u64)> { self.script_palettes @@ -456,7 +479,12 @@ impl Session { /// run is going or no event waits; otherwise the run's name, or the error that ended it before /// it began. An open edit that cannot be settled gives its error, and the events keep waiting. pub fn script_palette_start(&mut self) -> Option> { - if self.script_running() || self.script_palettes.waiting.is_empty() { + if self.script_running() { + return None; + } + // Events that can no longer run do not settle the open edit. + self.script_palettes.drop_stale(); + if self.script_palettes.waiting.is_empty() { return None; } // An event waits while a drag or an undo group is open, which a run cannot start in. @@ -507,6 +535,9 @@ impl Session { let want = self.script_palettes.last_ticket; let mut mine = None; loop { + if !self.script_running() { + self.script_palettes.drop_stale(); + } if !self.script_running() && !self.script_palettes.waiting.is_empty() && let Err(e) = self.settle_for_script() diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index cf873ec324..6908ef08ea 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -563,6 +563,32 @@ fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { assert_eq!(s.script_palette_events_waiting(), 0); } +#[test] +fn a_line_of_clicks_that_can_no_longer_run_does_not_settle_the_open_edit() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + // Settling would fail here, so a start that tries to settle gives an error. + SETTLE_FAILS.with(|f| f.set(true)); + let started = s.script_palette_start(); + SETTLE_FAILS.with(|f| f.set(false)); + assert!(started.is_none(), "the stale click does not settle the open edit: {:?}", started.map(|r| r.map_err(|e| e.to_string()))); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 8864fc1911..ba8e7f69f3 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1802,7 +1802,13 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if !slot(i, win, SHOWN)?.truthy() { return Ok(()); } + let hides = number_slot(i, win, HIDES)?; let (desc, ..) = describe(i, win)?; + // A getter that hid or closed the palette leaves the host the controls it had then. + let same = matches!(slot(i, win, PALETTE_ID)?, Value::Number(now) if now == id); + if !same || !slot(i, win, SHOWN)?.truthy() || number_slot(i, win, HIDES)? != hides { + return Ok(()); + } let f = host_fn(i, "paletteUpdate")?; i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; Ok(()) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 11bde4ca26..7468e82cfd 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -1250,6 +1250,22 @@ fn a_hidden_palette_is_not_described_after_the_run() { assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls"); } +#[test] +fn a_palette_a_title_getter_hides_is_not_described_after_the_run() { + let (mut r, calls) = palette_realm(Vec::new()); + r.run( + "var p = new Window('palette', 'T'); p.add('button', undefined, 'Go'); p.show(); var hiding = false; \ + Object.defineProperty(p, 'text', {get: function () { if (hiding) { hiding = false; p.hide(); return 'New'; } return 'T'; }});", + ) + .unwrap(); + let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count(); + let before = updates(&calls); + r.run("hiding = true;").unwrap(); + r.refresh_script_ui().expect("the refresh reads the title"); + assert_eq!(r.run("[hiding, p.visible].join()").unwrap(), JsValue::String("false,false".into()), "the getter ran and hid the palette"); + assert_eq!(updates(&calls), before, "the host keeps the controls the palette had when it was hidden"); +} + #[test] fn a_palette_event_does_not_run_a_handler_whose_getter_closed_the_palette() { let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]); @@ -1339,19 +1355,24 @@ fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_th #[test] fn a_palette_list_change_throws_when_a_later_item_s_text_getter_changes_an_earlier_item_s_text() { - let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); // The second read of the second item's text, which compares it with the items the person saw, - // changes the first item's text, which that comparison already took. - r.run( - "var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ - l.onChange = function () { got.push(String(l.selection)); }; var reads = -1; \ - Object.defineProperty(l.items[1], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { l.items[0].text = 'z'; } return 'b'; }}); \ - p.show();", - ) - .unwrap(); - let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); - assert_eq!(e, JsValue::String("a palette's list changed before the person's choice was taken".into())); - assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into())); + // changes the first item's text, which that comparison already took. It also puts back a plain + // `b` in place of its getter, so that only the first item's change can end the choice: without + // that change, the same choice reaches `onChange`. + for (mutate, error, got) in [(true, "a palette's list changed before the person's choice was taken", ""), (false, "none", "a")] { + let (mut r, _) = palette_realm(vec![seen_list_change(0.0)]); + r.run(&format!( + "var mutate = {mutate}; var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; \ + l.onChange = function () {{ got.push(String(l.selection)); }}; var reads = -1; var second = l.items[1]; \ + Object.defineProperty(second, 'text', {{configurable: true, get: function () {{ if (reads >= 0 && ++reads == 2) {{ \ + if (mutate) {{ l.items[0].text = 'z'; }} Object.defineProperty(second, 'text', {{value: 'b', writable: true, configurable: true}}); }} \ + return 'b'; }}}}); p.show();" + )) + .unwrap(); + let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap(); + assert_eq!(e, JsValue::String(error.into()), "mutate: {mutate}"); + assert_eq!(r.run("got.join()").unwrap(), JsValue::String(got.into()), "mutate: {mutate}"); + } } #[test] diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0448534fda..5cc27ca4d9 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -831,6 +831,8 @@ impl VectorcraftApp { toast::post(&ctx, &WindowKey::main(), Toast::new(t.message).tone(tone(t.level)).timeout(Some(t.seconds as f32))); } menus::native::sync(self, &ctx); + // A palette event whose start failed tries again after this pass's input. + crate::script_palettes::clear_failed_start(self, &ctx); // A palette event that waited for an undo group this pass ended starts its run next frame. if crate::script_palettes::can_start(self) { ctx.request_repaint(); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 48401c4b57..825e87abdb 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -218,6 +218,18 @@ pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap /// as the script in `w` would check it first; when one is refused, every field keeps its text, /// `events` stays as it was and the error is returned. pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap, events: &mut Vec) -> Result<(), String> { + commit_texts_over(w, drafts, events, &[]) +} + +/// [`commit_texts`] for fields whose earlier changes still wait to be delivered: a draft of a field +/// whose id is in `queued` is given even when it matches the field's text, since the script reads the +/// waiting change's text first. +pub(crate) fn commit_texts_over( + w: &ScriptUiDialog, + drafts: &mut BTreeMap, + events: &mut Vec, + queued: &[u64], +) -> Result<(), String> { let mut given = Vec::new(); let mut changes = Vec::new(); for (i, n) in w.nodes.iter().enumerate() { @@ -230,7 +242,7 @@ pub(crate) fn commit_texts(w: &ScriptUiDialog, drafts: &mut BTreeMap String { /// Draws the visible controls of the ScriptUI window `w` at the places the engine laid them out, /// with the text typed in its edit fields (`drafts`); none can be used unless `usable`. -pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, usable: bool) -> Pass { +pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, usable: bool, queued: &[u64]) -> Pass { let (width, height) = w.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; @@ -432,7 +444,13 @@ pub(crate) fn controls(ui: &mut Ui, w: &ScriptUiDialog, drafts: &BTreeMap, + queued_text: bool, } /// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, @@ -531,7 +550,7 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr shown.event = Some(UiEvent::Click(i)); } } - UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)), + UiKind::EditText => shown = edit(ui, rect, drafts, enabled, place.queued_text, (i, n, prompt)), UiKind::DropDownList => { let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect); @@ -634,9 +653,15 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { /// accepts, so that a text that is too long can still be typed, refused and shortened. pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; +/// The change an edit field `n` at index `i` gives when its text `text` is committed: none for a +/// read-only field, or for the field's own text unless a change of the field waits (`queued`). +pub(crate) fn text_change(i: usize, n: &UiNode, text: String, queued: bool) -> Option { + (!n.readonly && (text != n.text || queued)).then_some(UiEvent::Change(i, UiValue::Text(text))) +} + /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, queued: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) .limit(DRAFT_CHARS) @@ -648,13 +673,14 @@ fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: } let out = field.show_at(ui, rect); let focused = out.response.has_focus(); - let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); + let queued = queued && (drafts.contains_key(&n.id) || out.events.value().is_some()); + let mut draft = (out.events.value().is_some() || text != n.text || queued).then(|| Some(text.clone())); let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); - if committed && text != n.text && !n.readonly { - return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) }; + if committed && let Some(event) = text_change(i, n, text.clone(), queued) { + return Shown { event: Some(event), typing: true, container: None, draft: Some(None) }; } // A text the script refused stays in the field until the person changes it. - if !focused && text == n.text { + if !focused && text == n.text && !queued { draft = Some(None); } Shown { event: None, typing: focused || committed, container: None, draft } diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index eed7529753..33862e7af2 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -55,12 +55,21 @@ pub(crate) struct PaletteWindow { /// field shows it until no change of that field waits, even while the palette's field holds the /// same text, since a run before the change may set the field to another one. pending: BTreeMap, + queued_texts: Vec, open: bool, } impl PaletteWindow { fn new(palette: ScriptPalette) -> Self { - PaletteWindow { palette, drafts: BTreeMap::new(), draft_scopes: BTreeMap::new(), given: Vec::new(), pending: BTreeMap::new(), open: true } + PaletteWindow { + palette, + drafts: BTreeMap::new(), + draft_scopes: BTreeMap::new(), + given: Vec::new(), + pending: BTreeMap::new(), + queued_texts: Vec::new(), + open: true, + } } /// The palette as the session has it now. A typed text whose field the palette no longer has is @@ -68,6 +77,7 @@ impl PaletteWindow { /// [`vectorcraft_engine::Session::script_palette_changes_waiting`]). fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) { self.palette = palette; + self.queued_texts = waiting.iter().filter(|(id, _)| *id == self.palette.id).map(|(_, field)| *field).collect(); script_window::keep_fields(&self.palette.dialog, &mut self.drafts); let (nodes, palette, given) = (&self.palette.dialog.nodes, self.palette.id, !self.given.is_empty()); self.pending.retain(|id, _| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id)); @@ -76,7 +86,7 @@ impl PaletteWindow { /// Draws the palette's controls in `ui` and takes what the person did, as its body does. #[cfg(test)] pub(crate) fn paint(&mut self, ui: &mut Ui) { - let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true); + let pass = script_window::controls(ui, &shown_dialog(&self.palette.dialog, &self.pending), &self.drafts, true, &self.queued_texts); self.take_pass(pass.drafts.into_iter().collect(), pass.events); } @@ -105,8 +115,12 @@ impl PaletteWindow { /// the focus. #[cfg(test)] pub(crate) fn commit_text(&mut self, i: usize, text: &str) { - if let Some(n) = self.palette.dialog.nodes.get(i) { - self.take_pass(vec![(n.id, None)], vec![UiEvent::Change(i, UiValue::Text(text.to_string()))]); + let committed = shown_dialog(&self.palette.dialog, &self.pending) + .nodes + .get(i) + .map(|n| (n.id, script_window::text_change(i, n, text.to_string(), self.queued_texts.contains(&n.id)))); + if let Some((id, event)) = committed { + self.take_pass(vec![(id, None)], event.into_iter().collect()); } } @@ -219,7 +233,7 @@ impl StackDialog for PaletteWindow { fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { let heading = script_window::heading(&self.palette.dialog); - let PaletteWindow { palette, drafts, pending, open, .. } = self; + let PaletteWindow { palette, drafts, pending, queued_texts, open, .. } = self; let dialog = shown_dialog(&palette.dialog, pending); let drafts_now = &*drafts; // The body can run twice in a pass (measure, then paint), so the last run's report is @@ -228,7 +242,7 @@ impl StackDialog for PaletteWindow { .modeless() .initial_focus(Initial::Keep) .opened(Bind::bound(open)) - .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true)); + .show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true, queued_texts)); let pass = shown.inner.unwrap_or_default(); let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes @@ -316,7 +330,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { _ => true, }); let before = at_pass.clone(); - let (batch, refused) = drafted(app, &p.dialog, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); + let (batch, refused) = drafted(app, p, &mut at_pass, &mut events, &scope, &pass_scope, &at_scopes); // A refused text keeps every later click and close out of line too. change_refused |= refused; // A text the click or close took leaves its field unless a later one was typed there. @@ -358,13 +372,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { /// events with their scopes, and whether a text was refused. fn drafted( app: &mut VectorcraftApp, - w: &ScriptUiDialog, + p: &ScriptPalette, drafts: &mut BTreeMap, events: &mut Vec, scope: &ScopeHandle, pass_scope: &ScopeHandle, draft_scopes: &BTreeMap, ) -> (Vec<(ScopeHandle, UiEvent)>, bool) { + let w = &p.dialog; let mut refused = false; if let Some(e) = script_window::keep_refused(w, drafts, events) { app.status(e); @@ -375,7 +390,10 @@ fn drafted( if events.iter().any(closing) { changes.extend(events.iter().filter(|e| !closing(e)).cloned()); let existing = changes.len(); - match script_window::commit_texts(w, drafts, &mut changes) { + // A draft that matches its field's text still goes in line when a change of that field + // waits, so the click reads the draft and not the waiting change. + let queued: Vec = app.session.script_palette_changes_waiting().into_iter().filter(|(id, _)| *id == p.id).map(|(_, e)| e).collect(); + match script_window::commit_texts_over(w, drafts, &mut changes, &queued) { Ok(()) => { drop(changes.drain(..existing)); } @@ -465,10 +483,38 @@ pub(crate) fn with_palette(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut } /// Whether a waiting palette event's run can start now ([`vectorcraft_engine::Session::script_palette_can_start`]): -/// it also waits while the last run's print jobs wait to be approved or canceled, and asks for no -/// frame meanwhile. +/// it also waits while the last run's print jobs wait to be approved or canceled, and after a start +/// that failed until the person's next input or a change of the edit state ([`clear_failed_start`]), +/// and asks for no frame meanwhile. pub(crate) fn can_start(app: &VectorcraftApp) -> bool { - app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app) + app.ui.palette_start_failed.is_none_or(|at| at != edit_state(app)) + && app.session.script_palette_can_start() + && !crate::script_runs::waiting_for_print(app) +} + +/// What a failed start may depend on: the documents, whether each has changes, an open drag or +/// undo group, the active one, and the palette events in line. +fn edit_state(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::hash::DefaultHasher::new(); + for d in app.session.documents() { + (d.uid, d.is_dirty(), d.interaction.is_some(), d.undo_group.is_some()).hash(&mut h); + } + app.session.active().map(|d| d.uid).hash(&mut h); + app.session.script_copy_first.hash(&mut h); + app.session.prefs.recovery_off_for_complex.hash(&mut h); + app.session.prefs.recovery_folder.hash(&mut h); + app.session.script_palette_events_waiting().hash(&mut h); + app.session.script_palette_last_ticket().hash(&mut h); + h.finish() +} + +/// Lets a waiting palette event whose start failed try again once the frame carries input, which +/// may have changed the edit that kept it from starting. +pub(crate) fn clear_failed_start(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.ui.palette_start_failed.is_some() && ctx.input(|i| !i.events.is_empty()) { + app.ui.palette_start_failed = None; + } } /// Starts the run of the oldest waiting palette event when no run is going. → whether one started. @@ -485,6 +531,7 @@ pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { None => false, Some(Ok(_)) => true, Some(Err(e)) => { + app.ui.palette_start_failed = Some(edit_state(app)); app.status(e.to_string()); false } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8ff9aaf3ad..fecb678aee 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -724,6 +724,12 @@ pub struct UiState { #[serde(skip)] pub touch_drawing_tool: Option, pub status: String, + /// The edit state in which the last start of a waiting palette event's run failed + /// ([`crate::script_palettes::start_next`]). The event then waits for the person's next input, + /// or for that state to change, before it starts again, and asks for no frame meanwhile. Not + /// saved. + #[serde(skip)] + pub palette_start_failed: Option, /// How many times [`crate::VectorcraftApp::status`] has set `status`, so that work finishing /// later can tell whether the line it started with is still the latest one. Not saved. #[serde(skip)] @@ -1535,6 +1541,7 @@ impl Default for UiState { group_tool: vectorcraft_tools::TOOL_GROUPS.iter().map(|g| g[0].id.to_string()).collect(), touch_drawing_tool: None, status: String::new(), + palette_start_failed: None, status_sets: 0, replace_font_warning: None, last_find: None, diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index ef816ce39e..7efb272535 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -260,6 +260,66 @@ fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() { } } +#[test] +fn a_click_reads_a_typed_text_that_matches_the_field_while_another_change_of_it_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + // The person types the field's text back and clicks before the change to `b` is delivered. + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + let mut logs = Vec::new(); + for _ in 0..10 { + script_runs::poll(&mut app); + if !app.session.script_running() && app.session.script_palette_events_waiting() == 0 { + break; + } + run_to_end(&mut app); + logs.extend(app.session.script_report().unwrap()["log"].as_array().cloned().unwrap_or_default()); + } + run_to_end(&mut app); + if let Some(report) = app.session.script_report() { + logs.extend(report["log"].as_array().cloned().unwrap_or_default()); + } + assert!(logs.contains(&json!("clicked a")), "the click reads the text the person typed: {logs:?}"); + assert!(!logs.contains(&json!("clicked b")), "{logs:?}"); +} + +#[test] +fn focus_loss_commits_a_restored_text_while_another_change_of_the_field_waits() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();", + ); + app.session.script_palette_event(id, UiEvent::Change(1, UiValue::Text("b".into()))).unwrap(); + follow(&mut app); + with_palette(&app, id, |w| w.type_text(1, "a")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + crate::testing::part_frame(&mut app, &ctx, egui::RawInput::default(), |app, ui| { + with_palette(app, id, |w| w.paint(ui)); + }); + assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some("a")); + with_palette(&app, id, |w| w.commit_text(1, "a")).unwrap(); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 1, "focus loss merges the restored text into the waiting change"); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert_eq!(app.session.script_palette_events_waiting(), 2, "the click follows the restored text"); + for _ in 0..2 { + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + } + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked a"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_text_typed_in_two_scopes_goes_to_the_script_in_what_both_allow() { use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; @@ -791,6 +851,68 @@ fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() { assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status); } +#[test] +fn a_click_whose_run_cannot_begin_asks_for_no_frame_until_the_next_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine two\nvar p = new Window('palette'); p.add('button', undefined, 'A').onClick = function () { vc.log('a'); }; \ + p.add('button', undefined, 'B').onClick = function () { vc.log('b'); }; p.show();", + ); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + give(&app, id, UiEvent::Click(1)); + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the second click still waits"); + assert!(!script_palettes::can_start(&app), "the failed start does not retry, nor ask for a frame, on every pass"); + // An event given without the window, as automation gives one, changes what the start depends on. + app.session.script_palette_event(id, UiEvent::Click(1)).unwrap(); + assert!(script_palettes::can_start(&app), "a change of the edit state lets the start try again"); + assert!(!script_palettes::start_next(&mut app)); + assert!(!script_palettes::can_start(&app)); + let ctx = app.ui_ctx.clone().unwrap(); + let input = egui::RawInput { events: vec![egui::Event::PointerGone], ..Default::default() }; + crate::testing::part_frame(&mut app, &ctx, input, |app, ui| script_palettes::clear_failed_start(app, ui.ctx())); + assert!(script_palettes::can_start(&app), "the person's next input lets the click try again"); + app.session.script_copy_first = false; + assert!(script_palettes::start_next(&mut app)); +} + +#[test] +fn a_failed_palette_start_retries_after_recovery_settings_change_without_input() { + let mut app = app(); + let id = shown( + &mut app, + "#targetengine retries\nvar p = new Window('palette'); \ + for (var i = 0; i < 3; i++) { p.add('button', undefined, 'Go ' + i).onClick = function () { vc.log('clicked'); }; } p.show();", + ); + app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + app.session.script_copy_first = true; + for i in 1..=3 { + give(&app, id, UiEvent::Click(i)); + } + follow(&mut app); + assert!(!script_palettes::start_next(&mut app)); + assert_eq!(app.session.script_palette_events_waiting(), 2); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "the failed start asks for no frames"); + app.session.execute("prefs.set", &json!({"key": "recoveryOffForComplex", "value": true})).unwrap(); + assert!(script_palettes::can_start(&app), "automation can change the recovery condition without window input"); + assert!(!script_palettes::start_next(&mut app), "the missing recovery store still prevents a start"); + assert_eq!(app.session.script_palette_events_waiting(), 1); + assert!(!script_palettes::can_start(&app)); + assert_eq!(settled_delay(&mut app), std::time::Duration::MAX, "a repeated failure still asks for no frames"); + app.session.script_copy_first = false; + assert!(script_palettes::can_start(&app), "disabling the recovery prerequisite permits another attempt"); + assert!(script_palettes::start_next(&mut app)); + run_to_end(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/script_print.rs b/crates/ui-egui/src/tests/script_print.rs index a8d5c7c030..d633c3633d 100644 --- a/crates/ui-egui/src/tests/script_print.rs +++ b/crates/ui-egui/src/tests/script_print.rs @@ -277,6 +277,15 @@ fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() { cancel(&mut app, PRINT_KIND); script_runs::poll(&mut app); assert_eq!(app.session.script_palette_events_waiting(), 0, "the click's run starts once the jobs are answered"); + for _ in 0..10_000 { + if !app.session.script_running() { + break; + } + script_runs::poll(&mut app); + } + assert!(!app.session.script_running(), "the click's run ends"); + let report = app.session.script_report().expect("the click's run reports"); + assert_eq!(report["log"], serde_json::json!(["clicked"]), "the click's handler ran: {report}"); } /// Cancel, from anyone, drops the jobs and keeps the run's changes. diff --git a/docs/mcp.md b/docs/mcp.md index e99e34fe86..66b472c21f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4635,7 +4635,9 @@ 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 in order and returns the report of +`ui.inspect`'s `scriptReport`. When a waiting event's run cannot begin in the app, the status bar shows the error, +and the events still in line wait until the next input in the window, another `script.palette.event`, or a change +to a document's unsaved state, drag or undo group, or to the active document. 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. When an open edit cannot be finished before