diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index d5641d9606..e4b3a2df02 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -262,6 +262,23 @@ impl ScopeHandle { Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } + /// Whether this scope allows everything the calling thread's scope allows: its roots are none or + /// the same roots, and its script gate is none or the same gate. + pub(crate) fn covers_current(&self) -> bool { + let here = Self::capture(); + let gate = match (&self.1, &here.1) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (Some(_), None) => false, + }; + let roots = match (self.roots(), here.roots()) { + (None, _) => true, + (Some(a), Some(b)) => Arc::ptr_eq(&a, &b), + (Some(_), None) => false, + }; + gate && roots + } + /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { let Self(scope, gate, exempt) = self; diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 6298ec23d9..104ac1e1d8 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -75,6 +75,9 @@ pub(crate) struct Queued { /// Once its run starts, the SHA-256 the file grants of the palette's script are kept for, which /// the run takes as its own ([`super::files::Setup::own`]). pub(crate) grants: Option, + /// 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 palettes of a session, and the events that wait for a run. @@ -173,15 +176,17 @@ impl Palettes { _ => None, }; let element = control_of(&mut event).and_then(|c| p.dialog.nodes.get(*c)).map(|n| n.id); + let scope = crate::file_access::ScopeHandle::capture(); if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, element)) { slot.event = event; slot.list = list; + slot.scope = scope; 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 }); + self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope }); Ok(Waiting::Added) } @@ -199,11 +204,12 @@ impl Palettes { } /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other - /// engines' palettes keep their places in line. + /// 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 + /// first, preserving the order within each scope. fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { loop { - let list = &self.list; - let at = self.waiting.iter().position(|q| list.iter().any(|p| p.id == q.palette && p.engine == engine))?; + let at = self.oldest_for(engine)?; let q = self.waiting.remove(at)?; if let Some(taken) = self.checked(q) { return Some(taken); @@ -244,7 +250,13 @@ impl Palettes { /// Whether an event waits for a palette of the engine `engine`, which [`Palettes::take_for`] /// would then check and take. pub(crate) fn waits_for(&self, engine: &str) -> bool { - self.waiting.iter().any(|q| self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) + self.oldest_for(engine).is_some() + } + + /// The place of the oldest event for a palette of `engine`, when a palette's `update()` in a + /// run of that engine may take it ([`Palettes::next_of`]). + fn oldest_for(&self, engine: &str) -> Option { + self.waiting.iter().position(|q| q.scope.covers_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine)) } } @@ -257,7 +269,7 @@ fn engine_line(name: &str) -> String { /// The source of a palette's handler run: its engine, and the call that hands the event to the /// palette, which takes it from the run's host. fn handler_source(engine: &str) -> String { - format!("{}\nWindow.__vcPaletteEvent();\n", engine_line(engine)) + format!("{}\nthis[{:?}]();\n", engine_line(engine), vectorcraft_js::scriptui::PALETTE_EVENT_GLOBAL) } /// The event `event` (`click`, `change` or `close`) for `dialog`, from `script.palette.event`'s @@ -406,8 +418,10 @@ impl Session { module: false, actions: Vec::new(), }; + // The run takes the scope of the request that gave the event, within the scope in force now. + let scope = queued.scope.clone().within_current(); self.script_palettes.starting = Some(queued); - let r = self.script_start(request); + let r = scope.run(|| self.script_start(request)); self.script_palettes.starting = None; Some(r) } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 54de688f93..539dcb87fb 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -250,6 +250,81 @@ fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn update_takes_eligible_events_past_deferred_events_in_scope_order() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine eligible\nvar p = new Window('palette'); var stopped = false; \ + var a = p.add('button', undefined, 'A'); var b = p.add('button', undefined, 'B'); \ + var c = p.add('button', undefined, 'C'); var cancel = p.add('button', undefined, 'Cancel'); \ + a.onClick = function () { vc.log('a'); }; b.onClick = function () { vc.log('b'); }; \ + c.onClick = function () { vc.log('c'); }; cancel.onClick = function () { stopped = true; vc.log('cancel'); }; p.show();", + ); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for control in 1..=4 { + let queued = if control % 2 == 1 { + crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(control))) + } else { + crate::file_access::unconfined(|| s.script_palette_event(id, UiEvent::Click(control))) + }; + assert_eq!(queued, Ok(Waiting::Added)); + } + let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine eligible\nwhile (!stopped) p.update(); vc.log('stopped');")); + assert_eq!(report["log"], json!(["b", "cancel", "stopped"])); + assert_eq!(s.script_palette_events_waiting(), 2); + for expected in ["a", "c"] { + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([expected])); + }); + } + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn a_handler_keeps_the_file_access_scope_of_the_request_that_gave_its_event() { + let base = std::env::temp_dir().join(format!("vc-script-palette-scope-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("other")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + std::fs::write(base.join("main/data.txt"), "hello").unwrap(); + let main = base.join("main/main.jsx"); + let path = serde_json::to_string(&base.join("main/data.txt").to_string_lossy()).unwrap(); + std::fs::write( + &main, + format!( + "#targetengine scope\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Read'); var stop = false; \ + b.onClick = function () {{ stop = true; vc.log(new File({path}).exists); }}; p.show();" + ), + ) + .unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + let roots = crate::file_access::AutomationRoots::new(&[&base.join("other")], &[]).unwrap().unwrap(); + // A confined request gives the click; the frame that starts its run later is not confined. + assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); + // An update() in a later unconfined run of the engine leaves the confined click waiting. + let r = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine scope\np.update(); vc.log(stop);")); + assert_eq!(r["log"], json!([false]), "{r}"); + assert_eq!(s.script_palette_events_waiting(), 1); + crate::file_access::unconfined(|| { + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!([false]), "the handler reads inside the roots only"); + // A click the person gives, as the desktop app's pass gives it, goes to an update() at once. + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + let r = run_in_app(&mut s, "#targetengine scope\nstop = false; for (var k = 0; k < 1000 && !stop; k++) p.update(); vc.log(stop);"); + assert_eq!(r["log"].as_array().and_then(|l| l.last()), Some(&json!(true)), "the handler ran in the update() loop: {r}"); + }); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { let mut s = one_doc(); @@ -496,6 +571,45 @@ fn close_fires_on_close_and_frees_the_window() { assert!(s.script_palettes().is_empty(), "close() freed the palette"); } +#[test] +fn update_on_a_removed_group_throws_an_error_the_script_catches_and_keeps_the_engine() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var g = p.add('group'); p.show(); p.remove(g); \ + try { g.update(); } catch (e) { vc.log(e.message); } vc.log('after');", + ) + .unwrap(); + assert_eq!(r["log"], json!(["update: the control was removed from its dialog", "after"]), "{r}"); + assert_eq!(s.script_palettes().len(), 1, "the engine and its palette stay"); +} + +#[test] +fn a_palette_still_takes_events_after_the_script_replaces_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} Window = function () {{}};")).unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + run(&mut s, "#targetengine tools\nWindow = 5;").unwrap(); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert!(closed["ok"].as_bool().unwrap_or(false), "{closed}"); + assert!(s.script_palettes().is_empty(), "the close box reached the palette"); +} + +#[test] +fn closing_a_palette_whose_visible_is_read_only_still_closes_it() { + let mut s = one_doc(); + let r = run( + &mut s, + &format!( + "{TOOLS} Object.defineProperty(p, 'visible', {{value: true, writable: false}}); try {{ p.close(); }} catch (e) {{ vc.log(e.name); }}" + ), + ) + .unwrap(); + assert!(s.script_palettes().is_empty(), "the host closed the palette: {r}"); +} + #[test] fn dropping_the_engine_closes_its_palettes() { let mut s = one_doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ddde9d70a9..143e054e8a 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -46,8 +46,9 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. The document model (`app`, its classes and the enumerations) acts on /// the open documents; `Document.saveAs` and `close` throw "not available yet". const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"), + ("", "$ %vcPaletteEvent File Folder UnitValue Window alert confirm localize prompt toSource"), ("Window.", "__vcPaletteEvent alert confirm length prompt prototype"), + ("%vcPaletteEvent.", "length"), ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show update"), ("Object.prototype.", "reflect toSource"), ("UnitValue.", "baseUnit baseUnit= length prototype"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 1f15cfb006..131db628db 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -94,6 +94,10 @@ use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; use crate::scriptui_resource::{self, Fault, Res, Spec}; use crate::value::{Value, index_key}; +/// The global property, not an identifier, that the run of a palette's handler calls as +/// `this[PALETTE_EVENT_GLOBAL]()` to take its event ([`palette_event`]). +pub const PALETTE_EVENT_GLOBAL: &str = "%vcPaletteEvent"; + /// The most controls a dialog holds, its groups and panels included. pub const MAX_CONTROLS: usize = 512; /// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. @@ -1654,7 +1658,7 @@ fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult if !is_container(&kind) { return Err(i.type_error("update: this is not a ScriptUI window or container")); } - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a container without its window".into())) }; + let win = window_of(i, o, "update")?; let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); update_window(i, win, palette, own)?; Ok(Value::Undefined) @@ -1742,10 +1746,11 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; set_slot(i, win, SHOWN, Value::Bool(false))?; - i.put(win, key("visible"), Value::Bool(false), true)?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + // The host has closed it; a `visible` the script made read-only stays as it is. + i.put(win, key("visible"), Value::Bool(false), false)?; } Ok(()) } @@ -2551,8 +2556,12 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul constructor(i, "Window", window, window_proto)?; let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; - // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + // The run of a palette's handler calls the global one through `this`, under a name that is + // not an identifier: a script can neither replace nor delete it nor declare the name, so + // the palettes still take events after a script assigns to `Window`. let global = i.global; + i.define(global, key(PALETTE_EVENT_GLOBAL), Prop::Data { value: Value::Object(event), flags: 0 })?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. for name in ["alert", "confirm", "prompt"] { if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? && i.is_callable(&value) diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 251afb4e78..2548b08b45 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -18,6 +18,7 @@ use craft::ui::contract::{Bind, ShowContainer as _}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; use craft::ui::runtime::focus::Initial; use egui::Ui; +use vectorcraft_engine::file_access::ScopeHandle; use vectorcraft_engine::script::{ScriptPalette, ScriptUiDialog, UiEvent, UiValue}; use crate::VectorcraftApp; @@ -41,7 +42,7 @@ pub(crate) struct PaletteWindow { /// The events the person gave since the app last took them, each with its control by its id, /// and a list's change with the items the person saw, so a run that changes the palette before /// the app takes them leaves each with its own control. - given: Vec, + given: Vec<(ScopeHandle, Vec)>, open: bool, } @@ -74,7 +75,14 @@ impl PaletteWindow { /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.given.extend(script_window::queued(&self.palette.dialog, &event)); + self.record(std::slice::from_ref(&event)); + } + + fn record(&mut self, events: &[UiEvent]) { + let events: Vec = events.iter().filter_map(|e| script_window::queued(&self.palette.dialog, e)).collect(); + if !events.is_empty() { + self.given.push((ScopeHandle::capture_now(), events)); + } } } @@ -99,7 +107,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, given, open } = self; + let PaletteWindow { palette, drafts, open, .. } = self; let (palette, drafts_now) = (&*palette, &*drafts); // The body can run twice in a pass (measure, then paint), so the last run's report is // applied after the container. @@ -115,14 +123,14 @@ impl StackDialog for PaletteWindow { None => drafts.remove(&id), }; } - let events = pass.events; - given.extend(events.iter().filter_map(|e| script_window::queued(&palette.dialog, e))); + let mut events = pass.events; // The close box gives the script the close; the palette stays open until the script closes // it. if shown.output.closed.is_some() { self.open = true; - self.given.push(Queued::Close); + events.push(UiEvent::Close); } + self.record(&events); None } } @@ -132,6 +140,10 @@ impl StackDialog for PaletteWindow { /// each palette in line. pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); + // A new palette waits while the run waits at a modal dialog, a file dialog or a growth prompt, + // which stays the top dialog and takes its answers. + let s = &app.session; + let modal = s.script_window().is_some() || s.script_dialog().is_some() || s.script_picker().is_some() || s.script_waiting(); let taken = with_host(app, |host, ctx| { let ids: Vec = shown.iter().map(|p| palette_id(p.id)).collect(); for d in host.open_dialogs() { @@ -147,9 +159,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { w.sync(p.clone()); taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.given))); } - None => { + None if !modal => { host.open(PaletteWindow::new(p.clone())); } + None => {} } } taken @@ -159,9 +172,14 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(p) = shown.iter().find(|p| p.id == id) else { continue }; // Each event goes to its control as the palette is now; one whose control is gone, or whose // list's items changed since the person chose, is dropped. - let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); - drafted(app, &p.dialog, &mut drafts, &mut events); - give(app, ctx, p, &mut drafts, events); + let mut change_refused = false; + for (scope, given) in given { + scope.run(|| { + let mut events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); + drafted(app, &p.dialog, &mut drafts, &mut events); + give(app, ctx, p, &mut drafts, events, &mut change_refused); + }); + } with_host(app, |host, _| { if let Some(w) = host.get_mut_by_id::(palette_id(id)) { w.drafts = drafts; @@ -188,10 +206,16 @@ fn drafted(app: &mut VectorcraftApp, w: &ScriptUiDialog, drafts: &mut BTreeMap, events: Vec) { - let mut change_refused = false; +fn give( + app: &mut VectorcraftApp, + ctx: &egui::Context, + p: &ScriptPalette, + drafts: &mut BTreeMap, + events: Vec, + change_refused: &mut bool, +) { for e in events { - if change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { + if *change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) { continue; } let change = match &e { @@ -200,13 +224,21 @@ fn give(app: &mut VectorcraftApp, ctx: &egui::Context, p: &ScriptPalette, drafts }; match app.session.script_palette_event(p.id, e) { // The next frame starts its run. - Ok(_) => ctx.request_repaint(), + Ok(_) => { + if let Some((i, Some(text))) = &change + && let Some(n) = p.dialog.nodes.get(*i) + && drafts.get(&n.id) == Some(text) + { + drafts.remove(&n.id); + } + ctx.request_repaint(); + } Err(error) => { if let Some((i, text)) = change { if let Some((n, text)) = p.dialog.nodes.get(i).zip(text) { drafts.insert(n.id, text); } - change_refused = true; + *change_refused = true; } app.status(error); } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index b2e89992e0..76ed72bf68 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -46,8 +46,7 @@ fn follow(app: &mut VectorcraftApp) { fn frame_delay(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &egui::Context)) -> std::time::Duration { let ctx = app.ui_ctx.clone().unwrap(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| f(app, ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| f(app, ui.ctx())); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) } @@ -91,6 +90,27 @@ fn a_script_dialog_opens_while_a_palette_is_open() { assert!(is_open::(&app)); } +#[test] +fn a_palette_shown_before_a_modal_dialog_does_not_open_above_it() { + let mut app = app(); + start( + &mut app, + "#targetengine tools\nvar p = new Window('palette', 'Tools'); p.add('button', undefined, 'Go'); p.show(); \ + var d = new Window('dialog', 'Ask'); d.add('button', undefined, 'OK'); vc.log(d.show());", + ); + for _ in 0..10_000 { + if app.session.script_window().is_some() { + break; + } + script_runs::poll(&mut app); + } + assert!(app.session.script_window().is_some(), "the run waits at its dialog"); + script_runs::poll(&mut app); + follow(&mut app); + assert!(crate::dialogs::script_window::is_top(&app), "the modal dialog stays on top and takes its answers"); + assert!(!is_open::(&app), "the palette waits for the modal dialog to close"); +} + #[test] fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { let mut app = app(); @@ -105,6 +125,75 @@ fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { assert_eq!(app.session.script_palette_events_waiting(), 0); } +#[test] +fn recorded_palette_events_keep_their_scopes_across_the_engine_handoff() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + for recorded_confined in [false, true] { + let mut app = app(); + let id = shown(&mut app, TOOLS); + if recorded_confined { + confine(Some(&roots), || give(&app, id, UiEvent::Click(1))); + unconfined(|| follow(&mut app)); + } else { + unconfined(|| give(&app, id, UiEvent::Click(1))); + confine(Some(&roots), || follow(&mut app)); + } + unconfined(|| { + start(&mut app, "#targetengine tools\np.update(); vc.log('after');"); + run_to_end(&mut app); + }); + if recorded_confined { + assert_eq!(app.session.script_report().unwrap()["log"], json!(["after"])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"])); + } else { + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked", "after"])); + } + assert_eq!(app.session.script_palette_events_waiting(), 0); + } +} + +#[test] +fn a_recorded_text_change_is_not_given_again_in_a_later_clicks_scope() { + use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined}; + + let mut app = app(); + let id = shown( + &mut app, + "#targetengine texts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \ + var go = p.add('button', undefined, 'Go'); t.onChange = function () { vc.log('changed'); }; \ + go.onClick = function () { vc.log('clicked'); }; p.show();", + ); + let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); + confine(Some(&roots), || { + with_palette(&app, id, |w| { + w.type_text(1, "typed"); + w.give(UiEvent::Change(1, UiValue::Text("typed".into()))); + }) + .unwrap(); + }); + unconfined(|| { + give(&app, id, UiEvent::Click(2)); + follow(&mut app); + start(&mut app, "#targetengine texts\np.update(); vc.log(t.text);"); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked", "a"])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + unconfined(|| { + script_runs::poll(&mut app); + run_to_end(&mut app); + }); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["changed"])); + assert_eq!(app.session.script_palettes()[0].dialog.nodes[1].text, "typed"); +} + #[test] fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { let mut app = app(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 7c51e909ea..8fb119da7f 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -532,8 +532,7 @@ fn a_run_waiting_at_its_dialog_asks_for_no_frames() { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let mut delay = std::time::Duration::ZERO; for _ in 0..5 { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.tick(ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(&mut app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| app.tick(ui.ctx())); delay = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); if delay == std::time::Duration::MAX { break; @@ -552,8 +551,7 @@ fn a_control_request_while_a_run_waits_at_its_dialog_asks_for_the_next_frame() { let ctx = app.ui_ctx.clone().unwrap(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let drain = |app: &mut VectorcraftApp| { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.run_control(ui.ctx())); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| app.run_control(ui.ctx())); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) }; // A new context asks for a frame or two of its own first. @@ -581,8 +579,7 @@ fn a_pass_that_gives_the_dialog_s_queued_event_asks_for_the_next_frame() { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); // One pass of the frame's pump, which gives the run the dialog's next queued event. let pass = |app: &mut VectorcraftApp| { - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |_| script_window::pump(app)); - out.textures_delta.clear(); + let out = crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, _| script_window::pump(app)); out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) }; let mut settled = false; diff --git a/docs/mcp.md b/docs/mcp.md index 431c5022cc..2f8adeb092 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3859,7 +3859,11 @@ the same controls, handlers and limits: `update()` on the palette, or on a group or panel in it, first runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a Cancel button's `onClick` can stop a loop that calls `update()` (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - Those events do not wait for runs of their own. Each one is checked against the palette as the script and the + `update()` takes eligible events oldest first. Events whose recorded file access scopes do not cover the run's + scope stay queued for runs of their own, while later eligible events for the same engine can run. Events within + one scope keep their order. A desktop event keeps the scope in force when the widget records it, even if the app + hands it to the engine under different automation roots. Each deferred event runs in its recorded scope within + the scope in force when its run starts. Each one is checked against the palette as the script and the handlers before it left it, as an event's own run would be, so a click on a control that an earlier handler disabled, hid or removed runs no handler. In the app, an `update()` in the script's own code then pauses the run so the app draws the palette as it is, at most once every 16 ms of the run's time