//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run //! and run one at a time after it, the events that take a waiting one's place, `close()` and the //! close box, the engine's end, and the limits. use std::time::Duration; use serde_json::{Value, json}; use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; use crate::script::scriptui::PALETTE_NEEDS_ENGINE; use crate::script::{DialogAnswer, SETTLE_FAILS, TEST_ELAPSED, UiEvent, Waiting}; use crate::*; /// One open document with one rectangle. fn one_doc() -> Session { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); s } fn run(s: &mut Session, source: &str) -> Result { s.execute("script.run", &json!({"source": source, "name": "p.js"})) } /// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). fn pump(s: &mut Session) -> Option> { for _ in 0..10_000 { if s.script_dialog().is_some() || s.script_window().is_some() { return None; } if let Some(r) = s.script_pump() { return Some(r); } } panic!("the run neither ended nor waited"); } /// Runs `source` in the app to its end. fn run_in_app(s: &mut Session, source: &str) -> Value { s.script_frames = true; assert_eq!(run(s, source).unwrap()["running"], true); pump(s).expect("the run ended").unwrap() } /// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and /// adds a rectangle, and a field (control 2). const TOOLS: &str = "#targetengine tools\n\ var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ var field = p.add('edittext', undefined, ''); \ go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; fn only_palette(s: &Session) -> u64 { let list = s.script_palettes(); assert_eq!(list.len(), 1, "{list:?}"); list[0].id } #[test] fn show_returns_at_once_and_the_palette_stays_after_the_run() { let mut s = one_doc(); let r = run(&mut s, TOOLS).unwrap(); assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); let id = only_palette(&s); let listed = s.execute("script.palettes", &json!({})).unwrap(); assert_eq!(listed["palettes"][0]["engine"], "tools"); assert_eq!(listed["palettes"][0]["title"], "Tools"); assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); assert_eq!(clicked["log"], json!(["click 1"])); assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); assert_eq!(changed["log"], json!(["change abc"])); } #[test] fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { let mut s = one_doc(); run( &mut s, "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ var go = p.add('button', undefined, 'Go'); \ go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", ) .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!(["done"]), "update() in the handler does not throw"); let listed = s.execute("script.palettes", &json!({})).unwrap(); assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); } #[test] fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { TEST_ELAPSED.set(Some(Duration::ZERO)); let mut s = one_doc(); s.script_frames = true; let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; assert_eq!(run(&mut s, source).unwrap()["running"], true); let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); for _ in 0..100 { assert!(s.script_pump().is_none(), "the run pauses at the first update()"); if value(&s) > 0.0 { break; } } let first = value(&s); assert!(first > 0.0); TEST_ELAPSED.set(Some(Duration::from_millis(16))); assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); let second = value(&s); assert!(second > first, "the palette shows the second update()"); assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); assert!(value(&s) > second); TEST_ELAPSED.set(None); } #[test] fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { TEST_ELAPSED.set(Some(Duration::ZERO)); let mut s = one_doc(); s.script_frames = true; let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; assert_eq!(run(&mut s, source).unwrap()["running"], true); for _ in 0..100 { if !s.script_palettes().is_empty() { break; } assert!(s.script_pump().is_none(), "the run pauses at the first update()"); } let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); let report = pump(&mut s).expect("the run ended").unwrap(); assert_eq!(report["log"], json!(["canceled"]), "{report}"); assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); TEST_ELAPSED.set(None); } #[test] fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { TEST_ELAPSED.set(Some(Duration::ZERO)); let mut s = one_doc(); s.script_frames = true; let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ other.onClick = function () { log.push('other'); }; \ p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; assert_eq!(run(&mut s, source).unwrap()["running"], true); for _ in 0..100 { if !s.script_palettes().is_empty() { break; } assert!(s.script_pump().is_none(), "the run pauses at the first update()"); } let id = only_palette(&s); 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)); let report = pump(&mut s).expect("the run ended").unwrap(); assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); TEST_ELAPSED.set(None); } #[test] fn update_in_a_handler_does_not_pause_the_run() { TEST_ELAPSED.set(Some(Duration::ZERO)); let mut s = one_doc(); run_in_app( &mut s, "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ var go = p.add('button', undefined, 'Go'); \ go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", ); let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); assert_eq!(report["log"], json!(["done"])); TEST_ELAPSED.set(None); } #[test] fn many_update_calls_within_one_interval_give_the_controls_once() { TEST_ELAPSED.set(Some(Duration::ZERO)); let mut s = one_doc(); let report = run_in_app( &mut s, "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", ); let calls = report["hostCalls"].as_u64().unwrap(); assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); let bar = s.script_palettes()[0].dialog.nodes[2].value; assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); TEST_ELAPSED.set(None); } #[test] fn a_later_run_in_the_engine_changes_what_the_palette_shows() { let mut s = one_doc(); run(&mut s, TOOLS).unwrap(); let id = only_palette(&s); run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); let listed = s.execute("script.palettes", &json!({})).unwrap(); assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); } #[test] fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", 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("picked")).unwrap(); let base = std::fs::canonicalize(&base).unwrap(); let data = base.join("picked/data.txt"); std::fs::write(&data, "hello").unwrap(); let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); let main = base.join("main/main.jsx"); let source = format!( "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" ); std::fs::write(&main, source).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); for _ in 0..10_000 { if s.script_picker().is_some() { break; } assert!(s.script_pump().is_none(), "the run waits at its file dialog"); } let picked = data.to_string_lossy().into_owned(); assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); pump(&mut s).expect("the run ended").unwrap(); let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); 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!(["hello"])); 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_change_does_not_take_the_place_of_a_waiting_change_given_in_another_scope() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ b.onClick = function () { vc.log('click'); }; p.show();", ); let id = only_palette(&s); let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); crate::file_access::unconfined(|| { assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, change("y")), Ok(Waiting::Added), "the confined change keeps its own place"); }); let report = crate::file_access::unconfined(|| run_in_app(&mut s, "#targetengine merge\np.update();")); assert_eq!(report["log"], json!(["click", "change y"]), "the click stays before the later change of its scope"); assert_eq!(s.script_palette_events_waiting(), 1); } #[test] fn a_change_does_not_merge_past_a_waiting_change_given_in_another_scope() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine merge\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ t.onChange = function () { vc.log('change ' + t.text); }; p.show();", ); let id = only_palette(&s); let roots = crate::file_access::AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); let change = |text: &str| UiEvent::Change(1, crate::script::UiValue::Text(text.into())); assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("x"))), Ok(Waiting::Added)); assert_eq!(crate::file_access::unconfined(|| s.script_palette_event(id, change("y"))), Ok(Waiting::Added)); assert_eq!(crate::file_access::confine(Some(&roots), || s.script_palette_event(id, change("z"))), Ok(Waiting::Added)); assert_eq!(s.script_palette_events_waiting(), 3); let mut logs = Vec::new(); crate::file_access::unconfined(|| { while let Some(started) = s.script_palette_start() { started.unwrap(); logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); } }); assert_eq!(logs, [json!(["change x"]), json!(["change y"]), json!(["change z"])]); assert_eq!(s.script_palette_events_waiting(), 0); } #[test] fn a_click_does_not_take_a_place_ahead_of_a_change_that_waits_after_it() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine ahead\nvar p = new Window('palette'); var t = p.add('edittext', undefined, ''); \ var b = p.add('button', undefined, 'B'); t.onChange = function () { vc.log('change ' + t.text); }; \ b.onClick = function () { vc.log('click ' + t.text); }; p.show();", ); let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Text("y".into()))), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added), "the click waits after the change"); let report = run_in_app(&mut s, "#targetengine ahead\np.update();"); assert_eq!(report["log"], json!(["click ", "change y", "click y"])); } #[test] fn repeated_clicks_and_closes_merge_after_the_last_change_of_their_palette() { use crate::file_access::{AutomationRoots, confine, unconfined}; let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap(); for closing in [UiEvent::Click(1), UiEvent::Close] { for confined_change in [false, true] { let mut s = one_doc(); run_in_app(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('close'); return false; }};")); let id = only_palette(&s); unconfined(|| assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added))); let change = UiEvent::Change(2, crate::script::UiValue::Text("typed".into())); let queued = if confined_change { confine(Some(&roots), || s.script_palette_event(id, change)) } else { unconfined(|| s.script_palette_event(id, change)) }; assert_eq!(queued, Ok(Waiting::Added)); unconfined(|| { assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, closing.clone()), Ok(Waiting::Merged)); }); assert_eq!(s.script_palette_events_waiting(), 3); let mut logs = Vec::new(); unconfined(|| { while let Some(started) = s.script_palette_start() { started.unwrap(); logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); } }); let expected = if matches!(closing, UiEvent::Close) { [json!(["close"]), json!(["change typed"]), json!(["close"])] } else { [json!(["click 1"]), json!(["change typed"]), json!(["click 2"])] }; assert_eq!(logs, expected); } } } #[test] fn update_takes_only_events_whose_roots_grant_what_the_run_s_roots_grant() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine contain\nvar p = new Window('palette'); var b = p.add('button', undefined, 'B'); \ b.onClick = function () { vc.log('clicked'); }; p.show();", ); let id = only_palette(&s); let base = std::fs::canonicalize(std::env::temp_dir()).unwrap(); let inner = base.join(format!("vc-script-palette-contain-{}", std::process::id())); std::fs::create_dir_all(&inner).unwrap(); let wide = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let same = crate::file_access::AutomationRoots::new(&[&base], &[]).unwrap().unwrap(); let narrow = crate::file_access::AutomationRoots::new(&[&inner], &[]).unwrap().unwrap(); assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); let report = crate::file_access::confine(Some(&same), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); assert_eq!(report["log"], json!(["clicked", "after"]), "the same roots made again: {report}"); assert_eq!(s.script_palette_events_waiting(), 0); // A run whose roots lie inside the event's roots would run the handler with less access than // the event was given: the event waits for a run of its own. assert_eq!(crate::file_access::confine(Some(&wide), || s.script_palette_event(id, UiEvent::Click(1))), Ok(Waiting::Added)); let report = crate::file_access::confine(Some(&narrow), || run_in_app(&mut s, "#targetengine contain\np.update(); vc.log('after');")); assert_eq!(report["log"], json!(["after"]), "roots inside the event's roots: {report}"); assert_eq!(s.script_palette_events_waiting(), 1); crate::file_access::confine(Some(&wide), || { 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!(["clicked"])); }); let _ = std::fs::remove_dir(inner); } #[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(); run(&mut s, TOOLS).unwrap(); assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); let listed = s.execute("script.palettes", &json!({})).unwrap(); assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); } #[test] fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ l.onChange = function () { vc.log(String(l.selection)); }; p.show();", ); let id = only_palette(&s); assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); assert!(pump(&mut s).is_none()); let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); assert!(s.script_answer(DialogAnswer::Confirm(true))); pump(&mut s).unwrap().unwrap(); assert!(s.script_palette_start().expect("the change starts its run").is_ok()); let e = pump(&mut s).unwrap().unwrap_err().to_string(); assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); assert!(s.script_palette_start().unwrap().is_ok()); assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } #[test] fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ l.onChange = function () { vc.log(String(l.selection)); }; p.show();", ); let id = only_palette(&s); assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); assert!(pump(&mut s).is_none()); assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); assert!(s.script_answer(DialogAnswer::Confirm(true))); pump(&mut s).unwrap().unwrap(); assert!(s.script_palette_start().expect("the change starts its run").is_ok()); let e = pump(&mut s).unwrap().unwrap_err().to_string(); assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); assert!(pump(&mut s).is_none()); assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); assert!(s.script_answer(DialogAnswer::Confirm(true))); pump(&mut s).unwrap().unwrap(); assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); assert_eq!(s.script_palette_events_waiting(), 0); } #[test] fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", ); let id = only_palette(&s); assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; assert_eq!(run(&mut s, added).unwrap()["running"], true); assert!(pump(&mut s).is_none()); assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); assert!(s.script_answer(DialogAnswer::Confirm(true))); pump(&mut s).unwrap().unwrap(); assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); } #[test] fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { 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"])); assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); 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(); run_in_app(&mut s, TOOLS); let id = only_palette(&s); assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); assert!(pump(&mut s).is_none(), "the run waits at its confirm"); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); assert_eq!(s.script_palette_events_waiting(), 1); assert!(s.script_answer(DialogAnswer::Confirm(true))); assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); assert_eq!(s.script_palette_events_waiting(), 0); } #[test] fn closing_a_palette_id_in_another_engine_keeps_that_palette_s_waiting_events() { let mut s = one_doc(); run_in_app(&mut s, TOOLS); run_in_app(&mut s, "#targetengine other\nvar q = new Window('palette', 'Other'); q.add('button', undefined, 'B'); q.show();"); let tools = s.script_palettes().iter().find(|p| p.engine == "tools").expect("the tools palette").id; assert_eq!(s.script_palette_event(tools, UiEvent::Click(1)), Ok(Waiting::Added)); assert!(!s.script_palettes.close(tools, "other"), "the other engine has no palette with that id"); assert_eq!(s.script_palette_events_waiting(), 1, "the tools palette's click still waits"); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); } #[test] fn double_clicks_while_queued_run_once() { let mut s = one_doc(); run_in_app(&mut s, TOOLS); 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(1)), Ok(Waiting::Merged)); let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); assert_eq!(s.script_palette_events_waiting(), 2); assert!(s.script_answer(DialogAnswer::Confirm(true))); pump(&mut s).unwrap().unwrap(); let mut logs = vec![]; while let Some(started) = s.script_palette_start() { started.unwrap(); logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); } assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); } #[test] fn a_list_change_takes_a_whole_float_as_its_item_index() { let mut s = one_doc(); run( &mut s, "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ l.onChange = function () { vc.log(String(l.selection)); }; p.show();", ) .unwrap(); let id = only_palette(&s); let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); assert_eq!(picked["log"], json!(["b"])); for value in [json!(0.5), json!(-1)] { let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); assert!(given.is_err(), "{value}"); } } #[test] fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { let mut s = one_doc(); run(&mut s, TOOLS).unwrap(); let id = only_palette(&s); s.execute("edit.undoGroup.begin", &json!({})).unwrap(); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("undo group is open"), "{e}"); assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); s.execute("edit.undoGroup.end", &json!({})).unwrap(); let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); } #[test] fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { 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)); // The document has changes, and the session has nowhere to keep a recovery copy of it. s.script_copy_first = true; let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("recovery copy"), "{e}"); assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); s.script_copy_first = false; assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); } #[test] fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_error_and_does_not_wait() { let mut s = one_doc(); run(&mut s, TOOLS).unwrap(); let id = only_palette(&s); SETTLE_FAILS.with(|f| f.set(true)); let r = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})); let waiting = s.script_palette_events_waiting(); SETTLE_FAILS.with(|f| f.set(false)); let e = r.unwrap_err().to_string(); assert!(e.contains("could not be settled"), "{e}"); assert_eq!(waiting, 0, "the refused click does not wait to run later"); let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran"); } #[test] fn a_waiting_event_whose_open_edit_cannot_be_settled_gives_the_app_that_error_and_keeps_waiting() { let mut s = one_doc(); run(&mut s, TOOLS).unwrap(); let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); SETTLE_FAILS.with(|f| f.set(true)); let started = s.script_palette_start(); SETTLE_FAILS.with(|f| f.set(false)); let e = started.expect("the start gives the app its error").unwrap_err().to_string(); assert!(e.contains("could not be settled"), "{e}"); assert_eq!(s.script_palette_events_waiting(), 1, "the click waits for a later start"); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); } /// A palette in the engine `acts` whose button plays the action `Box` of the set `Set`, shown by /// a run given that action, which draws a rectangle; and how many objects the document holds. fn acts_palette(s: &mut Session, handler: &str) -> (u64, fn(&Session) -> usize) { let actions = json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); let source = format!( "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () {{ {handler} }}; p.show();" ); s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); fn objects(s: &Session) -> usize { s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() } (only_palette(s), objects) } #[test] fn a_handler_that_update_runs_plays_the_actions_of_the_run_that_showed_its_palette() { let mut s = one_doc(); let (id, objects) = acts_palette(&mut s, "app.doScript('Box', 'Set'); vc.log('played');"); let before = objects(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); // A later run of the engine, given no actions, takes the click in its update(). let log = run(&mut s, "#targetengine acts\np.update(); try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }").unwrap()["log"].clone(); assert_eq!(log, json!(["played", "there is no action set “Set”"]), "the run's own call plays the run's own actions"); assert_eq!(objects(&s), before + 1, "the handler's action drew its rectangle"); } #[test] fn after_a_handler_that_update_runs_throws_the_run_plays_its_own_actions() { let mut s = one_doc(); let (id, objects) = acts_palette(&mut s, "throw new Error('broken');"); let before = objects(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); let log = run( &mut s, "#targetengine acts\ntry { p.update(); } catch (e) { vc.log(e.message); } \ try { app.doScript('Box', 'Set'); } catch (e) { vc.log(e.message); }", ) .unwrap()["log"] .clone(); assert_eq!(log, json!(["broken", "there is no action set “Set”"])); assert_eq!(objects(&s), before); } #[test] fn after_a_limit_ends_a_handler_that_update_runs_the_refresh_plays_the_run_s_own_actions() { let mut s = one_doc(); let (id, _) = acts_palette(&mut s, "started = true; for (;;) {}"); // The getter records what it plays only once the handler has started, so a read before the // click is taken does not count. run( &mut s, "#targetengine acts\nvar started = false; var after = []; Object.defineProperty(p, 'text', {get: function () { \ var played; try { app.doScript('Box', 'Set'); played = 'palette'; } catch (e) { played = 'own'; } \ if (started) { after.push(played); } return 'P'; }});", ) .unwrap(); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); assert!(run(&mut s, "#targetengine acts\nstarted = false; after = []; p.update();").is_err(), "the handler's loop ends the run"); let log = run(&mut s, "#targetengine acts\nvc.log(after.join(' '));").unwrap()["log"].clone(); let after = log[0].as_str().unwrap_or_default(); assert!(!after.is_empty(), "the palette is refreshed after the handler hit its limit: {log}"); assert!(after.split(' ').all(|p| p == "own"), "the refresh after the limit plays the run's own actions, not the palette's: {log}"); } #[test] fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() { let mut s = one_doc(); let actions = json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]); let source = "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ b.onClick = function () { app.doScript('Box', 'Set'); vc.log('played'); }; p.show();"; s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap(); let id = only_palette(&s); let objects = |s: &Session| s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::(); let before = objects(&s); let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); assert_eq!(clicked["log"], json!(["played"])); assert_eq!(objects(&s), before + 1, "the action drew its rectangle"); } #[test] fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() { let mut s = one_doc(); run(&mut s, TOOLS).unwrap(); let id = only_palette(&s); let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, text("b")), Ok(Waiting::Added), "the text typed after the click waits after it"); assert_eq!(s.script_palette_event(id, text("c")), Ok(Waiting::Merged), "changes with no click between them still merge"); let log = s.script_palette_run_waiting().unwrap()["log"].clone(); assert_eq!(log, json!(["change c"])); assert_eq!(s.script_palette_events_waiting(), 0); } #[test] fn a_point_change_a_palette_getter_makes_after_the_run_is_kept() { let mut s = one_doc(); run( &mut s, "#targetengine points\nvar armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \ Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; app.activeDocument.pathItems[0].pathPoints[0].anchor = [3, 4]; } return 'P'; }}); \ p.show();", ) .unwrap(); let before = format!("{:?}", s.documents()[0].doc.layers); run(&mut s, "#targetengine points\narmed = true;").unwrap(); assert_ne!(format!("{:?}", s.documents()[0].doc.layers), before, "the getter's point change was written"); let anchor = run(&mut s, "vc.log(app.activeDocument.pathItems[0].pathPoints[0].anchor);").unwrap()["log"].clone(); assert_eq!(anchor, json!([[3, 4]])); } #[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, "#targetengine fields\nvar p = new Window('palette'); var one = p.add('edittext', undefined, ''); \ var two = p.add('edittext', undefined, ''); one.onChange = function () { vc.log('change ' + one.text); }; \ two.onChange = function () { vc.log('other ' + two.text); }; p.show();", ) .unwrap(); let id = only_palette(&s); let text = |c: usize, t: &str| UiEvent::Change(c, crate::script::UiValue::Text(t.into())); assert_eq!(s.script_palette_event(id, text(1, "a")), Ok(Waiting::Added)); assert_eq!(s.script_palette_event(id, text(2, "q")), Ok(Waiting::Added)); // The new change takes the place of the first field's change, ahead of the second field's. let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": "z"})).unwrap(); assert_eq!(changed["log"], json!(["change z"]), "the report is the given change's, not the last run's"); assert_eq!(s.script_palette_events_waiting(), 0, "the second field's change ran too"); let texts = run(&mut s, "#targetengine fields\nvc.log(one.text + ' ' + two.text);").unwrap()["log"].clone(); assert_eq!(texts, json!(["z q"])); } #[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())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(&base).unwrap(); let base = std::fs::canonicalize(&base).unwrap(); let first = base.join("first.jsx"); std::fs::write( &first, "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", ) .unwrap(); let second = base.join("second.jsx"); std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); let mut s = one_doc(); for file in [&first, &second] { s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); } let id = only_palette(&s); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("handler"), "{e}"); let report = s.script_report().unwrap(); assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); assert_eq!(report["line"], 4, "{report}"); let _ = std::fs::remove_dir_all(base); } #[test] fn a_palette_from_a_script_without_a_named_engine_is_refused() { let mut s = one_doc(); for source in ["", "#targetengine main\n"] { let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); } assert!(s.script_palettes().is_empty()); } #[test] fn close_fires_on_close_and_frees_the_window() { let mut s = one_doc(); run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); let id = only_palette(&s); let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); assert_eq!(closed["log"], json!(["closing"])); assert!(s.script_palettes().is_empty(), "the close box freed the palette"); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); run(&mut s, TOOLS).unwrap(); let r = run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); assert_eq!(r["log"], json!([1])); assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); run(&mut s, "#targetengine tools\np.close();").unwrap(); 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(); run_in_app(&mut s, TOOLS); run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); let id = s.script_palettes()[0].id; s.script_palette_event(id, UiEvent::Click(1)).unwrap(); s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); assert_eq!(left, ["other"]); assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); assert!(s.script_palette_start().is_none()); } #[test] fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { let mut s = one_doc(); let before = s.documents()[0].history.undo.len(); run( &mut s, "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", ) .unwrap(); let id = only_palette(&s); let art = format!("{:?}", s.documents()[0].doc.layers); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("broken"), "{e}"); assert_eq!(format!("{:?}", s.documents()[0].doc.layers), art, "the failed handler's rectangle was rolled back"); assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler adds no undo step"); assert_eq!(only_palette(&s), id); } #[test] fn a_dialog_in_a_handler_throws_in_the_app() { let mut s = one_doc(); run_in_app( &mut s, "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", ); let id = only_palette(&s); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); assert!(s.script_palette_start().expect("the click starts its run").is_ok()); assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); assert_eq!(only_palette(&s), id); } #[test] fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { let mut s = one_doc(); run( &mut s, "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", ) .unwrap(); let id = only_palette(&s); let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); assert!(e.contains("no answer left"), "{e}"); assert_eq!(only_palette(&s), id, "the palette stays open"); } #[test] fn palettes_and_waiting_events_have_limits() { let mut s = one_doc(); let r = run( &mut s, "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", ) .unwrap(); assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); assert!(s.script_palettes().is_empty()); run_in_app( &mut s, "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", ); let id = only_palette(&s); assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); assert!(pump(&mut s).is_none()); for c in 1..=MAX_WAITING { assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); } let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); assert!(e.contains("this one was not kept"), "{e}"); assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); }