mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Merge pull request #9147 from dotCooCoo/feat/scripts-scriptui-palettes
Scripts: ScriptUI palettes stay open after the run and run their handlers in line
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -151,6 +151,13 @@ impl AutomationRoots {
|
||||
Arc::new(Self { read: both(&self.read, &other.read), write: both(&self.write, &other.write) })
|
||||
}
|
||||
|
||||
/// Whether these roots grant everything `other` grants: each root of `other` lies inside one of
|
||||
/// these roots of the same kind.
|
||||
pub(crate) fn contains(&self, other: &Self) -> bool {
|
||||
let within = |mine: &[Root], theirs: &[Root]| theirs.iter().all(|o| mine.iter().any(|r| inside(&o.resolved, &r.resolved)));
|
||||
within(&self.read, &other.read) && within(&self.write, &other.write)
|
||||
}
|
||||
|
||||
/// The roots for people: `read A, B; write C` (`none` for a kind without any).
|
||||
pub fn describe(&self) -> String {
|
||||
let list = |roots: &[Root]| {
|
||||
@@ -283,6 +290,42 @@ impl ScopeHandle {
|
||||
Self(Some(scope), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get))
|
||||
}
|
||||
|
||||
/// Whether this scope allows everything `other` allows: its roots are none, or each root of
|
||||
/// `other` lies inside one of its roots of the same kind, and its script gate is none or the
|
||||
/// same gate.
|
||||
fn covers(&self, other: &Self) -> bool {
|
||||
let gate = match (&self.1, &other.1) {
|
||||
(None, _) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
||||
(Some(_), None) => false,
|
||||
};
|
||||
gate && self.roots_cover(other)
|
||||
}
|
||||
|
||||
/// Whether this scope's roots are none, or each root of `other` lies inside one of its roots
|
||||
/// of the same kind.
|
||||
fn roots_cover(&self, other: &Self) -> bool {
|
||||
match (self.roots(), other.roots()) {
|
||||
(None, _) => true,
|
||||
(Some(a), Some(b)) => Arc::ptr_eq(&a, &b) || a.contains(&b),
|
||||
(Some(_), None) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this scope allows everything the calling thread's scope allows
|
||||
/// ([`ScopeHandle::covers`]) and the calling thread's roots cover this scope's roots too, so
|
||||
/// work run in the calling thread's scope reaches the same files this scope reaches.
|
||||
pub(crate) fn matches_current(&self) -> bool {
|
||||
let current = Self::capture();
|
||||
self.covers(¤t) && current.roots_cover(self)
|
||||
}
|
||||
|
||||
/// Whether this scope and `other` allow the same: each covers the other, and reads are exempt
|
||||
/// from the gate in both or in neither.
|
||||
pub fn same(&self, other: &Self) -> bool {
|
||||
self.2 == other.2 && self.covers(other) && other.covers(self)
|
||||
}
|
||||
|
||||
/// Run `f` in the captured scope.
|
||||
pub fn run<T>(self, f: impl FnOnce() -> T) -> T {
|
||||
let Self(scope, gate, exempt) = self;
|
||||
|
||||
@@ -399,6 +399,9 @@ pub struct Session {
|
||||
pub(crate) script_style_trail: script::StyleTrail,
|
||||
/// While a slice of a script runs in this session.
|
||||
pub(crate) script_in_run: bool,
|
||||
/// The ScriptUI palettes the named engines' runs showed, and the events that wait for a run
|
||||
/// ([`script::palettes`]).
|
||||
pub(crate) script_palettes: script::palettes::Palettes,
|
||||
/// A script's `file.new` asked for Overprint Preview, which is turned on when the run ends and
|
||||
/// is not turned on when the run fails.
|
||||
pub(crate) overprint_after_run: bool,
|
||||
|
||||
@@ -222,13 +222,18 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
|
||||
if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) {
|
||||
return Err(HostError::Type("doScript's dialogs must be true or false".into()));
|
||||
}
|
||||
let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
// A palette's handler that a palette's `update()` runs plays the actions of the run that showed
|
||||
// the palette, as the handler's own run would.
|
||||
let handler = h.palette_actions.borrow();
|
||||
let actions = handler.as_deref().unwrap_or(&h.actions);
|
||||
let found: Vec<&Playable> = actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect();
|
||||
let p = match found.as_slice() {
|
||||
[p] => *p,
|
||||
[] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[p] => (*p).clone(),
|
||||
[] if !actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))),
|
||||
[] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))),
|
||||
_ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))),
|
||||
};
|
||||
drop(handler);
|
||||
if p.steps.is_empty() {
|
||||
return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name))));
|
||||
}
|
||||
|
||||
@@ -222,6 +222,9 @@ pub(crate) struct Dialogs {
|
||||
approved: Cell<Option<OnYes>>,
|
||||
/// The error that ended the run when an answer could not reach the script.
|
||||
failed: RefCell<Option<RunError>>,
|
||||
/// An answer could not reach the script, so a dialog still open when the run ends is listed
|
||||
/// with the answer `"error"`.
|
||||
answer_failed: Cell<bool>,
|
||||
records: RefCell<Vec<Value>>,
|
||||
record_bytes: Cell<usize>,
|
||||
count: Cell<u64>,
|
||||
@@ -247,6 +250,7 @@ impl Dialogs {
|
||||
on_yes: Cell::new(None),
|
||||
approved: Cell::new(None),
|
||||
failed: RefCell::default(),
|
||||
answer_failed: Cell::new(false),
|
||||
records: RefCell::default(),
|
||||
record_bytes: Cell::new(0),
|
||||
count: Cell::new(0),
|
||||
@@ -295,6 +299,7 @@ impl Dialogs {
|
||||
self.window_waiting.set(false);
|
||||
if let Err(e) = realm.answer(event.data()) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
self.answer_failed.set(true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -447,24 +452,32 @@ impl Dialogs {
|
||||
}
|
||||
|
||||
/// Gives the waiting dialog `answer`, which must be for its kind and, for a prompt, at most
|
||||
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits.
|
||||
/// [`MAX_PROMPT_BYTES`]. → false when it is not, or nothing waits. The report lists the dialog
|
||||
/// with the answer, or with `"error"` when the answer could not reach the script.
|
||||
pub(crate) fn answer(&self, realm: &mut Realm, answer: DialogAnswer) -> bool {
|
||||
let fits = match &answer {
|
||||
DialogAnswer::Prompt(Some(t)) => t.len() <= MAX_PROMPT_BYTES,
|
||||
_ => true,
|
||||
};
|
||||
let mut waiting = self.waiting.borrow_mut();
|
||||
let Some(d) = waiting.as_ref().filter(|d| d.kind == answer.kind() && fits) else { return false };
|
||||
self.record(d, answer.json());
|
||||
*waiting = None;
|
||||
if !waiting.as_ref().is_some_and(|d| d.kind == answer.kind() && fits) {
|
||||
return false;
|
||||
}
|
||||
let Some(d) = waiting.take() else { return false };
|
||||
drop(waiting);
|
||||
let on_yes = self.on_yes.take();
|
||||
// A confirm the app opened returns `undefined` to the call that opened it.
|
||||
let data = if on_yes.is_some() { Data::Undefined } else { answer.data() };
|
||||
if answer == DialogAnswer::Confirm(true) {
|
||||
self.approved.set(on_yes);
|
||||
}
|
||||
if let Err(e) = realm.answer(data) {
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
match realm.answer(data) {
|
||||
Ok(()) => self.record(&d, answer.json()),
|
||||
Err(e) => {
|
||||
self.record(&d, json!("error"));
|
||||
*self.failed.borrow_mut() = Some(e);
|
||||
self.answer_failed.set(true);
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
@@ -493,15 +506,17 @@ impl Dialogs {
|
||||
self.approved.take()
|
||||
}
|
||||
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`.
|
||||
/// The run ends while a dialog waits: the report lists it with the answer `"stop"`, or
|
||||
/// `"error"` when an answer could not reach the script.
|
||||
pub(crate) fn stopped(&self) {
|
||||
self.on_yes.set(None);
|
||||
let answer = if self.answer_failed.replace(false) { json!("error") } else { json!("stop") };
|
||||
if let Some(d) = self.waiting.borrow_mut().take() {
|
||||
self.record(&d, json!("stop"));
|
||||
self.record(&d, answer.clone());
|
||||
}
|
||||
self.window_waiting.set(false);
|
||||
if let Some(showing) = self.window.borrow_mut().take() {
|
||||
self.end_record(&showing, json!("stop"));
|
||||
self.end_record(&showing, answer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -220,6 +220,9 @@ pub(crate) struct Setup {
|
||||
pub script: Option<String>,
|
||||
/// The script's text with the files it includes, whose SHA-256 the grants it keeps are for.
|
||||
pub source: String,
|
||||
/// The SHA-256 the grants are for in place of `source`'s: for the run of a ScriptUI palette's
|
||||
/// handler, the one of the script that showed the palette.
|
||||
pub own: Option<String>,
|
||||
/// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]).
|
||||
pub data_dir: Option<std::path::PathBuf>,
|
||||
/// The code the run's named engine kept from its earlier runs: the SHA-256 of each source
|
||||
@@ -309,7 +312,7 @@ impl Disk {
|
||||
let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned());
|
||||
let web = cfg!(target_arch = "wasm32");
|
||||
let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok());
|
||||
let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes());
|
||||
let own = setup.own.unwrap_or_else(|| vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()));
|
||||
let script = script.map(|p| (p, own.clone()));
|
||||
let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned);
|
||||
let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect();
|
||||
@@ -381,6 +384,11 @@ impl Disk {
|
||||
}
|
||||
}
|
||||
|
||||
/// The SHA-256 the run's grants are for ([`Setup::own`]).
|
||||
pub(crate) fn own(&self) -> &str {
|
||||
&self.own
|
||||
}
|
||||
|
||||
/// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new.
|
||||
fn saw(&mut self, hash: String) -> bool {
|
||||
if self.ran_too_much || self.ran.contains(&hash) || self.own == hash {
|
||||
|
||||
@@ -48,6 +48,11 @@
|
||||
//! that holds the run's host only while the run goes on. An error, a limit or a stop puts the
|
||||
//! documents back and keeps the engine's globals; an internal error drops the engine.
|
||||
//!
|
||||
//! A run in a named engine can show ScriptUI palettes ([`palettes`]), which stay open after it and
|
||||
//! whose events run as runs of their own in that engine, one at a time once no run is going. A run
|
||||
//! of that engine whose own code calls `update()` handles the waiting events inside the run
|
||||
//! instead. A palette closes with its engine.
|
||||
//!
|
||||
//! `Document.print` to a printer prepares its job in memory; the session holds the jobs of a run
|
||||
//! only after the run's changes are kept, for the frontend to send once the person approves them
|
||||
//! ([`printing`]).
|
||||
@@ -58,10 +63,12 @@ pub mod dialogs;
|
||||
pub mod dollar;
|
||||
pub mod dom;
|
||||
pub mod include;
|
||||
pub mod palettes;
|
||||
pub mod printing;
|
||||
pub mod scriptui;
|
||||
|
||||
pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog};
|
||||
pub use palettes::{ScriptPalette, Waiting};
|
||||
pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
@@ -111,6 +118,9 @@ pub const MAX_LOG_LINES: usize = 10_000;
|
||||
pub const MAX_LOG_BYTES: usize = 4 << 20;
|
||||
/// The most bytes of `args` given to one run, as JSON.
|
||||
pub const MAX_ARGS_BYTES: usize = 1 << 20;
|
||||
/// The shortest run time between two ScriptUI `update()` calls that each end the slice, so the app
|
||||
/// draws the window (VectorCraft's own value, about one frame).
|
||||
const UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(16);
|
||||
/// The `vc.run` calls one slice makes before the interface draws again.
|
||||
const SLICE_HOST_CALLS: u32 = 256;
|
||||
/// The bytes that may cross between a script and the host in one run.
|
||||
@@ -848,6 +858,8 @@ struct Host {
|
||||
started: Option<std::time::Instant>,
|
||||
/// The time since [`Host::started`] at which a `$.sleep` ends.
|
||||
wake_at: Cell<Option<std::time::Duration>>,
|
||||
/// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice.
|
||||
drawn_at: Cell<Option<std::time::Duration>>,
|
||||
/// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]).
|
||||
can_wait: Rc<Cell<bool>>,
|
||||
/// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one).
|
||||
@@ -856,6 +868,13 @@ struct Host {
|
||||
dollar: dollar::RunState,
|
||||
/// The run's `args`, which `vc.args` gives, and their size as `vc.args` charges it.
|
||||
args: RefCell<(Data, u64)>,
|
||||
/// The named engine the run is in; `None` for a new realm.
|
||||
engine: Option<String>,
|
||||
/// The script file the run was read from; `None` for a script given as text.
|
||||
file: Option<String>,
|
||||
/// For the run of a palette's handler, the palette's id and the event, until the palette takes
|
||||
/// it ([`palettes`]).
|
||||
palette_event: RefCell<Option<palettes::Queued>>,
|
||||
/// The run's state of the script object model (`app`).
|
||||
dom: dom::State,
|
||||
/// While a slice runs: the documents the interface has open ([`World::docs`] of the run's
|
||||
@@ -863,6 +882,10 @@ struct Host {
|
||||
interface_docs: RefCell<Vec<DocState>>,
|
||||
/// The actions `app.doScript` can play.
|
||||
actions: Vec<actions::Playable>,
|
||||
/// While a palette's `update()` gives a waiting event to its palette, the actions of the run
|
||||
/// that showed that palette, which `app.doScript` plays in place of [`Host::actions`]. A
|
||||
/// palette's `paletteTake` sets them and its `palettePending` clears them.
|
||||
palette_actions: RefCell<Option<Vec<actions::Playable>>>,
|
||||
/// The index of each open document's active artboard as the run starts, by document uid. The
|
||||
/// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it.
|
||||
active_artboards: Vec<(u64, usize)>,
|
||||
@@ -1098,6 +1121,24 @@ impl Host {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A palette's `update()` in the script's own code: in the app, ends the slice so the palette is
|
||||
/// drawn as the script left it, at most once per [`UPDATE_INTERVAL`] of the run's time. →
|
||||
/// whether it does, and the palette's controls are to be given now. Without a clock (the web
|
||||
/// build), and in a run with nobody to draw for, the palette is drawn when the slice or the run
|
||||
/// ends for another reason.
|
||||
fn update_drawn(&self) -> bool {
|
||||
if !self.framed {
|
||||
return false;
|
||||
}
|
||||
let Some(now) = self.elapsed() else { return false };
|
||||
if self.drawn_at.get().is_some_and(|t| now.saturating_sub(t) < UPDATE_INTERVAL) {
|
||||
return false;
|
||||
}
|
||||
self.drawn_at.set(Some(now));
|
||||
self.pause.set(true);
|
||||
true
|
||||
}
|
||||
|
||||
/// The time left of a `$.sleep`, or none when the run is not asleep.
|
||||
fn asleep(&self) -> Option<std::time::Duration> {
|
||||
let wake = self.wake_at.get()?;
|
||||
@@ -1977,6 +2018,7 @@ impl Session {
|
||||
match gone {
|
||||
Some(engine) => {
|
||||
drop(engine);
|
||||
self.keep_engines_palettes();
|
||||
Ok(())
|
||||
}
|
||||
None => Err(EngineError::Other(format!("there is no script engine named {name:?}"))),
|
||||
@@ -2264,6 +2306,7 @@ impl Session {
|
||||
lost
|
||||
});
|
||||
drop(lost);
|
||||
self.keep_engines_palettes();
|
||||
// The job's working copy went with it, with the documents the run opened.
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
@@ -2285,6 +2328,10 @@ impl Session {
|
||||
/// A script can't start while a document holds a drag in progress or an undo group, which its
|
||||
/// one undo step could not take in.
|
||||
fn settle_for_script(&mut self) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
if SETTLE_FAILS.with(Cell::get) {
|
||||
return Err(EngineError::Other("the open edit could not be settled".into()));
|
||||
}
|
||||
self.finish_tool_edit_later()?;
|
||||
if self.active().is_some() {
|
||||
cmd::settle_interaction(self)?;
|
||||
@@ -2297,6 +2344,7 @@ impl Session {
|
||||
|
||||
/// Begins a run of `request`. → the run's name.
|
||||
pub(crate) fn script_start(&mut self, request: Request) -> Result<String> {
|
||||
let palette_event = self.script_palettes.starting.take();
|
||||
self.settle_for_script()?;
|
||||
// In a build where a fault ends the program, every unsaved document has a copy first.
|
||||
if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() {
|
||||
@@ -2418,6 +2466,7 @@ impl Session {
|
||||
script: request.file.clone(),
|
||||
// The text with its included files, so a changed included file asks again.
|
||||
source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()),
|
||||
own: palette_event.as_ref().and_then(|q| q.grants.clone()),
|
||||
data_dir: self.script_data_dir.clone(),
|
||||
engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| {
|
||||
let m = m.borrow();
|
||||
@@ -2435,13 +2484,18 @@ impl Session {
|
||||
kept_maps,
|
||||
started: clock(),
|
||||
wake_at: Cell::new(None),
|
||||
drawn_at: Cell::new(None),
|
||||
can_wait: realm.wait_flag(),
|
||||
eval_strict: Cell::new(None),
|
||||
dollar: dollar::RunState::new(&request.locale),
|
||||
args: RefCell::new((Data::Undefined, 0)),
|
||||
engine: engine.clone(),
|
||||
file: request.file.clone(),
|
||||
palette_event: RefCell::new(palette_event),
|
||||
dom: dom::State::new(self.documents(), heap_bytes),
|
||||
interface_docs: RefCell::new(Vec::new()),
|
||||
actions: request.actions,
|
||||
palette_actions: RefCell::new(None),
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
artboard_picks,
|
||||
run_docs: RefCell::new(
|
||||
@@ -2518,6 +2572,7 @@ impl Session {
|
||||
// error drops a kept one.
|
||||
let keep = !fresh && e.kind != RunErrorKind::Internal;
|
||||
self.return_engine(engine.as_deref(), &link, keep.then_some(realm));
|
||||
self.keep_engines_palettes();
|
||||
let mut report = failure_report(&name, &e, file.as_deref(), &host, 0, 0);
|
||||
close_run(self, &host, &mut report, ending(&e.kind));
|
||||
let message = failure_text(&report);
|
||||
@@ -2666,6 +2721,7 @@ impl Session {
|
||||
let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left));
|
||||
close_run(self, &job.host, &mut report, ending(&e.kind));
|
||||
self.end_job(job, e.kind == RunErrorKind::Internal);
|
||||
self.keep_engines_palettes();
|
||||
self.plugin_events_script_ended(false);
|
||||
raise_ids(self);
|
||||
self.script_stop.clear();
|
||||
@@ -2812,7 +2868,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
pub(crate) const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script";
|
||||
const INVALID_RESULT: &str = "the script left a document that cannot be kept";
|
||||
const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written";
|
||||
const JOB_GONE: &str = "the script's run is no longer available";
|
||||
@@ -3007,6 +3063,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
std::mem::swap(s, &mut *cell.borrow_mut());
|
||||
let scope = job.scope.clone();
|
||||
let realm = &mut job.realm;
|
||||
let named = job.engine.is_some();
|
||||
let host = &job.host;
|
||||
let started = clock();
|
||||
let r = scope.run(|| {
|
||||
@@ -3017,12 +3074,34 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result<std::result:
|
||||
}
|
||||
// Point changes that still wait in the object model are written when the script ends. Between
|
||||
// slices the run's documents are put aside, so they can wait across slices.
|
||||
realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
let progress = realm.advance(SLICE_FUEL).and_then(|progress| {
|
||||
if matches!(progress, Progress::Done(_)) {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
}
|
||||
Ok(progress)
|
||||
})
|
||||
});
|
||||
// A limit that ends a palette's handler which `update()` took leaves the handler's
|
||||
// actions in place of the run's: once the run ends, the refresh's getters play the
|
||||
// run's own.
|
||||
if !matches!(progress, Ok(Progress::Paused)) {
|
||||
*host.palette_actions.borrow_mut() = None;
|
||||
}
|
||||
match progress {
|
||||
// The palettes of a named engine show the controls as the run left them. A getter
|
||||
// the refresh reads may change points, which are written before the run ends.
|
||||
Ok(Progress::Done(v)) if named => realm.refresh_script_ui().and_then(|()| {
|
||||
dom::flush(host).map_err(end_flush_error)?;
|
||||
Ok(Progress::Done(v))
|
||||
}),
|
||||
// A failed run keeps its globals, so its palettes show what it left too; a refresh
|
||||
// that fails as well (the fuel is spent, a stop) leaves them as they were, and the
|
||||
// run's error keeps its place.
|
||||
Err(e) if named && e.kind != RunErrorKind::Internal => {
|
||||
realm.refresh_script_ui_after_error();
|
||||
Err(e)
|
||||
}
|
||||
r => r,
|
||||
}
|
||||
})
|
||||
});
|
||||
if let Some(started) = started {
|
||||
@@ -3099,6 +3178,8 @@ thread_local! {
|
||||
pub(crate) static TEST_RESULT_BYTES: Cell<Option<usize>> = const { Cell::new(None) };
|
||||
/// Tests: makes the next slice panic.
|
||||
pub(crate) static PANIC_IN_SLICE: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes settling the open edits before a run fail.
|
||||
pub(crate) static SETTLE_FAILS: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: makes the next command a member runs past the script fence panic before it runs.
|
||||
pub(crate) static PANIC_WHILE_UNFENCED: Cell<bool> = const { Cell::new(false) };
|
||||
/// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`].
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
//! ScriptUI palettes (`new Window("palette")`, [`vectorcraft_js::scriptui`]): windows a run in a
|
||||
//! named engine (`#targetengine`) shows, which stay open after the run ends and take clicks and
|
||||
//! changes while the person goes on working.
|
||||
//!
|
||||
//! A palette needs a named engine, which keeps its controls and handlers between runs: in a script
|
||||
//! without `#targetengine`, or with `main`, `new Window("palette")` throws. `show()` returns at once.
|
||||
//! Each click, change or close the person gives a palette waits here, and then runs as a run of its
|
||||
//! own in the palette's engine, which takes the mutation lease like any other run: one event at a
|
||||
//! time, oldest first, each starting only once no run is going. A new click, change or close replaces
|
||||
//! the most recent waiting event of the same kind for the same control or palette only when that
|
||||
//! event has the same file access scope. Otherwise the new event waits at the end of the line. A click or
|
||||
//! close replaces an event only after its palette's last waiting change. A palette's `update()` in
|
||||
//! a run of the palette's engine takes the events that wait for that engine's palettes and runs their
|
||||
//! handlers in that run instead ([`Palettes::take_for`]).
|
||||
//!
|
||||
//! A palette closes when its script calls `close()` or the person closes it, unless `onClose`
|
||||
//! returns `false`; when its engine is dropped or ends with an internal error; and with the session.
|
||||
//! Hiding or closing a palette drops the events that wait for it. An error in a handler ends that
|
||||
//! handler's run like any failed run, with its report, and leaves the palette open.
|
||||
//!
|
||||
//! The limits here are VectorCraft's own: [`MAX_PALETTES`] and [`MAX_WAITING`].
|
||||
|
||||
use std::collections::VecDeque;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use super::actions::Playable;
|
||||
use super::scriptui::{self, ScriptUiDialog, UiEvent, UiKind, UiValue};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// The most palettes a session keeps, shown or hidden.
|
||||
pub const MAX_PALETTES: usize = 16;
|
||||
/// The most events that wait for a run, for every palette together.
|
||||
pub const MAX_WAITING: usize = 64;
|
||||
|
||||
/// A palette a run showed.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ScriptPalette {
|
||||
/// Its number in the session, which no other palette of the session has had.
|
||||
pub id: u64,
|
||||
/// The named engine its handlers run in.
|
||||
pub engine: String,
|
||||
/// The script file of the run that first showed it, whose folder its handlers read in; `None`
|
||||
/// for a script given as text.
|
||||
pub file: Option<String>,
|
||||
/// Its controls, as the last `show()`, `add()` or handler left them.
|
||||
pub dialog: ScriptUiDialog,
|
||||
pub visible: bool,
|
||||
/// The SHA-256 the file grants of the script that first showed it are kept for, which its
|
||||
/// handlers' runs keep using: the grants allowed with Always. A grant allowed once is the
|
||||
/// showing run's alone, as for any later run of the script.
|
||||
pub(crate) grants: String,
|
||||
}
|
||||
|
||||
/// What became of an event given to a palette.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Waiting {
|
||||
/// It waits at the end of the line.
|
||||
Added,
|
||||
/// It took the place of a waiting event for the same control.
|
||||
Merged,
|
||||
}
|
||||
|
||||
/// An event given to a palette, waiting for its run or handed to it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct Queued {
|
||||
pub(crate) palette: u64,
|
||||
pub(crate) event: UiEvent,
|
||||
/// The id of the control of a click or a change ([`super::scriptui::UiNode::id`]), by which the
|
||||
/// event finds its control again when a run adds or removes controls before it; `None` for a
|
||||
/// close.
|
||||
pub(crate) element: Option<u64>,
|
||||
/// For a list's change, the list's items as the palette showed them when the event was given and
|
||||
/// the list's revision then ([`super::scriptui::UiNode::revision`]), which the run checks the list
|
||||
/// still has.
|
||||
pub(crate) list: Option<(Vec<String>, f64)>,
|
||||
/// 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<String>,
|
||||
/// The file access scope of the request that gave the event, which its run keeps, narrowed to
|
||||
/// the scope in force when the run starts ([`crate::file_access::ScopeHandle::within_current`]).
|
||||
pub(crate) scope: crate::file_access::ScopeHandle,
|
||||
/// The number of the request that gave the event last: an event that takes the place of a
|
||||
/// waiting one takes a new number.
|
||||
pub(crate) ticket: u64,
|
||||
}
|
||||
|
||||
/// The palettes of a session, and the events that wait for a run.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Palettes {
|
||||
list: Vec<ScriptPalette>,
|
||||
/// The actions `app.doScript` plays in each palette's handlers, by palette id: those of the
|
||||
/// run that first showed the palette.
|
||||
actions: Vec<(u64, Vec<Playable>)>,
|
||||
waiting: VecDeque<Queued>,
|
||||
last_id: u64,
|
||||
/// The number the last event given took ([`Queued::ticket`]).
|
||||
last_ticket: u64,
|
||||
/// The number of the event whose run started last.
|
||||
started_ticket: Option<u64>,
|
||||
/// While [`Session::script_palette_run_waiting`] runs an event, the numbers of the events its
|
||||
/// run takes inside it (`update()`).
|
||||
taken_inline: Option<Vec<u64>>,
|
||||
/// The event the run that starts next handles ([`Session::script_palette_start`]).
|
||||
pub(crate) starting: Option<Queued>,
|
||||
}
|
||||
|
||||
/// Does `event`, for the control whose id is `element`, share the waiting `q`'s place in line: a
|
||||
/// click on the same control, a change of it, or a close?
|
||||
fn same_place(q: &Queued, event: &UiEvent, element: Option<u64>) -> bool {
|
||||
let same_kind = matches!(
|
||||
(&q.event, event),
|
||||
(UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close)
|
||||
);
|
||||
same_kind && q.element == element
|
||||
}
|
||||
|
||||
/// The control of a click or a change.
|
||||
fn control_of(event: &mut UiEvent) -> Option<&mut usize> {
|
||||
match event {
|
||||
UiEvent::Click(c) | UiEvent::Change(c, _) => Some(c),
|
||||
UiEvent::Close => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Palettes {
|
||||
fn find(&mut self, id: u64, engine: &str) -> Option<&mut ScriptPalette> {
|
||||
self.list.iter_mut().find(|p| p.id == id && p.engine == engine)
|
||||
}
|
||||
|
||||
/// `show()`: shows the palette `id` of `engine` with `dialog`, or a new one without `id`, whose
|
||||
/// handlers take the showing run's `actions`. → its id.
|
||||
pub(crate) fn show(
|
||||
&mut self,
|
||||
id: Option<u64>,
|
||||
engine: &str,
|
||||
(file, grants, actions): (Option<String>, String, &[Playable]),
|
||||
dialog: ScriptUiDialog,
|
||||
) -> std::result::Result<u64, String> {
|
||||
if let Some(p) = id.and_then(|id| self.find(id, engine)) {
|
||||
p.dialog = dialog;
|
||||
p.visible = true;
|
||||
return Ok(p.id);
|
||||
}
|
||||
if self.list.len() >= MAX_PALETTES {
|
||||
return Err(format!("show: a session keeps at most {MAX_PALETTES} script palettes; close one first"));
|
||||
}
|
||||
self.last_id += 1;
|
||||
self.list.push(ScriptPalette { id: self.last_id, engine: engine.to_string(), file, dialog, visible: true, grants });
|
||||
if !actions.is_empty() {
|
||||
self.actions.push((self.last_id, actions.to_vec()));
|
||||
}
|
||||
Ok(self.last_id)
|
||||
}
|
||||
|
||||
/// The palette's controls as a handler or `add()` left them. → false when it is closed.
|
||||
pub(crate) fn update(&mut self, id: u64, engine: &str, dialog: ScriptUiDialog) -> bool {
|
||||
let Some(p) = self.find(id, engine) else { return false };
|
||||
p.dialog = dialog;
|
||||
true
|
||||
}
|
||||
|
||||
/// `hide()`. → false when it is closed.
|
||||
pub(crate) fn hide(&mut self, id: u64, engine: &str) -> bool {
|
||||
let Some(p) = self.find(id, engine) else { return false };
|
||||
p.visible = false;
|
||||
self.waiting.retain(|q| q.palette != id);
|
||||
true
|
||||
}
|
||||
|
||||
/// `close()`, once `onClose` allowed it. → false when it was closed already.
|
||||
pub(crate) fn close(&mut self, id: u64, engine: &str) -> bool {
|
||||
let before = self.list.len();
|
||||
self.list.retain(|p| !(p.id == id && p.engine == engine));
|
||||
let closed = self.list.len() != before;
|
||||
if closed {
|
||||
self.waiting.retain(|q| q.palette != id);
|
||||
self.actions.retain(|(p, _)| *p != id);
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Closes the palettes of the engines `keep` does not keep, with their waiting events.
|
||||
fn keep_engines(&mut self, keep: impl Fn(&str) -> bool) {
|
||||
self.list.retain(|p| keep(&p.engine));
|
||||
let open: Vec<u64> = self.list.iter().map(|p| p.id).collect();
|
||||
self.waiting.retain(|q| open.contains(&q.palette));
|
||||
self.actions.retain(|(p, _)| open.contains(p));
|
||||
}
|
||||
|
||||
/// Puts `event` for the shown palette `id` in line, once it is checked against the palette.
|
||||
fn wait(&mut self, id: u64, event: UiEvent) -> std::result::Result<Waiting, String> {
|
||||
let Some(p) = self.list.iter().find(|p| p.id == id) else { return Err(format!("there is no script palette {id}")) };
|
||||
if !p.visible {
|
||||
return Err(format!("the script palette {id} is hidden"));
|
||||
}
|
||||
let mut event = scriptui::check_event(&p.dialog, event)?;
|
||||
let list = match &event {
|
||||
UiEvent::Change(c, UiValue::Index(_)) => p.dialog.nodes.get(*c).map(|n| (n.items.clone(), n.revision)),
|
||||
_ => 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();
|
||||
// Only the most recent event for the same place can merge, in the same file access scope.
|
||||
// A click or close merges only after its palette's last waiting change, and a change only
|
||||
// after its palette's last waiting click or close.
|
||||
let closing = matches!(event, UiEvent::Click(_) | UiEvent::Close);
|
||||
let after = self.waiting.iter().rposition(|q| q.palette == id && matches!(q.event, UiEvent::Change(..)) == closing).map_or(0, |at| at + 1);
|
||||
let at = self.waiting.iter_mut().skip(after).rev().find(|q| q.palette == id && same_place(q, &event, element));
|
||||
let ticket = self.last_ticket.wrapping_add(1);
|
||||
if let Some(slot) = at.filter(|q| q.scope.same(&scope)) {
|
||||
slot.event = event;
|
||||
slot.list = list;
|
||||
slot.ticket = ticket;
|
||||
self.last_ticket = ticket;
|
||||
return Ok(Waiting::Merged);
|
||||
}
|
||||
if self.waiting.len() >= MAX_WAITING {
|
||||
return Err(format!("{MAX_WAITING} script palette events already wait; this one was not kept"));
|
||||
}
|
||||
self.waiting.push_back(Queued { palette: id, event, element, list, grants: None, scope, ticket });
|
||||
self.last_ticket = ticket;
|
||||
Ok(Waiting::Added)
|
||||
}
|
||||
|
||||
/// The oldest waiting event whose palette is still shown, given to its control in the palette
|
||||
/// as the runs since left it, and that palette. An event whose control the palette
|
||||
/// no longer has, or that the control can no longer take ([`scriptui::check_event`]), for
|
||||
/// example because a handler disabled or hid it, is dropped.
|
||||
fn next(&mut self) -> Option<(ScriptPalette, Queued)> {
|
||||
while let Some(q) = self.waiting.pop_front() {
|
||||
if let Some(taken) = self.checked(q) {
|
||||
return Some(taken);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// first, preserving the order within each scope.
|
||||
fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> {
|
||||
loop {
|
||||
let at = self.oldest_for(engine)?;
|
||||
let q = self.waiting.remove(at)?;
|
||||
if let Some(taken) = self.checked(q) {
|
||||
return Some(taken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)> {
|
||||
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?)?;
|
||||
}
|
||||
// A list's change whose list a run changed since goes to its run, which ends with the
|
||||
// error that says so, when the list can still take a change: the choice is checked
|
||||
// without its item, which the list may no longer have.
|
||||
let list_changed = match (&q.event, &q.list) {
|
||||
(UiEvent::Change(c, UiValue::Index(_)), Some((_, revision))) => {
|
||||
p.dialog.nodes.get(*c).is_some_and(|n| n.revision != *revision).then_some(*c)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(c) = list_changed {
|
||||
scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).ok()?;
|
||||
} else {
|
||||
q.event = scriptui::check_event(&p.dialog, q.event).ok()?;
|
||||
}
|
||||
Some((p.clone(), q))
|
||||
}
|
||||
|
||||
/// The oldest waiting event for a palette of the engine `engine`, which a palette's `update()`
|
||||
/// in a run of that engine takes and hands to the palette at once ([`Palettes::next_of`]), with
|
||||
/// the actions its handlers play: those of the run that first showed its palette.
|
||||
pub(crate) fn take_for(&mut self, engine: &str) -> Option<(Queued, Vec<Playable>)> {
|
||||
let q = self.next_of(engine).map(|(_, q)| q)?;
|
||||
if let Some(taken) = self.taken_inline.as_mut() {
|
||||
taken.push(q.ticket);
|
||||
}
|
||||
let actions = self.actions.iter().find(|(id, _)| *id == q.palette).map(|(_, a)| a.clone()).unwrap_or_default();
|
||||
Some((q, actions))
|
||||
}
|
||||
|
||||
/// 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.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`]): the run reaches the same files the
|
||||
/// event's scope reaches, so the handler runs with neither more nor less access than in a run
|
||||
/// of its own. Any other event waits for a run of its own.
|
||||
fn oldest_for(&self, engine: &str) -> Option<usize> {
|
||||
self.waiting.iter().position(|q| q.scope.matches_current() && self.list.iter().any(|p| p.id == q.palette && p.engine == engine))
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` in a `#targetengine` line, quoted with a quote it does not hold.
|
||||
fn engine_line(name: &str) -> String {
|
||||
let quote = if name.contains('"') { '\'' } else { '"' };
|
||||
format!("#targetengine {quote}{name}{quote}")
|
||||
}
|
||||
|
||||
/// 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!("{}\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
|
||||
/// `control` (a control's index, or its name or text) and `value` (an edit field's text, a slider's
|
||||
/// number, or a list's item index or null).
|
||||
pub(crate) fn parse_event(
|
||||
dialog: &ScriptUiDialog,
|
||||
event: &str,
|
||||
control: Option<&Value>,
|
||||
value: Option<&Value>,
|
||||
) -> std::result::Result<UiEvent, String> {
|
||||
if event == "close" {
|
||||
if control.is_some() || value.is_some() {
|
||||
return Err("a close takes no `control` and no `value`".into());
|
||||
}
|
||||
return Ok(UiEvent::Close);
|
||||
}
|
||||
let id = match control {
|
||||
Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?,
|
||||
Some(Value::String(s)) => dialog.find(s).ok_or_else(|| format!("the palette has no control named {}", super::dialogs::cut_to(s, 64)))?,
|
||||
_ => return Err("`control` must be a control's index, name or text".into()),
|
||||
};
|
||||
let list = dialog.nodes.get(id).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox));
|
||||
let event = match (event, value) {
|
||||
("click", None) => UiEvent::Click(id),
|
||||
("click", Some(_)) => return Err("a click takes no `value`".into()),
|
||||
("change", Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())),
|
||||
("change", Some(Value::Number(v))) if list => match scriptui::list_index(v) {
|
||||
Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))),
|
||||
None => return Err("a list's `value` must be an item index or null".into()),
|
||||
},
|
||||
("change", Some(Value::Number(v))) => UiEvent::Change(id, UiValue::Number(v.as_f64().unwrap_or(f64::NAN))),
|
||||
("change", Some(Value::Null)) if list => UiEvent::Change(id, UiValue::Index(None)),
|
||||
("change", _) => return Err("a change's `value` must be a string, a number, or for a list an item index or null".into()),
|
||||
_ => return Err("`event` must be click, change or close".into()),
|
||||
};
|
||||
scriptui::check_event(dialog, event)
|
||||
}
|
||||
|
||||
/// A palette as `script.palettes` lists it.
|
||||
pub(crate) fn palette_json(p: &ScriptPalette) -> Value {
|
||||
let controls: Vec<Value> = p
|
||||
.dialog
|
||||
.nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(1)
|
||||
.map(|(i, n)| {
|
||||
let mut c = Map::new();
|
||||
c.insert("index".into(), json!(i));
|
||||
c.insert("kind".into(), json!(kind_id(n.kind)));
|
||||
c.insert("name".into(), json!(n.name));
|
||||
c.insert("text".into(), json!(n.text));
|
||||
c.insert("enabled".into(), json!(n.enabled));
|
||||
c.insert("visible".into(), json!(n.visible));
|
||||
match n.kind {
|
||||
UiKind::CheckBox | UiKind::RadioButton => {
|
||||
c.insert("value".into(), json!(n.checked));
|
||||
}
|
||||
UiKind::Slider | UiKind::ProgressBar => {
|
||||
c.insert("value".into(), json!(n.value));
|
||||
}
|
||||
UiKind::DropDownList | UiKind::ListBox => {
|
||||
c.insert("items".into(), json!(n.items));
|
||||
c.insert("selection".into(), json!(n.selection));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Value::Object(c)
|
||||
})
|
||||
.collect();
|
||||
json!({"id": p.id, "engine": p.engine, "title": p.dialog.title(), "visible": p.visible, "controls": controls})
|
||||
}
|
||||
|
||||
fn kind_id(kind: UiKind) -> &'static str {
|
||||
match kind {
|
||||
UiKind::Dialog => "palette",
|
||||
UiKind::Group => "group",
|
||||
UiKind::Panel => "panel",
|
||||
UiKind::StaticText => "statictext",
|
||||
UiKind::EditText => "edittext",
|
||||
UiKind::Button => "button",
|
||||
UiKind::CheckBox => "checkbox",
|
||||
UiKind::RadioButton => "radiobutton",
|
||||
UiKind::DropDownList => "dropdownlist",
|
||||
UiKind::ListBox => "listbox",
|
||||
UiKind::Slider => "slider",
|
||||
UiKind::ProgressBar => "progressbar",
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The palettes the named engines' runs showed and have not closed, shown or hidden, in the
|
||||
/// order they were first shown.
|
||||
pub fn script_palettes(&self) -> &[ScriptPalette] {
|
||||
&self.script_palettes.list
|
||||
}
|
||||
|
||||
/// How many palette events wait for a run.
|
||||
pub fn script_palette_events_waiting(&self) -> usize {
|
||||
self.script_palettes.waiting.len()
|
||||
}
|
||||
|
||||
/// 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
|
||||
.waiting
|
||||
.iter()
|
||||
.filter(|q| matches!(q.event, UiEvent::Change(..)))
|
||||
.filter_map(|q| q.element.map(|e| (q.palette, e)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether [`Session::script_palette_start`] can start a waiting event's run now: an event
|
||||
/// waits, no run is going, and no undo group is open, which a run cannot start in, nor a drag
|
||||
/// in a document other than the active one. A drag in the active document is not counted,
|
||||
/// since starting the run settles it.
|
||||
pub fn script_palette_can_start(&self) -> bool {
|
||||
!self.script_palettes.waiting.is_empty() && !self.script_running() && !self.palette_run_blocked()
|
||||
}
|
||||
|
||||
/// Whether an open edit keeps a palette event's run from starting: an undo group, the
|
||||
/// session's or a document's, or a drag in a document other than the active one (starting the
|
||||
/// run settles a drag in the active one).
|
||||
pub(crate) fn palette_run_blocked(&self) -> bool {
|
||||
let active = self.active().map(|d| d.uid);
|
||||
self.undo_group_open() || self.docs.iter().any(|d| d.interaction.is_some() && Some(d.uid) != active)
|
||||
}
|
||||
|
||||
/// Whether an undo group is open, the session's or a document's, which a run cannot start in.
|
||||
pub(crate) fn undo_group_open(&self) -> bool {
|
||||
self.explicit_undo_group.is_some() || self.docs.iter().any(|d| d.undo_group.is_some())
|
||||
}
|
||||
|
||||
/// Puts `event` for the shown palette `id` in line, to run in its engine once no run is going
|
||||
/// ([`Session::script_palette_start`]). → an error when there is no such shown palette, it
|
||||
/// cannot take the event ([`scriptui::check_event`]), or [`MAX_WAITING`] events already wait.
|
||||
pub fn script_palette_event(&mut self, id: u64, event: UiEvent) -> std::result::Result<Waiting, String> {
|
||||
self.script_palettes.wait(id, event)
|
||||
}
|
||||
|
||||
/// Starts the run of the oldest waiting palette event, when no run is going. → `None` when a
|
||||
/// 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<Result<String>> {
|
||||
if self.script_running() || 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.
|
||||
if let Err(e) = self.settle_for_script() {
|
||||
return Some(Err(e));
|
||||
}
|
||||
let (palette, mut queued) = self.script_palettes.next()?;
|
||||
self.script_palettes.started_ticket = Some(queued.ticket);
|
||||
queued.grants = Some(palette.grants.clone());
|
||||
let title = palette.dialog.title();
|
||||
let name = if title.is_empty() { "palette".to_string() } else { super::dialogs::cut_to(title, super::dialogs::MAX_TITLE_BYTES).to_string() };
|
||||
let locale = super::dollar::ui_locale(self.ui_language.as_deref().unwrap_or(&self.prefs.interface_language));
|
||||
let actions = self.script_palettes.actions.iter().find(|(id, _)| *id == palette.id).map(|(_, a)| a.clone()).unwrap_or_default();
|
||||
let request = super::Request {
|
||||
name,
|
||||
name_given: true,
|
||||
file: palette.file.clone(),
|
||||
checked_real: None,
|
||||
source: handler_source(&palette.engine),
|
||||
args: Map::new(),
|
||||
fuel: super::DEFAULT_FUEL,
|
||||
locale,
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions,
|
||||
};
|
||||
// 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 = scope.run(|| self.script_start(request));
|
||||
self.script_palettes.starting = None;
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// Closes the palettes whose engine the session no longer keeps.
|
||||
pub(crate) fn keep_engines_palettes(&mut self) {
|
||||
let names: Vec<String> = self.script_engines().into_iter().map(|(name, ..)| name).collect();
|
||||
self.script_palettes.keep_engines(|e| names.iter().any(|n| n == e));
|
||||
}
|
||||
|
||||
/// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn,
|
||||
/// in their order in line. → the report of the event just given, wherever it waited, or an
|
||||
/// error when it was dropped without a run. An event whose run could not begin, for example
|
||||
/// because the recovery copies could not be saved, ends this, and the events after it keep
|
||||
/// waiting: with its error, or with the given event's result when that one has run. An open
|
||||
/// edit that cannot be settled ends this with its error, and the given event no longer waits.
|
||||
pub(crate) fn script_palette_run_waiting(&mut self) -> Result<Value> {
|
||||
let want = self.script_palettes.last_ticket;
|
||||
let mut mine = None;
|
||||
loop {
|
||||
if !self.script_running()
|
||||
&& !self.script_palettes.waiting.is_empty()
|
||||
&& let Err(e) = self.settle_for_script()
|
||||
{
|
||||
// A caller that gives the event again then does not give it twice.
|
||||
self.script_palettes.waiting.retain(|q| q.ticket != want);
|
||||
return mine.unwrap_or(Err(e));
|
||||
}
|
||||
let Some(started) = self.script_palette_start() else { break };
|
||||
// A later event whose run cannot begin leaves the given event's result as it is.
|
||||
if let Err(e) = started {
|
||||
return mine.unwrap_or(Err(e));
|
||||
}
|
||||
self.script_palettes.taken_inline = Some(Vec::new());
|
||||
let r = self.script_run_to_end();
|
||||
// A run of the same engine can take the event while it runs (`update()`): its report
|
||||
// is then the event's.
|
||||
let inline = self.script_palettes.taken_inline.take().is_some_and(|t| t.contains(&want));
|
||||
if mine.is_none() && (self.script_palettes.started_ticket == Some(want) || inline) {
|
||||
mine = Some(r);
|
||||
}
|
||||
}
|
||||
mine.unwrap_or_else(|| {
|
||||
Err(EngineError::Other("the script palette event was dropped without a run: its palette or control can no longer take it".into()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run
|
||||
//! gives when it shows one, checked and laid out here before the app draws it, and the events the
|
||||
//! person or `script.run`'s `answers` give back.
|
||||
//! person or `script.run`'s `answers` give back. A palette (`new Window("palette")`) is described
|
||||
//! and laid out the same way; [`super::palettes`] keeps it and its events, and the host functions
|
||||
//! `palette`, `paletteShow`, `paletteUpdate`, `paletteHide`, `paletteClose` and `paletteEvent` here
|
||||
//! act for a run in a named engine, and throw [`PALETTE_NEEDS_ENGINE`] in any other.
|
||||
//!
|
||||
//! A description lists the dialog first and each control after the container that holds it. It is
|
||||
//! refused with an error thrown at `show()` when a control's container comes after it or is not a
|
||||
@@ -36,6 +39,7 @@ use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError};
|
||||
pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES};
|
||||
|
||||
use super::Host;
|
||||
use super::palettes::Queued;
|
||||
|
||||
/// The largest size or place, in pixels, of a dialog or a control in it.
|
||||
pub const MAX_EXTENT: f32 = 8192.0;
|
||||
@@ -143,6 +147,9 @@ pub struct UiNode {
|
||||
/// list from one that holds the same texts again.
|
||||
pub items_revision: u64,
|
||||
pub selection: Option<usize>,
|
||||
/// How many times a list's items were added or removed, which a palette's waiting change of
|
||||
/// the list is checked against.
|
||||
pub revision: f64,
|
||||
pub multiline: bool,
|
||||
pub readonly: bool,
|
||||
pub rect: UiRect,
|
||||
@@ -208,6 +215,12 @@ impl ScriptUiDialog {
|
||||
};
|
||||
by(true).or_else(|| by(false))
|
||||
}
|
||||
|
||||
/// The index in [`Self::nodes`] of the control whose id ([`UiNode::id`]) is `id`, if the dialog
|
||||
/// has one.
|
||||
pub fn index_of(&self, id: u64) -> Option<usize> {
|
||||
self.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// A value a control takes in a change.
|
||||
@@ -516,6 +529,7 @@ pub fn parse(d: &Data) -> Result<ScriptUiDialog, HostError> {
|
||||
items,
|
||||
items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64),
|
||||
selection,
|
||||
revision: number(field(f, "revision")).unwrap_or(0.0),
|
||||
multiline: flag("multiline"),
|
||||
readonly: flag("readonly"),
|
||||
rect: UiRect::default(),
|
||||
@@ -709,7 +723,132 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result<Data, HostError>
|
||||
|
||||
/// Adds `Window` to the realm, for the run `link` holds.
|
||||
pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> {
|
||||
realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))])
|
||||
realm.define_script_ui(vec![
|
||||
("open".into(), function(link, open)),
|
||||
("wait".into(), function(link, wait)),
|
||||
("end".into(), function(link, end)),
|
||||
("palette".into(), function(link, palette)),
|
||||
("paletteShow".into(), function(link, palette_show)),
|
||||
("paletteUpdate".into(), function(link, palette_update)),
|
||||
("paletteHide".into(), function(link, palette_hide)),
|
||||
("paletteClose".into(), function(link, palette_close)),
|
||||
("paletteEvent".into(), function(link, palette_event)),
|
||||
("paletteTake".into(), function(link, palette_take)),
|
||||
("palettePending".into(), function(link, palette_pending)),
|
||||
("paletteDraw".into(), function(link, palette_draw)),
|
||||
])
|
||||
}
|
||||
|
||||
/// The error of `new Window("palette")` in a run without a named engine.
|
||||
pub const PALETTE_NEEDS_ENGINE: &str = "Window: a palette needs a named engine, which keeps its controls and handlers after the script ends; put a #targetengine line with a name other than main at the top of the script";
|
||||
|
||||
/// The named engine of the run, for a palette.
|
||||
fn palette_engine(host: &Host) -> Result<&str, HostError> {
|
||||
host.engine.as_deref().ok_or_else(|| HostError::Error(PALETTE_NEEDS_ENGINE.into()))
|
||||
}
|
||||
|
||||
/// A palette's id as a script holds it: a whole number from 1, or none.
|
||||
fn palette_id(d: Option<&Data>) -> Option<u64> {
|
||||
match d {
|
||||
Some(Data::Number(n)) if *n >= 1.0 && n.fract() == 0.0 && *n < 9.0e15 => Some(*n as u64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `new Window("palette")`: refused in a run without a named engine.
|
||||
fn palette(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
palette_engine(host)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A palette's `show()`, with its description and its id (none the first time). → its id.
|
||||
fn palette_show(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let dialog = described(host, args)?;
|
||||
let id = palette_id(args.get(1));
|
||||
let grants = host.disk.borrow().own().to_string();
|
||||
let shown = host.session.borrow_mut().script_palettes.show(id, &engine, (host.file.clone(), grants, &host.actions), dialog);
|
||||
shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range)
|
||||
}
|
||||
|
||||
/// The palette `id`'s controls as a handler, `add()` or `update()` left them.
|
||||
fn palette_update(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let dialog = described(host, args)?;
|
||||
if let Some(id) = palette_id(args.get(1)) {
|
||||
host.session.borrow_mut().script_palettes.update(id, &engine, dialog);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// A palette's `update()` in the script's own code asks whether the app draws the palette now
|
||||
/// ([`Host::update_drawn`]). → `true` when it does, and the script then gives the palette's
|
||||
/// controls through `paletteUpdate`.
|
||||
fn palette_draw(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
palette_engine(host)?;
|
||||
Ok(Data::Bool(host.update_drawn()))
|
||||
}
|
||||
|
||||
/// A palette's `update()` takes the oldest event the person gave a palette of the run's engine,
|
||||
/// which no run has handled yet, as `paletteEvent` gives it; `null` when none waits. Until the next
|
||||
/// `palettePending`, `app.doScript` plays the actions of the run that showed the event's palette.
|
||||
fn palette_take(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
let taken = host.session.borrow_mut().script_palettes.take_for(&engine);
|
||||
let (data, actions) = match taken {
|
||||
Some((queued, actions)) => (event_data(queued), Some(actions)),
|
||||
None => (Data::Null, None),
|
||||
};
|
||||
*host.palette_actions.borrow_mut() = actions;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Whether an event waits for a palette of the run's engine, which a palette's `update()` asks
|
||||
/// before it gives the palettes' controls and takes the event with `paletteTake`, and once more
|
||||
/// after the event's handlers end. `app.doScript` then plays the run's own actions again.
|
||||
fn palette_pending(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
*host.palette_actions.borrow_mut() = None;
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
Ok(Data::Bool(host.session.borrow().script_palettes.waits_for(&engine)))
|
||||
}
|
||||
|
||||
fn palette_hide(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
if let Some(id) = palette_id(args.first()) {
|
||||
host.session.borrow_mut().script_palettes.hide(id, &engine);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn palette_close(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
let engine = palette_engine(host)?.to_string();
|
||||
if let Some(id) = palette_id(args.first()) {
|
||||
host.session.borrow_mut().script_palettes.close(id, &engine);
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The event a palette handler's run is for, once: `{palette, event, id, value, element, items}`,
|
||||
/// as `show()` takes a dialog's event with the palette's id added, the id of a click's or a
|
||||
/// change's control (`element`, [`UiNode::id`]), which the run finds the control by, and for a
|
||||
/// list's change the items the palette showed; `null` for any other run, and after the first call.
|
||||
fn palette_event(host: &Host, _: &[Data]) -> Result<Data, HostError> {
|
||||
let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) };
|
||||
Ok(event_data(queued))
|
||||
}
|
||||
|
||||
/// The waiting event `queued` as a script takes it ([`palette_event`]).
|
||||
fn event_data(queued: Queued) -> Data {
|
||||
let Data::Object(mut fields) = queued.event.data() else { return Data::Null };
|
||||
fields.push(("palette".into(), Data::Number(queued.palette as f64)));
|
||||
if let Some(element) = queued.element {
|
||||
fields.push(("element".into(), Data::Number(element as f64)));
|
||||
}
|
||||
if let Some((items, revision)) = queued.list {
|
||||
fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect())));
|
||||
fields.push(("revision".into(), Data::Number(revision)));
|
||||
}
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
fn described(host: &Host, args: &[Data]) -> Result<ScriptUiDialog, HostError> {
|
||||
|
||||
@@ -198,6 +198,7 @@ impl Session {
|
||||
script_high_water: Default::default(),
|
||||
script_style_trail: Default::default(),
|
||||
script_in_run: false,
|
||||
script_palettes: Default::default(),
|
||||
overprint_after_run: false,
|
||||
script_unfenced: None,
|
||||
script_printers: None,
|
||||
|
||||
@@ -195,6 +195,7 @@ mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_modules;
|
||||
mod script_palettes;
|
||||
mod script_print;
|
||||
mod script_raster_capture;
|
||||
mod script_run;
|
||||
|
||||
@@ -200,6 +200,30 @@ fn prompt_cancel_returns_null() {
|
||||
assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!([true]));
|
||||
}
|
||||
|
||||
/// A prompt's answer that the engine's nearly full heap cannot hold ends the run, and the report
|
||||
/// lists the prompt with the answer `"error"`, not the text that did not reach the script.
|
||||
#[test]
|
||||
fn a_prompt_answer_that_cannot_reach_the_script_is_listed_as_an_error() {
|
||||
use crate::script::TEST_ENGINE_HEAP;
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(Some(8 << 20)));
|
||||
let mut s = one_doc();
|
||||
let filled = headless(
|
||||
&mut s,
|
||||
"#targetengine full\nvar head = null, c = 'x';\nwhile (c.length < 4096) c += c;\nfor (var i = 0; ; i++) head = {s: c + i, n: head};",
|
||||
json!([]),
|
||||
);
|
||||
framed(&mut s, "#targetengine full\nvar a = prompt('Name', '');");
|
||||
let waited = pump(&mut s).is_none();
|
||||
let answered = s.script_answer(DialogAnswer::Prompt(Some("x".repeat(dialogs::MAX_PROMPT_BYTES))));
|
||||
let ended = pump(&mut s);
|
||||
let report = s.script_report();
|
||||
TEST_ENGINE_HEAP.with(|h| h.set(None));
|
||||
assert!(filled.unwrap_err().to_string().contains("Heap"));
|
||||
assert!(waited && answered);
|
||||
assert!(ended.unwrap().is_err(), "the answer did not fit in the heap");
|
||||
assert_eq!(report.unwrap()["dialogs"][0]["answer"], "error");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dialog_loop_stops_or_exhausts() {
|
||||
let mut s = one_doc();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -62,9 +62,10 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"),
|
||||
("", "$ %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"),
|
||||
("UnitValue.prototype.", "as baseUnit baseUnit= constructor convert toString type type= value value="),
|
||||
|
||||
@@ -730,6 +730,11 @@ impl Interp {
|
||||
!self.frames.is_empty() || self.promises.draining
|
||||
}
|
||||
|
||||
/// Whether promise jobs wait to run.
|
||||
pub(crate) fn jobs_waiting(&self) -> bool {
|
||||
!self.promises.queue.is_empty()
|
||||
}
|
||||
|
||||
/// Runs the queued jobs, and the jobs they queue, until the queue is empty, after the script's
|
||||
/// code ended with `completion`, which this gives back.
|
||||
pub(crate) fn drain_jobs(&mut self, completion: Value) -> JsResult<Value> {
|
||||
@@ -887,9 +892,10 @@ impl Interp {
|
||||
}
|
||||
|
||||
/// The promises the run rejected that still have no handler, the first [`MAX_REPORTED`] of
|
||||
/// them described, and how many there are; the run's notes are cleared.
|
||||
pub(crate) fn take_unhandled(&mut self) -> (Vec<crate::Rejection>, usize) {
|
||||
let rejected = std::mem::take(&mut self.promises.rejected);
|
||||
/// them described, and how many there are. The run's notes stay until the next run starts, so a
|
||||
/// later call leaves out a promise that has a handler since.
|
||||
pub(crate) fn unhandled(&mut self) -> (Vec<crate::Rejection>, usize) {
|
||||
let rejected = self.promises.rejected.clone();
|
||||
let mut out = Vec::new();
|
||||
let mut attribution = Vec::new();
|
||||
let mut count = 0;
|
||||
|
||||
+48
-1
@@ -489,7 +489,7 @@ impl Realm {
|
||||
}
|
||||
match result {
|
||||
Ok(v) => {
|
||||
self.rejections = interp.take_unhandled();
|
||||
self.rejections = interp.unhandled();
|
||||
Ok(interp.to_js_value(&v))
|
||||
}
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
@@ -755,6 +755,53 @@ impl Realm {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the host's `paletteUpdate` the controls of each ScriptUI palette this realm keeps, as
|
||||
/// the run that just ended left them; nothing when it keeps none. A getter it reads runs in the
|
||||
/// run's fuel, at most [`Realm::set_unbroken_fuel`] of it, as a nested run that cannot pause
|
||||
/// does; what it throws ends the run. The promise jobs a getter queues run in the same fuel,
|
||||
/// and the host then gets the controls once more ([`crate::scriptui::refresh`]). The run's
|
||||
/// report of unhandled rejections ([`Realm::unhandled_rejections`]) is then made again: it
|
||||
/// takes in the rejections of those jobs and leaves out a run's rejection that a getter or a
|
||||
/// job gave a handler.
|
||||
pub fn refresh_script_ui(&mut self) -> Result<(), RunError> {
|
||||
let interp = &mut self.interp;
|
||||
let total = interp.fuel;
|
||||
let cap = self.unbroken_fuel.min(total);
|
||||
interp.fuel = cap;
|
||||
let r = crate::scriptui::refresh(interp);
|
||||
let used = cap - interp.fuel;
|
||||
interp.fuel = total - used;
|
||||
match r {
|
||||
Ok(()) => {
|
||||
self.rejections = self.interp.unhandled();
|
||||
Ok(())
|
||||
}
|
||||
// A refresh that fails reports no rejection, as after any failed run.
|
||||
Err(Abrupt::Limit(LimitKind::Fuel)) if total > cap => {
|
||||
self.rejections = (Vec::new(), 0);
|
||||
self.outcome(Err(Abrupt::Limit(LimitKind::Unbroken))).map(drop)
|
||||
}
|
||||
Err(e) => {
|
||||
self.rejections = (Vec::new(), 0);
|
||||
self.outcome(Err(e)).map(drop)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Realm::refresh_script_ui`] after a run that failed: what the refresh throws is dropped,
|
||||
/// and the run's error keeps its place ([`Realm::error_source`], [`Realm::error_mark`]) and
|
||||
/// its thrown value. The report of unhandled rejections stays empty, as after any failed run.
|
||||
pub fn refresh_script_ui_after_error(&mut self) {
|
||||
let (tag, mark) = (self.interp.error_tag, self.interp.error_mark);
|
||||
let thrown = self.interp.last_thrown.clone();
|
||||
let rejections = std::mem::take(&mut self.rejections);
|
||||
let _ = self.refresh_script_ui();
|
||||
self.interp.error_tag = tag;
|
||||
self.interp.error_mark = mark;
|
||||
self.interp.last_thrown = thrown;
|
||||
self.rejections = rejections;
|
||||
}
|
||||
|
||||
/// Adds the global constructors `File` and `Folder`, whose file system work the host functions
|
||||
/// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`,
|
||||
/// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`,
|
||||
|
||||
+827
-104
File diff suppressed because it is too large
Load Diff
@@ -308,8 +308,10 @@ fn a_stop_from_end_when_show_fails_ends_the_run() {
|
||||
#[test]
|
||||
fn types_that_are_not_available_yet_throw_errors_that_say_so() {
|
||||
for (source, want) in [
|
||||
("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"),
|
||||
("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"),
|
||||
("new Window('window')", "Window: a window of type window is not available yet; use dialog or palette"),
|
||||
("new Window('window { b: Button {} }')", "Window: a window of type window is not available yet; use dialog or palette"),
|
||||
("new Window('palette')", "Window: this host shows no palettes"),
|
||||
("new Window('palette { b: Button {} }')", "Window: this host shows no palettes"),
|
||||
("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"),
|
||||
("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"),
|
||||
("new Window('dialog').add('wobble')", "add: there is no control type wobble"),
|
||||
@@ -706,6 +708,824 @@ fn a_show_that_waits_resumes_with_the_host_s_answer() {
|
||||
assert_eq!(seen.borrow().ends, vec![(1.0, true)]);
|
||||
}
|
||||
|
||||
/// What a palette host was asked: each call's name and its palette id (0 for none).
|
||||
type Calls = Rc<RefCell<Vec<(String, f64)>>>;
|
||||
|
||||
/// A realm with palette host functions: `paletteShow` gives ids from 1, and `paletteEvent` gives
|
||||
/// the events in `events`, in order, then `null`.
|
||||
fn palette_realm(events: Vec<Data>) -> (Realm, Calls) {
|
||||
palette_realm_with(events, Vec::new(), Vec::new())
|
||||
}
|
||||
|
||||
/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`,
|
||||
/// whose `palettePending` says whether any of them is left, and whose `paletteDraw` gives the
|
||||
/// answers in `draws`, in order, then `false`.
|
||||
fn palette_realm_with(events: Vec<Data>, taken: Vec<Data>, draws: Vec<bool>) -> (Realm, Calls) {
|
||||
let mut r = Realm::new();
|
||||
r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() });
|
||||
let calls: Calls = Rc::default();
|
||||
let events = Rc::new(RefCell::new(VecDeque::from(events)));
|
||||
let id_of = |args: &[Data], at: usize| match args.get(at) {
|
||||
Some(Data::Number(n)) => *n,
|
||||
_ => 0.0,
|
||||
};
|
||||
let record = |name: &'static str, at: usize| -> HostFunction {
|
||||
let c = calls.clone();
|
||||
Rc::new(move |args| {
|
||||
c.borrow_mut().push((name.to_string(), id_of(&args, at)));
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
};
|
||||
let c = calls.clone();
|
||||
let show: HostFunction = Rc::new(move |args| {
|
||||
let given = id_of(&args, 1);
|
||||
let id = if given > 0.0 { given } else { 1.0 + c.borrow().iter().filter(|(n, _)| n == "paletteShow").count() as f64 };
|
||||
c.borrow_mut().push(("paletteShow".into(), id));
|
||||
Ok(Data::Number(id))
|
||||
});
|
||||
let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null)));
|
||||
let taken = Rc::new(RefCell::new(VecDeque::from(taken)));
|
||||
let c = calls.clone();
|
||||
let left = taken.clone();
|
||||
let take: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("paletteTake".into(), 0.0));
|
||||
Ok(left.borrow_mut().pop_front().unwrap_or(Data::Null))
|
||||
});
|
||||
let c = calls.clone();
|
||||
let pending: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("palettePending".into(), 0.0));
|
||||
Ok(Data::Bool(!taken.borrow().is_empty()))
|
||||
});
|
||||
let draws = RefCell::new(VecDeque::from(draws));
|
||||
let c = calls.clone();
|
||||
let draw: HostFunction = Rc::new(move |_| {
|
||||
c.borrow_mut().push(("paletteDraw".into(), 0.0));
|
||||
Ok(Data::Bool(draws.borrow_mut().pop_front().unwrap_or(false)))
|
||||
});
|
||||
let none: HostFunction = Rc::new(|_| Err(HostError::Error("no dialog here".into())));
|
||||
let items = vec![
|
||||
("open".into(), HostItem::Function(none.clone())),
|
||||
("wait".into(), HostItem::Function(none.clone())),
|
||||
("end".into(), HostItem::Function(none)),
|
||||
("palette".into(), HostItem::Function(record("palette", 0))),
|
||||
("paletteShow".into(), HostItem::Function(show)),
|
||||
("paletteUpdate".into(), HostItem::Function(record("paletteUpdate", 1))),
|
||||
("paletteHide".into(), HostItem::Function(record("paletteHide", 0))),
|
||||
("paletteClose".into(), HostItem::Function(record("paletteClose", 0))),
|
||||
("paletteEvent".into(), HostItem::Function(event)),
|
||||
("paletteTake".into(), HostItem::Function(take)),
|
||||
("palettePending".into(), HostItem::Function(pending)),
|
||||
("paletteDraw".into(), HostItem::Function(draw)),
|
||||
];
|
||||
r.define_script_ui(items).unwrap();
|
||||
(r, calls)
|
||||
}
|
||||
|
||||
fn palette_event(palette: f64, event: Data) -> Data {
|
||||
let Data::Object(mut fields) = event else { return Data::Null };
|
||||
fields.push(("palette".into(), Data::Number(palette)));
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
fn names(calls: &Calls) -> Vec<String> {
|
||||
calls.borrow().iter().map(|(n, _)| n.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2)), palette_event(1.0, change(3, Data::String("typed".into())))]);
|
||||
let made = r
|
||||
.run(
|
||||
"var p = new Window('palette', 'Tools'); var label = p.add('statictext', undefined, 'idle'); \
|
||||
var b = p.add('button', undefined, 'Go'); var t = p.add('edittext', undefined, ''); var log = []; \
|
||||
b.onClick = function () { log.push('click'); label.text = 'clicked'; }; \
|
||||
t.onChange = function () { log.push('change ' + t.text); }; String(p.show())",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(made, JsValue::String("undefined".into()), "show() gives undefined without waiting");
|
||||
assert_eq!(names(&calls), ["palette", "paletteShow", "paletteUpdate"]);
|
||||
r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("log.join('|') + '|' + label.text").unwrap(), JsValue::String("click|change typed|clicked".into()));
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count();
|
||||
assert_eq!(updates(&calls), 1, "the handlers give the host nothing");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(updates(&calls), 2, "the refresh after the run gives the host the new controls");
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); 'nothing'").unwrap(), JsValue::String("nothing".into()), "no event left: nothing runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_runs_no_handler_once_its_button_was_taken_out_of_the_palette() {
|
||||
// The button's onClick getter takes it out of the palette and gives a function.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { p.remove(b); return function () { log.push('ran'); }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "the getter's function does not run");
|
||||
// A capturing listener on the palette takes the button out before the button's own turn.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var log = []; \
|
||||
b.onClick = function () { log.push('click'); }; b.addEventListener('click', function () { log.push('listener'); }); \
|
||||
p.addEventListener('click', function () { log.push('capture'); p.remove(b); }, true); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("capture".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_is_dropped_when_a_getter_read_for_it_disables_its_button_or_a_group_above() {
|
||||
for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(3))]);
|
||||
r.run(&format!(
|
||||
"var armed = false, log = []; var p = new Window('palette'); var label = p.add('statictext', undefined, 'L'); \
|
||||
var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \
|
||||
Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \
|
||||
p.show(); armed = true;"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_is_dropped_when_a_getter_read_after_its_button_disables_the_button_or_a_group_above() {
|
||||
for disable in ["b.enabled = false;", "g.enabled = false;", "g.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(&format!(
|
||||
"var armed = false, log = []; var p = new Window('palette'); \
|
||||
var g = p.add('group'); var b = g.add('button', undefined, 'Go'); b.onClick = function () {{ log.push('click'); }}; \
|
||||
var label = p.add('statictext', undefined, 'L'); \
|
||||
Object.defineProperty(label, 'text', {{get: function () {{ if (armed) {{ armed = false; {disable} }} return 'L'; }}}}); \
|
||||
p.show(); armed = true;"
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()), "{disable}");
|
||||
}
|
||||
// A getter that gives the button's state, and disables it while it says the button is visible.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var armed = false, log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show(); \
|
||||
Object.defineProperty(b, 'visible', {get: function () { b.enabled = false; return true; }}); b.enabled = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("".into()));
|
||||
// Without a getter that disables anything, the same click runs its handler.
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var log = []; var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { log.push('click'); }; p.add('statictext', undefined, 'L'); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.run("Window.__vcPaletteEvent(); log.join()").unwrap(), JsValue::String("click".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_an_item_s_text_comes_from_a_getter() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(0.0), seen_list_change(0.0)]);
|
||||
// The first item's getter gives `label`, which the second item's getter changes after the
|
||||
// first was compared.
|
||||
r.run(
|
||||
"var p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); var got = []; var label = 'a', armed = false; \
|
||||
l.onChange = function () { got.push(String(l.selection)); }; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { return label; }}); \
|
||||
Object.defineProperty(l.items[1], 'text', {get: function () { if (armed) { label = 'z'; } return 'b'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
for arm in ["false", "true"] {
|
||||
let e = r.run(&format!("armed = {arm}; label = 'a'; 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()), "armed {arm}");
|
||||
}
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_asks_the_host_once_more_after_a_handler_s_exception() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); b.onClick = function () { throw new Error('broken'); }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let thrown = r.run("try { p.update(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(thrown, JsValue::String("broken".into()));
|
||||
let asked: Vec<String> = names(&calls).into_iter().filter(|n| n == "palettePending" || n == "paletteTake").collect();
|
||||
assert_eq!(asked, ["palettePending", "paletteTake", "palettePending"], "the host learns the event's handlers ended");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_palette_runs_on_close_which_can_keep_it_open() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, close()), palette_event(1.0, close()), palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; \
|
||||
var asked = 0; p.onClose = function () { asked++; p.close(); return asked > 1; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert!(!names(&calls).contains(&"paletteClose".to_string()), "the first onClose kept it open");
|
||||
assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(true), "a palette onClose kept open stays visible");
|
||||
r.run("Window.__vcPaletteEvent(); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[asked, clicks].join()").unwrap(), JsValue::String("2,0".into()), "a close inside onClose does not run it again");
|
||||
assert_eq!(r.run("p.visible").unwrap(), JsValue::Bool(false), "a closed palette is not visible");
|
||||
assert_eq!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1);
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
fn count(calls: &Calls, name: &str) -> usize {
|
||||
calls.borrow().iter().filter(|(n, _)| n == name).count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_in_the_script_s_own_code_gives_the_controls_only_when_the_host_draws_the_palette() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true, false, false, true]);
|
||||
r.start(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 4); p.show(); \
|
||||
for (var k = 1; k <= 4; k++) { bar.value = k; p.update(); }",
|
||||
)
|
||||
.unwrap();
|
||||
while r.advance(1_000_000).unwrap() == Progress::Paused {}
|
||||
assert_eq!(count(&calls, "paletteDraw"), 4, "each update() asks whether the palette is drawn");
|
||||
assert_eq!(count(&calls, "paletteUpdate"), 1 + 2, "show(), then only the update() calls the host draws");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_in_a_handler_neither_asks_to_draw_the_palette_nor_gives_its_controls() {
|
||||
let (mut r, calls) = palette_realm_with(vec![palette_event(1.0, click(2))], Vec::new(), vec![true; 3]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); var b = p.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.start("Window.__vcPaletteEvent();").unwrap();
|
||||
while r.advance(1_000_000).unwrap() == Progress::Paused {}
|
||||
assert_eq!(count(&calls, "paletteDraw"), 0, "a handler cannot pause, so its update() is not drawn");
|
||||
assert_eq!(count(&calls, "paletteUpdate"), before, "the handler's update() calls give the host no controls");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 1, "the controls go to the host once the run ends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(2))], Vec::new());
|
||||
let done = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100); \
|
||||
var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; \
|
||||
cancel.onClick = function () { stopped = true; }; p.show(); \
|
||||
var k = 0; while (!stopped && k < 100) { k++; bar.value = k; p.update(); } k + ':' + stopped",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1, "update() takes events while one waits");
|
||||
assert!(count(&calls, "palettePending") >= 2, "update() asks again after each event");
|
||||
let order = names(&calls);
|
||||
let take = order.iter().position(|n| n == "paletteTake");
|
||||
let last_update = order.iter().rposition(|n| n == "paletteUpdate");
|
||||
assert!(take.zip(last_update).is_some_and(|(t, u)| u < t), "the host gets the controls before the event is taken");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_a_getter_calls_while_a_click_waits_leaves_the_click_to_the_update_taking_it() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
let done = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; var armed = false; \
|
||||
b.onClick = function () { clicks++; }; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { reads++; p.update(); } return 'P'; }}); \
|
||||
p.show(); armed = true; p.update(); clicks + ':' + (reads > 0)",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(done, JsValue::String("1:true".into()), "the getter's update() runs, and the click's onClick runs once");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_throws_for_a_window_that_is_not_showing() {
|
||||
let (mut r, _, _) = realm(vec![click(12)]);
|
||||
let source = format!(
|
||||
"{FORM} var before = 'none'; try {{ w.update(); }} catch (e) {{ before = e.message; }} var during = 'none'; \
|
||||
ok.onClick = function () {{ w.update(); during = 'ran'; w.close(1); }}; [w.show(), before, during].join('|')"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("1|update: the window is not showing|ran".into()));
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
let hidden = r
|
||||
.run(
|
||||
"var p = new Window('palette'); var log = []; try { p.update(); } catch (e) { log.push('before show'); } \
|
||||
p.show(); p.update(); p.hide(); try { p.update(); } catch (e) { log.push('hidden'); } log.join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(hidden, JsValue::String("before show,hidden".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_on_a_showing_dialog_its_group_or_its_panel_runs_in_a_handler() {
|
||||
let (mut r, _, _) = realm(vec![click(12)]);
|
||||
let source = format!(
|
||||
"{FORM} var done = 'none'; ok.onClick = function () {{ bar.value = 7; w.update(); g.update(); p.update(); done = 'ran'; w.close(1); }}; \
|
||||
[w.show(), done].join('|')"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("1|ran".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn update_follows_whether_the_host_shows_a_palette_not_its_visible_property() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), Vec::new(), vec![true; 4]);
|
||||
r.run("var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); p.show();").unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.start(
|
||||
"var log = []; p.visible = false; p.update(); g.update(); log.push('shown'); \
|
||||
p.hide(); p.visible = true; try { p.update(); } catch (e) { log.push('hidden'); } \
|
||||
try { b.update(); } catch (e) { log.push(e.name); } log.join()",
|
||||
)
|
||||
.unwrap();
|
||||
let log = loop {
|
||||
if let Progress::Done(v) = r.advance(1_000_000).unwrap() {
|
||||
break v;
|
||||
}
|
||||
};
|
||||
assert_eq!(log, JsValue::String("shown,hidden,TypeError".into()));
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the palette and its group each give the host the controls while it shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_after_its_items_changed_throws() {
|
||||
let seen = |index: f64| {
|
||||
let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null };
|
||||
fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())])));
|
||||
// The two items the list was made with.
|
||||
fields.push(("revision".into(), Data::Number(2.0)));
|
||||
Data::Object(fields)
|
||||
};
|
||||
let (mut r, _) = palette_realm(vec![seen(1.0), seen(1.0), seen(1.0), seen(1.0)]);
|
||||
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)); }; p.show();")
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent(); l.removeAll(); l.add('item', 'c'); l.add('item', 'd');").unwrap();
|
||||
let message = "a palette's list changed before the person's choice was taken";
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "the same number of items, other texts");
|
||||
r.run("l.removeAll(); l.add('item', 'a');").unwrap();
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "fewer items");
|
||||
r.run("l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap();
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String(message.into()), "new items with the same texts");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("b".into()));
|
||||
}
|
||||
|
||||
/// A palette list change as the host gives it: the item index, the items the person saw (`a` and
|
||||
/// `b`) and the revision of a list made with those two items.
|
||||
fn seen_list_change(index: f64) -> Data {
|
||||
let Data::Object(mut fields) = palette_event(1.0, change(1, Data::Number(index))) else { return Data::Null };
|
||||
fields.push(("items".into(), Data::Array(vec![Data::String("a".into()), Data::String("b".into())])));
|
||||
fields.push(("revision".into(), Data::Number(2.0)));
|
||||
Data::Object(fields)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_after_an_item_s_text_changed_throws() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
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)); }; p.show();")
|
||||
.unwrap();
|
||||
r.run("l.items[1].text = 'z';").unwrap();
|
||||
let e = r.run("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()), "the same items, one with another text");
|
||||
assert_eq!(r.run("got.join()").unwrap(), JsValue::String("".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The event reads the first item's text twice: for the palette's description, then to compare
|
||||
// it with the items the person saw. The second read turns the getter back into a plain text and
|
||||
// replaces the items with ones of the same texts, so only the list's revision tells them apart.
|
||||
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; var first = l.items[0]; \
|
||||
Object.defineProperty(first, 'text', {configurable: true, get: function () { if (reads >= 0 && ++reads == 2) { \
|
||||
Object.defineProperty(first, 'text', {value: 'a', writable: true, enumerable: true, configurable: true}); \
|
||||
l.removeAll(); l.add('item', 'a'); l.add('item', 'b'); } return 'a'; }}); \
|
||||
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("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_finds_its_control_by_its_id() {
|
||||
let of = |id: usize, element: f64| {
|
||||
let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null };
|
||||
fields.push(("element".into(), Data::Number(element)));
|
||||
Data::Object(fields)
|
||||
};
|
||||
// The palette is element 1, the group 2 and the button 3. The host's indexes are stale: 1 is
|
||||
// the group, and after the group is removed, 2 is past the end.
|
||||
let (mut r, _) = palette_realm(vec![of(1, 3.0), of(2, 3.0), of(1, 99.0)]);
|
||||
r.run("var p = new Window('palette'); var g = p.add('group'); var b = p.add('button', undefined, 'Go'); var clicks = 0; b.onClick = function () { clicks++; }; p.show();")
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0), "the click reaches the control with its id");
|
||||
r.run("p.remove(g); Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0), "the click follows the control after a control before it is removed");
|
||||
let e = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("a palette event names a control the palette no longer holds".into()), "no control with the id");
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(2.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_on_a_button_a_getter_removed_runs_no_handler_and_throws() {
|
||||
// The palette is element 1, the label 2 and the button 3.
|
||||
let Data::Object(mut fields) = palette_event(1.0, click(2)) else { panic!("an event is an object") };
|
||||
fields.push(("element".into(), Data::Number(3.0)));
|
||||
let (mut r, _) = palette_realm(vec![Data::Object(fields)]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \
|
||||
var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.remove(b); } return 'idle'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
// The event reads the label's text for the palette's description, which removes the button.
|
||||
let given = r.run("armed = true; try { Window.__vcPaletteEvent(); 'given'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(given, JsValue::String("a palette event names a control the palette no longer holds".into()));
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the removed button's handler does not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var b = p.add('button', undefined, 'Go'); \
|
||||
var clicks = 0; b.onClick = function () { clicks++; }; var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { armed = false; p.close(); } return 'idle'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
// The event reads the label's text for the palette's description, which closes the palette.
|
||||
r.run("armed = true; Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("clicks").unwrap(), JsValue::Number(0.0), "the click is not given to a closed palette");
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_runs_no_more_listeners_once_one_closed_the_palette() {
|
||||
let (mut r, calls) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var later = 0; \
|
||||
b.addEventListener('click', function () { p.close(); }); b.addEventListener('click', function () { later++; }); \
|
||||
p.addEventListener('click', function () { later++; }); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
assert_eq!(r.run("later").unwrap(), JsValue::Number(0.0), "neither the next listener nor the palette's runs after the close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_does_not_run_on_change_once_an_item_s_text_getter_closed_the_palette() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The event reads the first item's text twice: for the palette's description, then to compare
|
||||
// it with the items the person saw. The second read closes the palette.
|
||||
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[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()));
|
||||
assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_disabled_or_hid_the_list() {
|
||||
for disable in ["l.enabled = false;", "l.visible = false;"] {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text, which compares it with the items the person
|
||||
// saw, disables the list.
|
||||
r.run(&format!(
|
||||
"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[0], 'text', {{get: function () {{ if (reads >= 0 && ++reads == 2) {{ {disable} }} return 'a'; }}}}); \
|
||||
p.show();"
|
||||
))
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()), "{disable}");
|
||||
assert_eq!(r.run("[got.join(), String(l.selection)].join()").unwrap(), JsValue::String(",null".into()), "{disable}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_click_does_not_turn_over_a_check_box_its_value_getter_disabled() {
|
||||
// Whichever read of `value` disables the box, the click neither sets it nor runs its handler.
|
||||
for read in 1..=4 {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(&format!(
|
||||
"var p = new Window('palette'); var c = p.add('checkbox', undefined, 'On'); var clicks = 0, on = false, reads = -1; \
|
||||
Object.defineProperty(c, 'value', {{get: function () {{ if (reads >= 0 && ++reads == {read}) {{ c.enabled = false; }} return on; }}, \
|
||||
set: function (v) {{ on = v; }}}}); c.onClick = function () {{ clicks++; }}; p.show(); reads = 0;"
|
||||
))
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
let got = r.run(&format!("reads >= {read} ? [clicks, on].join() : 'not read'")).unwrap();
|
||||
assert!(got == JsValue::String("0,false".into()) || (read > 1 && got == JsValue::String("not read".into())), "read {read}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_palette_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(); p.hide(); \
|
||||
Object.defineProperty(p, 'text', {get: function () { throw new Error('read'); }});",
|
||||
)
|
||||
.unwrap();
|
||||
let updates = |calls: &Calls| calls.borrow().iter().filter(|(n, _)| n == "paletteUpdate").count();
|
||||
let before = updates(&calls);
|
||||
r.refresh_script_ui().expect("a hidden palette's throwing title getter is not read");
|
||||
assert_eq!(updates(&calls), before, "the host is not given a hidden palette's controls");
|
||||
}
|
||||
|
||||
#[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))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { reads++; p.close(); return function () { clicks++; }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a closed palette does not run");
|
||||
assert!(calls.borrow().contains(&("paletteClose".into(), 1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_whose_getter_hid_the_palette() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0; var reads = 0; \
|
||||
Object.defineProperty(b, 'onClick', {get: function () { reads++; p.hide(); return function () { clicks++; }; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[reads, clicks].join()").unwrap(), JsValue::String("1,0".into()), "the handler read from a hidden palette does not run");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_listener_hid_and_showed_the_palette_again() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(1))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \
|
||||
p.addEventListener('click', function () { heard++; p.hide(); p.show(); }, true); \
|
||||
b.onClick = function () { clicks++; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(
|
||||
r.run("[heard, clicks, p.visible].join()").unwrap(),
|
||||
JsValue::String("1,0,true".into()),
|
||||
"a click the palette took before a hide is not its click after the palette shows again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_event_does_not_run_a_handler_once_a_capturing_listener_disabled_its_group() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, click(2))]);
|
||||
r.run(
|
||||
"var p = new Window('palette'); var g = p.add('group'); var b = g.add('button', undefined, 'Go'); var clicks = 0, heard = 0; \
|
||||
g.addEventListener('click', function () { heard++; g.enabled = false; }, true); \
|
||||
b.onClick = function () { clicks++; }; p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
r.run("Window.__vcPaletteEvent();").unwrap();
|
||||
assert_eq!(r.run("[heard, clicks].join()").unwrap(), JsValue::String("1,0".into()), "a control in a disabled group takes no click");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_refresh_that_fails_reports_no_rejection() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }}); \
|
||||
p.show(); Promise.reject(new Error('early')); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r.unhandled_rejection_count(), 1, "the run left the rejection unhandled");
|
||||
assert!(r.refresh_script_ui().is_err());
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed refresh reports no rejection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_runs_no_on_change_once_an_item_s_text_getter_removed_the_list() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text, which compares it with the items the person saw,
|
||||
// removes the list from the palette.
|
||||
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[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.remove(l); } return 'a'; }}); \
|
||||
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 event names a control the palette no longer holds".into()));
|
||||
assert_eq!(r.run("[reads, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("2,,null".into()));
|
||||
}
|
||||
|
||||
#[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()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_whose_palette_update_a_getter_breaks_still_returns_the_control() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.run(
|
||||
"var p = new Window('palette'); var label = p.add('statictext', undefined, 'idle'); var armed = false; \
|
||||
Object.defineProperty(label, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'idle'; }}); \
|
||||
var list = p.add('listbox', undefined, ['a']); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let added = r
|
||||
.run(
|
||||
"armed = true; var c, d, m = []; try { c = p.add('button', undefined, 'New'); } catch (e) { m.push(e.message); } \
|
||||
try { d = list.add('item', 'b'); } catch (e) { m.push(e.message); } \
|
||||
try { list.remove(0); } catch (e) { m.push(e.message); } \
|
||||
try { p.remove(c); } catch (e) { m.push(e.message); } armed = false; \
|
||||
[String(c && c.text), String(d && d.text), list.items.length, p.children.length, m.length].join()",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(added, JsValue::String("New,b,1,2,0".into()), "each change is made once and gives its result");
|
||||
// A later error is at its own line, not at the getter's.
|
||||
let e = r.run("armed = true;\np.add('button', undefined, 'Other');\narmed = false;\nthrow new Error('later');").unwrap_err();
|
||||
assert_eq!((e.message.contains("later"), e.line), (true, 4), "{e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_while_the_palette_is_refreshed_run() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var ran = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
Promise.resolve().then(function () { ran++; b.text = 'Done'; }); Promise.reject(new Error('late')); } return 'P'; }}); \
|
||||
p.show(); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again after the jobs ran");
|
||||
assert_eq!(r.unhandled_rejections().len(), 1, "the job's rejection is the run's");
|
||||
assert_eq!(r.run("[ran, b.text].join()").unwrap(), JsValue::String("1,Done".into()), "the job the getter queued ran with the refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_s_rejection_that_a_palette_getter_handles_during_the_refresh_is_not_reported() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false, caught = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
early.catch(function () { caught++; }); } return 'P'; }}); \
|
||||
p.show(); var early = Promise.reject(new Error('early')); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (1, 1), "the run left the rejection unhandled");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "the getter gave it a handler");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejection_a_palette_getter_makes_while_a_failed_run_is_refreshed_is_not_reported() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var armed = false; var p = new Window('palette'); p.add('button', undefined, 'Go'); \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { armed = false; \
|
||||
Promise.reject('late'); } return 'P'; }}); p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
assert!(r.run("armed = true; throw new Error('failed');").is_err());
|
||||
r.refresh_script_ui_after_error();
|
||||
assert_eq!((r.unhandled_rejections().len(), r.unhandled_rejection_count()), (0, 0), "a failed run reports no rejection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_on_every_refresh_run_without_another_refresh() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var n = 0, reads = 0; var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); \
|
||||
Object.defineProperty(p, 'text', {get: function () { reads++; \
|
||||
Promise.resolve().then(function () { n++; }); return 'Title'; }});",
|
||||
)
|
||||
.unwrap();
|
||||
let before = count(&calls, "paletteUpdate");
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteUpdate") - before, 2, "the host gets the controls again once after the jobs run");
|
||||
assert_eq!(r.run("reads > 0 && n === reads").unwrap(), JsValue::Bool(true), "every getter read's job runs before the refresh returns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn promise_jobs_a_palette_getter_queues_during_refresh_leave_waiting_clicks_queued() {
|
||||
let (mut r, calls) = palette_realm_with(Vec::new(), vec![palette_event(1.0, click(1))], Vec::new());
|
||||
r.add_es2015();
|
||||
r.run(
|
||||
"var clicks = 0, jobs = 0, armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { clicks++; }; \
|
||||
Object.defineProperty(p, 'text', {get: function () { if (armed) { \
|
||||
Promise.resolve().then(function () { jobs++; p.update(); }); } return 'P'; }}); \
|
||||
p.show(); armed = true;",
|
||||
)
|
||||
.unwrap();
|
||||
r.refresh_script_ui().unwrap();
|
||||
assert_eq!(count(&calls, "paletteTake"), 0, "the refresh leaves the waiting click queued");
|
||||
assert_eq!(r.run("jobs > 0 && clicks === 0").unwrap(), JsValue::Bool(true), "the promise jobs run without dispatching the click");
|
||||
assert_eq!(r.run("armed = false; p.update(); clicks").unwrap(), JsValue::Number(1.0), "a later update takes the waiting click");
|
||||
assert_eq!(count(&calls, "paletteTake"), 1, "the refresh restores the event-taking guard");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_object_on_close_throws_stays_whole_while_the_close_ends() {
|
||||
let (mut r, _) = palette_realm(vec![palette_event(1.0, close())]);
|
||||
r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.onClose = function () { throw {tag: 'kept'}; }; p.show();").unwrap();
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let thrown = r.run("try { Window.__vcPaletteEvent(); 'none'; } catch (e) { String(e.tag); }");
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(thrown.unwrap(), JsValue::String("kept".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_list_change_is_dropped_once_an_item_s_text_getter_closed_the_palette_and_on_close_changed_the_list() {
|
||||
let (mut r, _) = palette_realm(vec![seen_list_change(1.0)]);
|
||||
// The second read of the first item's text closes the palette, and its `onClose` adds an item.
|
||||
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; \
|
||||
p.onClose = function () { l.add('item', 'c'); }; \
|
||||
Object.defineProperty(l.items[0], 'text', {get: function () { if (reads >= 0 && ++reads == 2) { p.close(); } return 'a'; }}); \
|
||||
p.show();",
|
||||
)
|
||||
.unwrap();
|
||||
let e = r.run("reads = 0; try { Window.__vcPaletteEvent(); 'none'; } catch (e) { e.message; }").unwrap();
|
||||
assert_eq!(e, JsValue::String("none".into()), "the event for a closed palette is dropped without an error");
|
||||
assert_eq!(r.run("[reads >= 2, l.items.length, got.join(), String(l.selection)].join()").unwrap(), JsValue::String("true,3,,null".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_palette_s_visible_follows_hide_and_show() {
|
||||
let (mut r, _) = palette_realm(Vec::new());
|
||||
let v = r
|
||||
.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); var a = p.visible; p.hide(); var b = p.visible; p.show(); [a, b, p.visible].join()")
|
||||
.unwrap();
|
||||
assert_eq!(v, JsValue::String("true,false,true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_close_inside_a_dialog_s_on_close_does_nothing() {
|
||||
let (mut r, seen, _) = realm(vec![close(), click(13)]);
|
||||
let source = format!(
|
||||
"{FORM} var asked = 0; w.onClose = function () {{ asked++; if (asked == 1) {{ w.close(5); return false; }} return true; }}; [w.show(), asked].join()"
|
||||
);
|
||||
assert_eq!(r.run(&source).unwrap(), JsValue::String("2,2".into()), "the dialog waited for the click on Cancel");
|
||||
assert_eq!(seen.borrow().ends, vec![(2.0, true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_whose_ends_add_up_past_the_largest_number_stay_finite() {
|
||||
let (mut r, seen, _) = realm(vec![close()]);
|
||||
r.run("var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); b.bounds = {x: 1e308, y: 0, width: 1e308, height: 20}; w.show()")
|
||||
.unwrap();
|
||||
let described = nodes(&seen.borrow().descriptions[0]);
|
||||
let want = Data::Array(vec![Data::Number(1e308), Data::Number(0.0), Data::Number(f64::MAX), Data::Number(20.0)]);
|
||||
assert_eq!(field(&described[1], "bounds"), &want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hide_keeps_the_palette_and_show_shows_it_again_with_the_same_id() {
|
||||
let (mut r, calls) = palette_realm(Vec::new());
|
||||
r.run("var p = new Window('palette'); p.add('button', undefined, 'Go'); p.show(); p.hide(); p.show();").unwrap();
|
||||
let shows: Vec<f64> = calls.borrow().iter().filter(|(n, _)| n == "paletteShow" || n == "paletteHide").map(|(_, id)| *id).collect();
|
||||
assert_eq!(shows, [1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn findelement_items_and_selection_follow_the_list() {
|
||||
let (mut r, _, _) = realm(Vec::new());
|
||||
|
||||
@@ -235,7 +235,7 @@ features! {
|
||||
Reflection "reflection" Language,
|
||||
ScriptuiDialog "scriptui.dialog" Dialogs,
|
||||
ScriptuiDrawing "scriptui.drawing" Dialogs,
|
||||
ScriptuiPalette "scriptui.palette" HostOnly,
|
||||
ScriptuiPalette "scriptui.palette" Dialogs,
|
||||
ScriptuiWindow "scriptui.window" Dialogs,
|
||||
SelectTool "selectTool" Dom,
|
||||
Socket "socket" HostOnly,
|
||||
|
||||
@@ -120,8 +120,8 @@ pub enum Need {
|
||||
MenuCommands,
|
||||
/// Dialogs and windows of its own.
|
||||
Dialogs,
|
||||
/// Features only the reference app has (palettes, messages to other apps, network
|
||||
/// connections, native code, actions).
|
||||
/// Features only the reference app has (messages to other apps, network connections, native
|
||||
/// code, actions).
|
||||
HostOnly,
|
||||
}
|
||||
|
||||
|
||||
@@ -2163,6 +2163,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() {
|
||||
assert_eq!(notify(five, &Limits::default()).0, Vec::<usize>::new());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palettes_need_dialogs() {
|
||||
let r = report("#targetengine tools\nvar w = new Window('palette');\nw.show();\n");
|
||||
assert_eq!(r.needs, [Need::Language, Need::Dialogs]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_methods_are_features_not_members() {
|
||||
let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n");
|
||||
|
||||
@@ -586,15 +586,23 @@ impl VectorcraftApp {
|
||||
// A panel's, a dialog's or the text input's commit journaled in the frame before.
|
||||
crate::panels::actions::after_journaled_edit(self);
|
||||
crate::scripts_menu::poll(self, ctx);
|
||||
// A palette event whose run starts on the next frame. While a run goes on, the block below
|
||||
// asks for its frames, and a run that waits for the person goes on at their next input. An
|
||||
// event that waits for an open undo group asks for no frame; the pass that ends the group
|
||||
// asks for the next one (`ui_frame`).
|
||||
if crate::script_palettes::can_start(self) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if self.session.script_running()
|
||||
&& !crate::script_runs::waiting_for_print(self)
|
||||
&& !self.session.script_waiting()
|
||||
&& self.session.script_dialog().is_none()
|
||||
&& self.session.script_window().is_none()
|
||||
&& self.session.script_picker().is_none()
|
||||
{
|
||||
// A script in `$.sleep` goes on when its time is up; until then the app can idle. A
|
||||
// script at a file dialog goes on when the dialog answers, and `file_asks::poll` looks
|
||||
// for that.
|
||||
// for that. A script at its ScriptUI dialog goes on when the dialog gives it an event.
|
||||
match self.session.script_sleep_left() {
|
||||
Some(left) => ctx.request_repaint_after(left),
|
||||
None => ctx.request_repaint(),
|
||||
@@ -801,6 +809,7 @@ impl VectorcraftApp {
|
||||
panels::learn::locate::tidy(self, &ctx);
|
||||
crate::doc_windows::show(self, ui);
|
||||
export_progress::show(self, ui);
|
||||
crate::script_palettes::show(self, &ctx);
|
||||
// After every window this pass may open, and before the palette's field takes the keyboard.
|
||||
panel_docking::close_overlays_for_modal(self, &ctx);
|
||||
let drawn_document = self.session.active().map(|st| (st.uid, st.revision));
|
||||
@@ -821,6 +830,10 @@ 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 that waited for an undo group this pass ended starts its run next frame.
|
||||
if crate::script_palettes::can_start(self) {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
// Only a field's commit in the pass of the press is the one it made.
|
||||
self.canvas.committed_preview = false;
|
||||
self.drop_formats_after_egui_copy(&ctx);
|
||||
|
||||
@@ -44,6 +44,7 @@ impl VectorcraftApp {
|
||||
});
|
||||
self.finish_captures(finished);
|
||||
let settle = settle_ms(ctx.global_style().animation_time);
|
||||
let mut handled = 0usize;
|
||||
while let Some(req) = self.deferred_control.take().or_else(|| self.channel.as_mut().and_then(ControlChannel::next_request)) {
|
||||
// A request held past its deadline is answered as one still queued then.
|
||||
if req.deadline.is_some_and(|deadline| self.instant() >= deadline) {
|
||||
@@ -71,6 +72,7 @@ impl VectorcraftApp {
|
||||
// Guarded per request: a panic must not stop the requests behind it.
|
||||
let answer = file_access::confine(roots.as_ref(), || vectorcraft_engine::guard::catch_panic(|| control::handle(self, ctx, &req)));
|
||||
self.ui.answering_control = false;
|
||||
handled += 1;
|
||||
let reply = match answer {
|
||||
Ok(reply) => reply,
|
||||
Err(msg) => {
|
||||
@@ -92,6 +94,10 @@ impl VectorcraftApp {
|
||||
host.paint_while_hidden();
|
||||
}
|
||||
ctx.request_repaint();
|
||||
} else if handled > 0 && self.session.script_running() {
|
||||
// A request may have answered the dialog a run waits at, which the app idles for: the
|
||||
// next frame takes the answer and the run's next slice.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
self.answer_pointer_waits(ctx);
|
||||
}
|
||||
|
||||
@@ -532,9 +532,15 @@ pub(crate) fn asking_to_print(app: &VectorcraftApp) -> bool {
|
||||
with_host(app, |host, _| host.is_open::<ScriptPrint>()).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether a dialog is open or waits to open: a script's dialog opens only over nothing.
|
||||
/// Whether a dialog is open or waits to open: a script's dialog opens only over nothing. A
|
||||
/// script's palettes ([`crate::script_palettes`]) stay open beside the documents and are not
|
||||
/// counted.
|
||||
pub(crate) fn busy(app: &VectorcraftApp) -> bool {
|
||||
app.any_dialog_open() || with_host(app, |host, _| !host.is_empty()).unwrap_or(false)
|
||||
let other = |host: &mut DialogHost| {
|
||||
let open = host.open_dialogs();
|
||||
!host.is_empty() && (open.is_empty() || open.iter().any(|d| d.key.as_deref() != Some(crate::script_palettes::KIND)))
|
||||
};
|
||||
app.any_dialog_open() || with_host(app, |host, _| other(host)).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Whether the run's question can open now: over nothing, or over the script's ScriptUI dialog
|
||||
@@ -764,7 +770,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) {
|
||||
Some(parent) => {
|
||||
host.open_child(close_question(), parent);
|
||||
}
|
||||
None if host.is_empty() => {
|
||||
// The script's palettes stay open beside the question.
|
||||
None if host.is_empty() || host.open_dialogs().iter().all(|d| d.key.as_deref() == Some(crate::script_palettes::KIND)) => {
|
||||
host.open(close_question());
|
||||
}
|
||||
None => {}
|
||||
|
||||
@@ -50,7 +50,7 @@ use crate::VectorcraftApp;
|
||||
pub const KIND: &str = "scriptWindow";
|
||||
|
||||
/// The most of the dialog's content shown at once; a larger dialog scrolls.
|
||||
const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0);
|
||||
pub(crate) const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0);
|
||||
|
||||
/// The room the engine's layout adds around a list box's rows.
|
||||
const LIST_PAD: f32 = 6.0;
|
||||
@@ -158,65 +158,20 @@ impl ScriptWindow {
|
||||
self.waiting = waiting.is_some();
|
||||
if let Some(w) = waiting {
|
||||
self.window = w;
|
||||
let fields: Vec<u64> = self.window.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect();
|
||||
self.drafts.retain(|id, _| fields.contains(id));
|
||||
keep_fields(&self.window, &mut self.drafts);
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a click or a close, gives the script the text typed in each edit field that has not
|
||||
/// left the field yet, so the handler of a button that closes the dialog, or `onClose`, reads
|
||||
/// it. A disabled or hidden field keeps its text for later. Each text is checked 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.
|
||||
/// left the field yet ([`commit_texts`]).
|
||||
pub(crate) fn commit_drafts(&mut self, w: &ScriptUiDialog, events: &mut Vec<UiEvent>) -> Result<(), String> {
|
||||
let mut given = Vec::new();
|
||||
let mut changes = Vec::new();
|
||||
for (i, n) in w.nodes.iter().enumerate() {
|
||||
if n.kind != UiKind::EditText
|
||||
|| n.readonly
|
||||
|| !n.enabled
|
||||
|| !n.visible
|
||||
|| events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = self.drafts.get(&n.id) {
|
||||
if *text != n.text {
|
||||
changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?);
|
||||
}
|
||||
given.push(n.id);
|
||||
}
|
||||
}
|
||||
for id in given {
|
||||
self.drafts.remove(&id);
|
||||
}
|
||||
let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close);
|
||||
events.sort_by_key(closing);
|
||||
let at = events.iter().position(closing).unwrap_or(events.len());
|
||||
events.splice(at..at, changes);
|
||||
Ok(())
|
||||
commit_texts(w, &mut self.drafts, events)
|
||||
}
|
||||
|
||||
/// Takes out of `events` each text an edit field gave as it lost the focus that the script
|
||||
/// would refuse, and puts it back in its field, so the person can fix it. → the error of the
|
||||
/// last one.
|
||||
/// would refuse ([`keep_refused`]). → the error of the last one.
|
||||
pub(crate) fn keep_refused_texts(&mut self, events: &mut Vec<UiEvent>) -> Option<String> {
|
||||
let mut refused = None;
|
||||
let (w, drafts) = (&self.window, &mut self.drafts);
|
||||
events.retain(|e| {
|
||||
let UiEvent::Change(i, UiValue::Text(text)) = e else { return true };
|
||||
match check_event(w, e.clone()) {
|
||||
Ok(_) => true,
|
||||
Err(error) => {
|
||||
if let Some(n) = w.nodes.get(*i) {
|
||||
drafts.insert(n.id, text.clone());
|
||||
}
|
||||
refused = Some(error);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
refused
|
||||
keep_refused(&self.window, &mut self.drafts, events)
|
||||
}
|
||||
|
||||
/// The next queued event the dialog `w` can still take, with its control's index in `w` now.
|
||||
@@ -251,8 +206,72 @@ impl ScriptWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops each typed text in `drafts` whose edit field the dialog `w` no longer has.
|
||||
pub(crate) fn keep_fields(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>) {
|
||||
let fields: Vec<u64> = w.nodes.iter().skip(1).filter(|n| n.kind == UiKind::EditText).map(|n| n.id).collect();
|
||||
drafts.retain(|id, _| fields.contains(id));
|
||||
}
|
||||
|
||||
/// Before a click or a close, gives the script the text typed in each edit field of `w` that has
|
||||
/// not left the field yet (`drafts`), so the handler of a button that closes the dialog, or
|
||||
/// `onClose`, reads it. A disabled or hidden field keeps its text for later. Each text is checked
|
||||
/// 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<u64, String>, events: &mut Vec<UiEvent>) -> Result<(), String> {
|
||||
let mut given = Vec::new();
|
||||
let mut changes = Vec::new();
|
||||
for (i, n) in w.nodes.iter().enumerate() {
|
||||
if n.kind != UiKind::EditText
|
||||
|| n.readonly
|
||||
|| !n.enabled
|
||||
|| !n.visible
|
||||
|| events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(text) = drafts.get(&n.id) {
|
||||
if *text != n.text {
|
||||
changes.push(check_event(w, UiEvent::Change(i, UiValue::Text(text.clone())))?);
|
||||
}
|
||||
given.push(n.id);
|
||||
}
|
||||
}
|
||||
for id in given {
|
||||
drafts.remove(&id);
|
||||
}
|
||||
// The events of one pass are listed in the order of the controls, not the order the person
|
||||
// gave them, so each change goes before the clicks and the close, and a handler that closes
|
||||
// the dialog reads it.
|
||||
let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close);
|
||||
events.sort_by_key(closing);
|
||||
let at = events.iter().position(closing).unwrap_or(events.len());
|
||||
events.splice(at..at, changes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes out of `events` each text an edit field of `w` gave as it lost the focus that the script
|
||||
/// would refuse, and puts it back in its field (`drafts`), so the person can fix it. → the error of
|
||||
/// the last one.
|
||||
pub(crate) fn keep_refused(w: &ScriptUiDialog, drafts: &mut BTreeMap<u64, String>, events: &mut Vec<UiEvent>) -> Option<String> {
|
||||
let mut refused = None;
|
||||
events.retain(|e| {
|
||||
let UiEvent::Change(i, UiValue::Text(text)) = e else { return true };
|
||||
match check_event(w, e.clone()) {
|
||||
Ok(_) => true,
|
||||
Err(error) => {
|
||||
if let Some(n) = w.nodes.get(*i) {
|
||||
drafts.insert(n.id, text.clone());
|
||||
}
|
||||
refused = Some(error);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
refused
|
||||
}
|
||||
|
||||
/// `event` in the dialog `w`, with its control by its id.
|
||||
fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option<Queued> {
|
||||
pub(crate) fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option<Queued> {
|
||||
let id = |i: usize| w.nodes.get(i).map(|n| n.id);
|
||||
Some(match event {
|
||||
UiEvent::Click(i) => Queued::Click(id(*i)?),
|
||||
@@ -266,8 +285,8 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option<Queued> {
|
||||
|
||||
/// The queued event `q` in the dialog `w`, with `control` the index its control has in `w` now.
|
||||
/// `None` when `w` no longer has the control, or for a list's change, when the list's items are no
|
||||
/// longer those the person chose from.
|
||||
fn resolved(w: &ScriptUiDialog, q: Queued) -> Option<UiEvent> {
|
||||
/// longer those the person chose from: other texts, or the same texts added again.
|
||||
pub(crate) fn resolved(w: &ScriptUiDialog, q: Queued) -> Option<UiEvent> {
|
||||
match q {
|
||||
Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)),
|
||||
Queued::Change(id, v, items) => {
|
||||
@@ -306,10 +325,7 @@ impl StackDialog for ScriptWindow {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let top = stack.is_top(self.id());
|
||||
let heading = match self.window.title() {
|
||||
"" => tl!("Script Alert").to_string(),
|
||||
title => shown_text(title, false),
|
||||
};
|
||||
let heading = heading(&self.window);
|
||||
let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)];
|
||||
let ScriptWindow { window, waiting, drafts, open, .. } = self;
|
||||
let (window, waiting, drafts) = (&*window, *waiting, &*drafts);
|
||||
@@ -320,35 +336,7 @@ impl StackDialog for ScriptWindow {
|
||||
let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open));
|
||||
// The body can run twice in a pass (measure, then paint), so it only reports what the
|
||||
// person did; the dialog applies the last run's report after the container.
|
||||
let shown = dialog.show(ui, |ui, _| {
|
||||
let (width, height) = window.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() };
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_size(MAX_SHOWN);
|
||||
Stack::new().scroll(Scroll::both()).show(ui, |ui, _| {
|
||||
let origin = ui.cursor().min;
|
||||
ui.set_min_size(size);
|
||||
// Each container comes before the controls it holds.
|
||||
let mut containers: Vec<Option<egui::Id>> = vec![None; window.nodes.len()];
|
||||
for (i, n) in window.nodes.iter().enumerate().skip(1) {
|
||||
if !n.visible {
|
||||
continue;
|
||||
}
|
||||
let parent = containers.get(n.parent).copied().flatten();
|
||||
let place = Place { origin, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent };
|
||||
let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i)));
|
||||
if let Some(slot) = containers.get_mut(i) {
|
||||
*slot = shown.container;
|
||||
}
|
||||
pass.typing |= shown.typing;
|
||||
pass.events.extend(shown.event);
|
||||
pass.drafts.extend(shown.draft.map(|d| (n.id, d)));
|
||||
}
|
||||
});
|
||||
});
|
||||
pass
|
||||
});
|
||||
let shown = dialog.show(ui, |ui, _| controls(ui, window, drafts, waiting));
|
||||
let pass = shown.inner.unwrap_or_default();
|
||||
if pass.layer.is_some() {
|
||||
self.layer = pass.layer;
|
||||
@@ -418,6 +406,46 @@ impl StackDialog for ScriptWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// The heading of the ScriptUI window `w`: its title, or "Script Alert" without one.
|
||||
pub(crate) fn heading(w: &ScriptUiDialog) -> String {
|
||||
match w.title() {
|
||||
"" => tl!("Script Alert").to_string(),
|
||||
title => shown_text(title, false),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<u64, String>, usable: bool) -> 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() };
|
||||
ui.scope(|ui| {
|
||||
ui.set_max_size(MAX_SHOWN);
|
||||
Stack::new().scroll(Scroll::both()).show(ui, |ui, _| {
|
||||
let origin = ui.cursor().min;
|
||||
ui.set_min_size(size);
|
||||
// Each container comes before the controls it holds.
|
||||
let mut containers: Vec<Option<egui::Id>> = vec![None; w.nodes.len()];
|
||||
for (i, n) in w.nodes.iter().enumerate().skip(1) {
|
||||
if !n.visible {
|
||||
continue;
|
||||
}
|
||||
let parent = containers.get(n.parent).copied().flatten();
|
||||
let place = Place { origin, enabled: usable && n.enabled, default: w.default_element == Some(i), parent };
|
||||
let shown = control(ui, drafts, &place, (i, n, prompt_of(w, i)));
|
||||
if let Some(slot) = containers.get_mut(i) {
|
||||
*slot = shown.container;
|
||||
}
|
||||
pass.typing |= shown.typing;
|
||||
pass.events.extend(shown.event);
|
||||
pass.drafts.extend(shown.draft.map(|d| (n.id, d)));
|
||||
}
|
||||
});
|
||||
});
|
||||
pass
|
||||
}
|
||||
|
||||
/// Where a control is drawn: from `origin`, enabled or not, whether it is the default button, and
|
||||
/// the accessibility node of the group or panel that holds it.
|
||||
struct Place {
|
||||
@@ -441,10 +469,10 @@ struct Shown {
|
||||
/// What one run of the dialog's body gave: the events, whether an edit field has the keyboard
|
||||
/// focus, the typed texts to keep or forget, by field id, and the overlay layer it was drawn in.
|
||||
#[derive(Default)]
|
||||
struct Pass {
|
||||
events: Vec<UiEvent>,
|
||||
pub(crate) struct Pass {
|
||||
pub(crate) events: Vec<UiEvent>,
|
||||
typing: bool,
|
||||
drafts: Vec<(u64, Option<String>)>,
|
||||
pub(crate) drafts: Vec<(u64, Option<String>)>,
|
||||
layer: Option<egui::Id>,
|
||||
}
|
||||
|
||||
@@ -733,11 +761,24 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
|
||||
UiEvent::Change(i, UiValue::Text(t)) => w.nodes.get(*i).map(|n| (n.id, t.clone())),
|
||||
_ => None,
|
||||
};
|
||||
if let Err(e) = give(app, &w, event) {
|
||||
if let Some((id, text)) = typed {
|
||||
with_window(app, |d| d.drafts.insert(id, text));
|
||||
match give(app, &w, event) {
|
||||
// The event lets the run go on, which the app idles for while it waits: the next frame
|
||||
// takes the run's next slice.
|
||||
Ok(()) => {
|
||||
if let Some(ctx) = &app.ui_ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some((id, text)) = typed {
|
||||
with_window(app, |d| d.drafts.insert(id, text));
|
||||
}
|
||||
app.status(e);
|
||||
// The next frame gives the run the next queued event.
|
||||
if let Some(ctx) = &app.ui_ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -747,12 +788,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp) {
|
||||
/// next wait.
|
||||
fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result<(), String> {
|
||||
let mut events = vec![check_event(w, event)?];
|
||||
// When the run does not take the first event, the typed texts stay in their fields.
|
||||
let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default();
|
||||
if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) {
|
||||
with_window(app, |d| d.commit_drafts(w, &mut events)).unwrap_or(Ok(()))?;
|
||||
}
|
||||
let mut events = events.into_iter();
|
||||
if let Some(first) = events.next() {
|
||||
app.session.script_window_answer(first)?;
|
||||
if let Some(first) = events.next()
|
||||
&& let Err(e) = app.session.script_window_answer(first)
|
||||
{
|
||||
with_window(app, |d| d.drafts = drafts);
|
||||
return Err(e);
|
||||
}
|
||||
let later: Vec<Queued> = events.filter_map(|e| queued(w, &e)).collect();
|
||||
with_window(app, |d| {
|
||||
@@ -794,6 +840,8 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string());
|
||||
};
|
||||
let mut events = vec![cancel_event(&w)];
|
||||
// When the run does not take the first event, the typed texts stay in their fields.
|
||||
let drafts = with_window(app, |d| d.drafts.clone()).unwrap_or_default();
|
||||
with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?;
|
||||
let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true);
|
||||
// A cancel after other events goes last, and is a click on the cancel button of the dialog the
|
||||
@@ -803,8 +851,12 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> {
|
||||
events.pop();
|
||||
}
|
||||
let mut events = events.into_iter();
|
||||
if empty && let Some(first) = events.next() {
|
||||
app.session.script_window_answer(first)?;
|
||||
if empty
|
||||
&& let Some(first) = events.next()
|
||||
&& let Err(e) = app.session.script_window_answer(first)
|
||||
{
|
||||
with_window(app, |d| d.drafts = drafts);
|
||||
return Err(e);
|
||||
}
|
||||
let mut later: Vec<Queued> = events.filter_map(|e| queued(&w, &e)).collect();
|
||||
if deferred {
|
||||
|
||||
@@ -6622,6 +6622,8 @@ liquify-list-end {0}, {1} {0} i {1}
|
||||
@msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name}
|
||||
@msg `answers` must be a list of answers `answers` ha de ser una llista de respostes
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` té més de {MAX_ANSWERS} respostes
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept ja esperen {MAX_WAITING} esdeveniments de paletes d'scripts; aquest no s'ha conservat
|
||||
@msg The list's items changed before the choice was taken Els elements de la llista han canviat abans que es prengués l'elecció
|
||||
@msg `answers` is larger than 1 MiB `answers` ocupa més d'1 MiB
|
||||
@msg must be an object with `kind` and `value` ha de ser un objecte amb `kind` i `value`
|
||||
@msg must have exactly `kind` and `value` ha de tenir exactament `kind` i `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9147,6 +9147,8 @@ breakText Glyphs Glyfy
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` musí uvádět indexy kotevních bodů (0, 1, 2…), ne {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` pro tento dialog {kind} musí být jedna z hodnot: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` má více než {MAX_ANSWERS} odpovědí
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept už čeká {MAX_WAITING} událostí palet skriptů; tato nebyla zachována
|
||||
@msg The list's items changed before the choice was taken Položky seznamu se změnily dříve, než byla volba převzata
|
||||
@msg `answers` is larger than 1 MiB `answers` je větší než 1 MiB
|
||||
@msg `answers` must be a list of answers `answers` musí být seznam odpovědí
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` musí být index pracovní plochy dokumentu
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -228,6 +228,8 @@ liquify-list-end {0}, {1} {0} og {1}
|
||||
@msg there is no script engine named {name} der findes ingen scriptmotor med navnet {name}
|
||||
@msg `answers` must be a list of answers `answers` skal være en liste med svar
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` har flere end {MAX_ANSWERS} svar
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} hændelser fra scriptpaletter venter allerede; denne blev ikke gemt
|
||||
@msg The list's items changed before the choice was taken Listens elementer blev ændret, før valget blev modtaget
|
||||
@msg `answers` is larger than 1 MiB `answers` er større end 1 MiB
|
||||
@msg `answers[{i}]` {e} `answers[{i}]` {e}
|
||||
@msg must be an object with `kind` and `value` skal være et objekt med `kind` og `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8585,6 +8585,8 @@ breakText Glyphs Glyphen
|
||||
@msg `align` must be a string `align` muss ein String sein
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` für dieses {kind}-Dialogfeld muss eines der folgenden sein: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} Ereignisse von Skriptpaletten warten bereits; dieses wurde nicht behalten
|
||||
@msg The list's items changed before the choice was taken Die Einträge der Liste haben sich geändert, bevor die Auswahl übernommen wurde
|
||||
@msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2812,6 +2812,8 @@ liquify-list-end {0}, {1} {0} και {1}
|
||||
@msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name}
|
||||
@msg `answers` must be a list of answers το `answers` πρέπει να είναι λίστα απαντήσεων
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers το `answers` έχει περισσότερες από {MAX_ANSWERS} απαντήσεις
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept ήδη περιμένουν {MAX_WAITING} συμβάντα παλετών σεναρίων· αυτό δεν κρατήθηκε
|
||||
@msg The list's items changed before the choice was taken Τα στοιχεία της λίστας άλλαξαν πριν ληφθεί η επιλογή
|
||||
@msg `answers` is larger than 1 MiB το `answers` είναι μεγαλύτερο από 1 MiB
|
||||
@msg `answers[{i}]` {e} το `answers[{i}]` {e}
|
||||
@msg must be an object with `kind` and `value` πρέπει να είναι αντικείμενο με `kind` και `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5091,6 +5091,8 @@ liquify-list-end {0}, {1} {0}, {1}
|
||||
@msg there is no script engine named {name} no hay ningún motor de scripts llamado {name}
|
||||
@msg `answers` must be a list of answers `answers` debe ser una lista de respuestas
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` tiene más de {MAX_ANSWERS} respuestas
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept ya esperan {MAX_WAITING} eventos de paletas de scripts; este no se ha conservado
|
||||
@msg The list's items changed before the choice was taken Los elementos de la lista cambiaron antes de que se tomara la elección
|
||||
@msg `answers` is larger than 1 MiB `answers` ocupa más de 1 MiB
|
||||
@msg must be an object with `kind` and `value` debe ser un objeto con `kind` y `value`
|
||||
@msg must have exactly `kind` and `value` debe tener exactamente `kind` y `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5334,6 +5334,8 @@ liquify-list-end {0}, {1} {0} ja {1}
|
||||
@msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole
|
||||
@msg `answers` must be a list of answers `answers` on oltava vastausten luettelo
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers kohteessa `answers` on yli {MAX_ANSWERS} vastausta
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} skriptipalettien tapahtumaa odottaa jo; tätä ei säilytetty
|
||||
@msg The list's items changed before the choice was taken Luettelon kohteet muuttuivat ennen kuin valinta otettiin vastaan
|
||||
@msg `answers` is larger than 1 MiB `answers` on suurempi kuin 1 MiB
|
||||
@msg must be an object with `kind` and `value` on oltava objekti, jossa on `kind` ja `value`
|
||||
@msg must have exactly `kind` and `value` siinä on oltava täsmälleen `kind` ja `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9014,6 +9014,8 @@ breakText Glyphs Glyphes
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` contient plus de {MAX_ANSWERS} réponses
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} événements de palettes de script attendent déjà, celui-ci n’a donc pas été conservé
|
||||
@msg The list's items changed before the choice was taken Les éléments de la liste ont changé avant que le choix soit pris en compte
|
||||
@msg `answers` is larger than 1 MiB `answers` dépasse 1 Mio
|
||||
@msg `answers` must be a list of answers `answers` doit être une liste de réponses
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` doit être l’indice d’un plan de travail du document
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7830,6 +7830,8 @@ liquify-list-end {0}, {1} {0} और {1}
|
||||
@msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है
|
||||
@msg `answers` must be a list of answers `answers` उत्तरों की सूची होनी चाहिए
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` में {MAX_ANSWERS} से अधिक उत्तर हैं
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept स्क्रिप्ट पैलेट की {MAX_WAITING} घटनाएँ पहले से प्रतीक्षा में हैं; यह नहीं रखी गई
|
||||
@msg The list's items changed before the choice was taken चुनाव लिए जाने से पहले सूची के आइटम बदल गए
|
||||
@msg `answers` is larger than 1 MiB `answers` 1 MiB से बड़ा है
|
||||
@msg `answers[{i}]` {e} `answers[{i}]`: {e}
|
||||
@msg must be an object with `kind` and `value` `kind` और `value` वाला ऑब्जेक्ट होना चाहिए
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9018,6 +9018,8 @@ breakText Glyphs Glifák
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`: horgonypont-indexek listája kell (0, 1, 2…), ez nem az: {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer`: ennél a párbeszédablaknál ({kind}) ezek egyike kell: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers`: több mint {MAX_ANSWERS} választ tartalmaz
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept már {MAX_WAITING} parancsfájlpaletta-esemény várakozik; ez nem lett megtartva
|
||||
@msg The list's items changed before the choice was taken A lista elemei megváltoztak, mielőtt a választás érvénybe lépett
|
||||
@msg `answers` is larger than 1 MiB `answers`: nagyobb 1 MiB-nál
|
||||
@msg `answers` must be a list of answers `answers`: válaszok listája kell
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard`: a dokumentum egyik rajztáblájának indexe kell
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -135,6 +135,8 @@
|
||||
@msg {name}: `answers` has no answer left for this dialog {name}: `answers` tidak memiliki jawaban tersisa untuk dialog ini
|
||||
@msg `answers` must be a list of answers `answers` harus berupa daftar jawaban
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` berisi lebih dari {MAX_ANSWERS} jawaban
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} peristiwa palet skrip sudah menunggu; yang ini tidak disimpan
|
||||
@msg The list's items changed before the choice was taken Item daftar berubah sebelum pilihan diterima
|
||||
@msg `answers` is larger than 1 MiB `answers` lebih besar dari 1 MiB
|
||||
@msg must be an object with `kind` and `value` harus berupa objek dengan `kind` dan `value`
|
||||
@msg must have exactly `kind` and `value` harus memiliki tepat `kind` dan `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8626,6 +8626,8 @@ breakText Glyphs Glifi
|
||||
@msg `align` must be a string `align` deve essere una stringa
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` per questa finestra di dialogo {kind} deve essere uno tra: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} eventi delle palette di script sono già in attesa; questo non è stato conservato
|
||||
@msg The list's items changed before the choice was taken Le voci dell'elenco sono cambiate prima che la scelta fosse acquisita
|
||||
@msg `answers` is larger than 1 MiB `answers` supera 1 MiB
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7428,6 +7428,8 @@ axis Y Axis Y 軸
|
||||
@msg `align` must be a string `align` には文字列を指定してください
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} この {kind} ダイアログの `answer` には次のいずれかを指定してください: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` の回答が {MAX_ANSWERS} 個を超えています
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept スクリプトパレットのイベントがすでに {MAX_WAITING} 件待機しているため、このイベントは保持されませんでした
|
||||
@msg The list's items changed before the choice was taken 選択が受け付けられる前にリストの項目が変更されました
|
||||
@msg `answers` is larger than 1 MiB `answers` が 1 MiB を超えています
|
||||
@msg `answers` must be a list of answers `answers` には回答のリストを指定してください
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` にはドキュメントのアートボードのインデックスを指定してください
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -177,6 +177,8 @@
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} დიალოგისთვის (ტიპი: {kind}) `answer` უნდა იყოს ერთ-ერთი: {_1}
|
||||
@msg `answers[{i}]` {e} `answers[{i}]` {e}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` შეიცავს {MAX_ANSWERS}-ზე მეტ პასუხს
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept სკრიპტის პალიტრების {MAX_WAITING} მოვლენა უკვე ელოდება; ეს არ შენარჩუნდა
|
||||
@msg The list's items changed before the choice was taken სიის ელემენტები შეიცვალა არჩევანის მიღებამდე
|
||||
@msg `answers` is larger than 1 MiB `answers` 1 MiB-ზე დიდია
|
||||
@msg `answers` must be a list of answers `answers` უნდა იყოს პასუხების სია
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8784,6 +8784,8 @@ breakText Glyphs 글리프
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors`에는 앵커 인덱스(0, 1, 2…)를 나열해야 합니다: {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} 이 {kind} 대화 상자의 `answer`은(는) 다음 중 하나여야 합니다: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers`에 응답이 {MAX_ANSWERS}개보다 많습니다
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept 스크립트 팔레트 이벤트가 이미 {MAX_WAITING}개 대기 중이므로 이 이벤트는 보관되지 않았습니다
|
||||
@msg The list's items changed before the choice was taken 선택이 적용되기 전에 목록의 항목이 변경되었습니다
|
||||
@msg `answers` is larger than 1 MiB `answers`이(가) 1 MiB보다 큽니다
|
||||
@msg `answers` must be a list of answers `answers`은(는) 응답 목록이어야 합니다
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard`은(는) 문서에 있는 아트보드의 인덱스여야 합니다
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -6645,6 +6645,8 @@ imageTrace Outline Contour
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` moet ankerindexen bevatten (0, 1, 2…), niet {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` voor dit dialoogvenster {kind} moet een van de volgende zijn: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` heeft meer dan {MAX_ANSWERS} antwoorden
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept er wachten al {MAX_WAITING} gebeurtenissen van scriptpaletten; deze is niet bewaard
|
||||
@msg The list's items changed before the choice was taken De items van de lijst zijn gewijzigd voordat de keuze werd overgenomen
|
||||
@msg `answers` is larger than 1 MiB `answers` is groter dan 1 MiB
|
||||
@msg `answers` must be a list of answers `answers` moet een lijst met antwoorden zijn
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` moet de index van een tekengebied van het document zijn
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8829,6 +8829,8 @@ breakText Glyphs Glify
|
||||
@msg `align` must be a string `align` musi być ciągiem znaków
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` dla tego okna dialogowego {kind} musi mieć jedną z wartości: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept czeka już {MAX_WAITING} zdarzeń palet skryptów; to zdarzenie nie zostało zachowane
|
||||
@msg The list's items changed before the choice was taken Elementy listy zmieniły się, zanim wybór został przyjęty
|
||||
@msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -9200,6 +9200,8 @@ swatch Yellow Green Verde-amarelado
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` deve listar índices de pontos de ancoragem (0, 1, 2…), não {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` para esta caixa de diálogo {kind} deve ser um de: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept já há {MAX_WAITING} eventos de paletas de script aguardando; este não foi mantido
|
||||
@msg The list's items changed before the choice was taken Os itens da lista mudaram antes de a escolha ser aplicada
|
||||
@msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5116,6 +5116,8 @@ liquify-list-end {0}, {1} {0} и {1}
|
||||
@msg there is no script engine named {name} движка скриптов с именем {name} нет
|
||||
@msg `answers` must be a list of answers `answers` должен быть списком ответов
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers в `answers` больше {MAX_ANSWERS} ответов
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept уже ожидают {MAX_WAITING} событий палитр скриптов; это событие не сохранено
|
||||
@msg The list's items changed before the choice was taken Элементы списка изменились до того, как выбор был принят
|
||||
@msg `answers` is larger than 1 MiB `answers` больше 1 МиБ
|
||||
@msg must be an object with `kind` and `value` должен быть объектом с `kind` и `value`
|
||||
@msg must have exactly `kind` and `value` должен содержать ровно `kind` и `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4988,6 +4988,8 @@ liquify-list-end {0}, {1} {0} och {1}
|
||||
@msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name}
|
||||
@msg `answers` must be a list of answers `answers` måste vara en lista med svar
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` har fler än {MAX_ANSWERS} svar
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} händelser från skriptpaletter väntar redan; den här sparades inte
|
||||
@msg The list's items changed before the choice was taken Listans objekt ändrades innan valet togs emot
|
||||
@msg `answers` is larger than 1 MiB `answers` är större än 1 MiB
|
||||
@msg `answers[{i}]` {e} `answers[{i}]` {e}
|
||||
@msg must be an object with `kind` and `value` måste vara ett objekt med `kind` och `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -7806,6 +7806,8 @@ axis Y Axis Y ekseni
|
||||
@msg `align` must be a string `align` bir dize olmalıdır
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} bu {kind} iletişim kutusu için `answer` şunlardan biri olmalıdır: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` içinde {MAX_ANSWERS} taneden fazla yanıt var
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept {MAX_WAITING} betik paleti olayı zaten bekliyor; bu olay tutulmadı
|
||||
@msg The list's items changed before the choice was taken Seçim alınmadan önce listenin öğeleri değişti
|
||||
@msg `answers` is larger than 1 MiB `answers` 1 MiB'tan büyük
|
||||
@msg `answers` must be a list of answers `answers` bir yanıt listesi olmalıdır
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard`, belgedeki bir çalışma yüzeyinin dizini olmalıdır
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8785,6 +8785,8 @@ breakText Glyphs Гліфи
|
||||
@msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` має містити індекси опорних точок (0, 1, 2…), а не {v}
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} `answer` для цього діалогового вікна ({kind}) має бути одним з: {_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept уже очікують {MAX_WAITING} подій палітр скриптів; цю подію не збережено
|
||||
@msg The list's items changed before the choice was taken Елементи списку змінилися до того, як вибір було прийнято
|
||||
@msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1}
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5616,6 +5616,8 @@ liquify-list-end {0}, {1} {0} và {1}
|
||||
@msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name}
|
||||
@msg `answers` must be a list of answers `answers` phải là một danh sách câu trả lời
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` có hơn {MAX_ANSWERS} câu trả lời
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept đã có {MAX_WAITING} sự kiện bảng tập lệnh đang chờ; sự kiện này không được giữ lại
|
||||
@msg The list's items changed before the choice was taken Các mục của danh sách đã thay đổi trước khi lựa chọn được nhận
|
||||
@msg `answers` is larger than 1 MiB `answers` lớn hơn 1 MiB
|
||||
@msg must be an object with `kind` and `value` phải là một đối tượng có `kind` và `value`
|
||||
@msg must have exactly `kind` and `value` phải có đúng `kind` và `value`
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8837,6 +8837,8 @@ breakText Glyphs 字形
|
||||
@msg `align` must be a string `align` 必须是字符串
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 对话框的 `answer` 必须是以下之一:{_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 个脚本面板事件在等待;此事件未保留
|
||||
@msg The list's items changed before the choice was taken 在采用选择之前,列表的项目已更改
|
||||
@msg `answers` is larger than 1 MiB `answers` 大于 1 MiB
|
||||
@msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框
|
||||
@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -8780,6 +8780,8 @@ breakText Glyphs 字符
|
||||
@msg `align` must be a string `align` 必須是字串
|
||||
@msg `answer` for this {kind} dialog must be one of: {_1} 此 {kind} 對話框的 `answer` 必須是下列其中之一:{_1}
|
||||
@msg `answers` has more than {MAX_ANSWERS} answers `answers` 的答案超過 {MAX_ANSWERS} 個
|
||||
@msg {MAX_WAITING} script palette events already wait; this one was not kept 已有 {MAX_WAITING} 個指令碼面板事件在等待;此事件未保留
|
||||
@msg The list's items changed before the choice was taken 在採用選擇之前,清單的項目已變更
|
||||
@msg `answers` is larger than 1 MiB `answers` 大於 1 MiB
|
||||
@msg `answers` must be a list of answers `answers` 必須是答案清單
|
||||
@msg `artboard` must be the index of an artboard of the document `artboard` 必須是文件中某個工作區域的索引
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -74,6 +74,7 @@ pub mod recovery;
|
||||
pub mod render_worker;
|
||||
pub mod retype_runs;
|
||||
pub mod screen_color;
|
||||
pub mod script_palettes;
|
||||
pub mod script_runs;
|
||||
pub mod scripts_menu;
|
||||
mod settings;
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
//! The ScriptUI palettes a script shows with `new Window("palette")` in a named engine
|
||||
//! ([`vectorcraft_engine::script::palettes`]): each shown palette is a modeless dialog on the
|
||||
//! window's dialog host (kind `scriptPalette`) that stays open after the run, with the controls the
|
||||
//! engine laid out. A click, a change or the close box waits in the session's line and runs as a
|
||||
//! script run of its own once no run is going ([`crate::script_runs::poll`]), unless a run of the
|
||||
//! palette's engine calls `update()` in its own code first and handles it inside that run; the
|
||||
//! palette stays usable while a run goes on, and its events wait for it. A palette does not take
|
||||
//! the keyboard focus when it opens or changes. An edit field's text is given when it loses the
|
||||
//! focus, at Enter in a one-line field, or before a click or a close; a text the script would
|
||||
//! refuse, or that the full line refuses, stays in its field with the error in the status bar, and
|
||||
//! the click or close after it is not given.
|
||||
//!
|
||||
//! The dialog's body has no app, so it keeps what the person did, and [`show`] follows the
|
||||
//! session's palettes into the host each frame and puts the events in line.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
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;
|
||||
use crate::dialogs::script_run::with_host;
|
||||
use crate::dialogs::script_window::{self, Queued};
|
||||
|
||||
/// The dialog kind of a ScriptUI palette.
|
||||
pub const KIND: &str = "scriptPalette";
|
||||
|
||||
/// The dialog id of the palette `id` ([`ScriptPalette::id`]).
|
||||
pub(crate) fn palette_id(id: u64) -> DialogId {
|
||||
dialog_id((KIND, id))
|
||||
}
|
||||
|
||||
/// One batch of given events: its pass's scope, its own scope, the events, and the typed texts as
|
||||
/// they were in its pass, each with its typing scope.
|
||||
type Given = (ScopeHandle, ScopeHandle, Vec<Queued>, BTreeMap<u64, (String, ScopeHandle)>);
|
||||
|
||||
/// A shown palette on the window's dialog host.
|
||||
pub(crate) struct PaletteWindow {
|
||||
/// The palette as the session has it, from the last frame.
|
||||
palette: ScriptPalette,
|
||||
/// The text typed in each edit field that the script has not had yet, by the field's id.
|
||||
drafts: BTreeMap<u64, String>,
|
||||
/// Each draft's typing scope, narrowed by every pass that edits the text.
|
||||
draft_scopes: BTreeMap<u64, ScopeHandle>,
|
||||
/// 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. Each batch also keeps the typed texts as
|
||||
/// they were in its pass, so a click or close gives only the texts typed before it.
|
||||
given: Vec<Given>,
|
||||
/// The text each edit field gave the script, by the field's id, while its change waits: the
|
||||
/// 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<u64, String>,
|
||||
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 }
|
||||
}
|
||||
|
||||
/// The palette as the session has it now. A typed text whose field the palette no longer has is
|
||||
/// dropped, and so is a given text once its change no longer waits in the session (`waiting`:
|
||||
/// [`vectorcraft_engine::Session::script_palette_changes_waiting`]).
|
||||
fn sync(&mut self, palette: ScriptPalette, waiting: &[(u64, u64)]) {
|
||||
self.palette = palette;
|
||||
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));
|
||||
}
|
||||
|
||||
/// 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);
|
||||
self.take_pass(pass.drafts.into_iter().collect(), pass.events);
|
||||
}
|
||||
|
||||
/// The text edit field `i` shows.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn shown_text(&self, i: usize) -> Option<String> {
|
||||
let id = self.palette.dialog.nodes.get(i)?.id;
|
||||
self.drafts.get(&id).cloned().or_else(|| shown_dialog(&self.palette.dialog, &self.pending).nodes.get(i).map(|n| n.text.clone()))
|
||||
}
|
||||
|
||||
/// The text typed in edit field `i` that the script has not had yet.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn typed(&self, i: usize) -> Option<&str> {
|
||||
self.palette.dialog.nodes.get(i).and_then(|n| self.drafts.get(&n.id)).map(String::as_str)
|
||||
}
|
||||
|
||||
/// Types `text` in edit field `i`, as the person does before the field loses the focus.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn type_text(&mut self, i: usize, text: &str) {
|
||||
if let Some(n) = self.palette.dialog.nodes.get(i) {
|
||||
self.take_pass(vec![(n.id, Some(text.to_string()))], Vec::new());
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives the text typed in edit field `i` as `text`, as the field does at Enter or when it loses
|
||||
/// 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()))]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes one pass's typed texts (by field index) and events, as the palette's body reports them.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn pass(&mut self, drafts: &[(usize, Option<&str>)], events: Vec<UiEvent>) {
|
||||
let drafts = drafts.iter().filter_map(|(i, t)| self.palette.dialog.nodes.get(*i).map(|n| (n.id, t.map(str::to_string)))).collect();
|
||||
self.take_pass(drafts, events);
|
||||
}
|
||||
|
||||
/// Gives `event`, as the person does in the palette.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn give(&mut self, event: UiEvent) {
|
||||
self.record(std::slice::from_ref(&event), &BTreeMap::new());
|
||||
}
|
||||
|
||||
/// Takes what the person did in one pass: the typed texts (`None` for a field whose text was
|
||||
/// given or dropped) and the events. A typed text keeps the scope of each pass that edited it,
|
||||
/// narrowed to what all of them allow, and a text the field gives goes in line in that scope.
|
||||
fn take_pass(&mut self, drafts: Vec<(u64, Option<String>)>, events: Vec<UiEvent>) {
|
||||
let mut committed = BTreeMap::new();
|
||||
for (id, draft) in drafts {
|
||||
match draft {
|
||||
Some(text) => {
|
||||
// A pass that leaves the text as it was leaves its scope as it was too.
|
||||
let edited = self.drafts.get(&id) != Some(&text);
|
||||
let scope = match self.draft_scopes.remove(&id) {
|
||||
Some(typed) if edited => typed.within_current(),
|
||||
Some(typed) => typed,
|
||||
None => ScopeHandle::capture_now(),
|
||||
};
|
||||
self.draft_scopes.insert(id, scope);
|
||||
self.drafts.insert(id, text);
|
||||
}
|
||||
None => {
|
||||
if let Some(typed) = self.draft_scopes.remove(&id) {
|
||||
committed.insert(id, typed);
|
||||
}
|
||||
self.drafts.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
for e in &events {
|
||||
if let UiEvent::Change(i, UiValue::Text(text)) = e
|
||||
&& let Some(n) = self.palette.dialog.nodes.get(*i)
|
||||
{
|
||||
self.pending.insert(n.id, text.clone());
|
||||
}
|
||||
}
|
||||
self.record(&events, &committed);
|
||||
}
|
||||
|
||||
/// Puts `events` in line in the scope of the calling thread, except that a field's change takes
|
||||
/// the scope its text was typed in (`committed`), narrowed to this one. Every click or close
|
||||
/// in the pass also takes what all of those text scopes allow.
|
||||
fn record(&mut self, events: &[UiEvent], committed: &BTreeMap<u64, ScopeHandle>) {
|
||||
let here = ScopeHandle::capture_now();
|
||||
let given: Vec<ScopeHandle> = events
|
||||
.iter()
|
||||
.filter_map(|e| match e {
|
||||
UiEvent::Change(i, UiValue::Text(_)) => self.palette.dialog.nodes.get(*i).and_then(|n| committed.get(&n.id)),
|
||||
_ => None,
|
||||
})
|
||||
.map(|t| t.clone().within_current())
|
||||
.collect();
|
||||
let mut events: Vec<_> = events.iter().collect();
|
||||
events.sort_by_key(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close));
|
||||
let mut batches: Vec<(ScopeHandle, Vec<Queued>)> = Vec::new();
|
||||
for e in events {
|
||||
let Some(q) = script_window::queued(&self.palette.dialog, e) else { continue };
|
||||
let typed = match e {
|
||||
UiEvent::Change(i, UiValue::Text(_)) => self.palette.dialog.nodes.get(*i).and_then(|n| committed.get(&n.id)),
|
||||
_ => None,
|
||||
};
|
||||
let mut scope = typed.map_or_else(|| here.clone(), |t| t.clone().within_current());
|
||||
if matches!(e, UiEvent::Click(_) | UiEvent::Close) {
|
||||
for t in &given {
|
||||
scope = t.clone().run(|| scope.within_current());
|
||||
}
|
||||
}
|
||||
match batches.last_mut() {
|
||||
Some((last, list)) if last.same(&scope) => list.push(q),
|
||||
_ => batches.push((scope, vec![q])),
|
||||
}
|
||||
}
|
||||
let seen: BTreeMap<u64, (String, ScopeHandle)> =
|
||||
self.drafts.iter().filter_map(|(id, text)| self.draft_scopes.get(id).map(|s| (*id, (text.clone(), s.clone())))).collect();
|
||||
self.given.extend(batches.into_iter().map(|(scope, events)| (here.clone(), scope, events, seen.clone())));
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for PaletteWindow {
|
||||
type Result = ();
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
palette_id(self.palette.id)
|
||||
}
|
||||
|
||||
fn instance(&self) -> Option<DialogId> {
|
||||
Some(self.id())
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KIND)
|
||||
}
|
||||
|
||||
fn modeless(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let heading = script_window::heading(&self.palette.dialog);
|
||||
let PaletteWindow { palette, drafts, pending, 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
|
||||
// applied after the container.
|
||||
let shown = Dialog::new(heading)
|
||||
.modeless()
|
||||
.initial_focus(Initial::Keep)
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui, |ui, _| script_window::controls(ui, &dialog, drafts_now, true));
|
||||
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
|
||||
// it.
|
||||
if shown.output.closed.is_some() {
|
||||
self.open = true;
|
||||
events.push(UiEvent::Close);
|
||||
}
|
||||
self.take_pass(pass.drafts.into_iter().collect(), events);
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The controls of `dialog` as the fields show them: a given text whose change waits (`pending`)
|
||||
/// stands in for its field's text.
|
||||
fn shown_dialog<'a>(dialog: &'a ScriptUiDialog, pending: &BTreeMap<u64, String>) -> std::borrow::Cow<'a, ScriptUiDialog> {
|
||||
if pending.is_empty() {
|
||||
return std::borrow::Cow::Borrowed(dialog);
|
||||
}
|
||||
let mut dialog = dialog.clone();
|
||||
for n in &mut dialog.nodes {
|
||||
if let Some(text) = pending.get(&n.id) {
|
||||
n.text.clone_from(text);
|
||||
}
|
||||
}
|
||||
std::borrow::Cow::Owned(dialog)
|
||||
}
|
||||
|
||||
/// Follows the session's shown palettes into the dialog host: opens a palette that shows, updates
|
||||
/// one that changed and closes one that was hidden or closed. Then puts the events the person gave
|
||||
/// each palette in line.
|
||||
pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
let shown: Vec<ScriptPalette> = 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 waiting = s.script_palette_changes_waiting();
|
||||
let taken = with_host(app, |host, ctx| {
|
||||
let ids: Vec<DialogId> = shown.iter().map(|p| palette_id(p.id)).collect();
|
||||
for d in host.open_dialogs() {
|
||||
if d.key.as_deref() == Some(KIND) && !ids.contains(&d.id) {
|
||||
host.cancel_by_id(ctx, d.id);
|
||||
let _ = host.take_by_id::<PaletteWindow>(d.id);
|
||||
}
|
||||
}
|
||||
let mut taken = Vec::new();
|
||||
for p in &shown {
|
||||
match host.get_mut_by_id::<PaletteWindow>(palette_id(p.id)) {
|
||||
Some(w) => {
|
||||
w.sync(p.clone(), &waiting);
|
||||
taken.push((p.id, std::mem::take(&mut w.drafts), std::mem::take(&mut w.draft_scopes), std::mem::take(&mut w.given)));
|
||||
}
|
||||
None if !modal => {
|
||||
host.open(PaletteWindow::new(p.clone()));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
taken
|
||||
})
|
||||
.unwrap_or_default();
|
||||
for (id, mut drafts, mut draft_scopes, given) in taken {
|
||||
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 change_refused = false;
|
||||
// Texts whose change went in line, typed ones a click or close gave included: the field
|
||||
// shows each until its change no longer waits.
|
||||
let mut accepted = BTreeMap::new();
|
||||
for (pass_scope, scope, given, seen) in given {
|
||||
let mut events: Vec<UiEvent> = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect();
|
||||
// Only the texts typed by this batch's pass are given with its click or close; a text
|
||||
// typed in a later pass stays in its field. A text this frame already gave is not given
|
||||
// again.
|
||||
let seen: BTreeMap<u64, (String, ScopeHandle)> =
|
||||
seen.into_iter().filter(|(field, (text, _))| accepted.get(field) != Some(text)).collect();
|
||||
let mut at_pass: BTreeMap<u64, String> = seen.iter().map(|(field, (text, _))| (*field, text.clone())).collect();
|
||||
// Each text keeps the scope it had when it was typed, even when a later pass gave it.
|
||||
let at_scopes: BTreeMap<u64, ScopeHandle> = seen.into_iter().map(|(field, (_, s))| (field, s)).collect();
|
||||
script_window::keep_fields(&p.dialog, &mut at_pass);
|
||||
// A field's change carrying a text this frame already gave is not given a second time.
|
||||
events.retain(|e| match e {
|
||||
UiEvent::Change(i, UiValue::Text(text)) => p.dialog.nodes.get(*i).is_none_or(|n| accepted.get(&n.id) != Some(text)),
|
||||
_ => true,
|
||||
});
|
||||
let before = at_pass.clone();
|
||||
let (batch, refused) = drafted(app, &p.dialog, &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.
|
||||
for (field, text) in &before {
|
||||
if !at_pass.contains_key(field) && drafts.get(field) == Some(text) {
|
||||
drafts.remove(field);
|
||||
}
|
||||
}
|
||||
// A text refused in this batch goes back in its field unless a later one was typed there.
|
||||
for (field, text) in at_pass {
|
||||
if before.get(&field) != Some(&text) {
|
||||
drafts.entry(field).or_insert(text);
|
||||
}
|
||||
}
|
||||
for (event_scope, event) in batch {
|
||||
event_scope.run(|| give(app, ctx, p, &mut drafts, vec![event], &mut change_refused, &mut accepted));
|
||||
}
|
||||
// A text that went back in its field without a scope of its own takes this one.
|
||||
for field in drafts.keys() {
|
||||
draft_scopes.entry(*field).or_insert_with(|| scope.clone());
|
||||
}
|
||||
}
|
||||
draft_scopes.retain(|field, _| drafts.contains_key(field));
|
||||
with_host(app, |host, _| {
|
||||
if let Some(w) = host.get_mut_by_id::<PaletteWindow>(palette_id(id)) {
|
||||
// A refused text goes back in its field as typed, so the field does not show it as
|
||||
// given.
|
||||
w.pending.extend(accepted);
|
||||
w.pending.retain(|field, _| !drafts.contains_key(field));
|
||||
w.drafts = drafts;
|
||||
w.draft_scopes = draft_scopes;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Commits drafts in dialog order, each under its typing and committing scopes. Every draft is
|
||||
/// validated before any is removed. A refused draft keeps the click or close out of line. → the
|
||||
/// events with their scopes, and whether a text was refused.
|
||||
fn drafted(
|
||||
app: &mut VectorcraftApp,
|
||||
w: &ScriptUiDialog,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: &mut Vec<UiEvent>,
|
||||
scope: &ScopeHandle,
|
||||
pass_scope: &ScopeHandle,
|
||||
draft_scopes: &BTreeMap<u64, ScopeHandle>,
|
||||
) -> (Vec<(ScopeHandle, UiEvent)>, bool) {
|
||||
let mut refused = false;
|
||||
if let Some(e) = script_window::keep_refused(w, drafts, events) {
|
||||
app.status(e);
|
||||
refused = true;
|
||||
}
|
||||
let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close);
|
||||
let mut changes = Vec::new();
|
||||
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) {
|
||||
Ok(()) => {
|
||||
drop(changes.drain(..existing));
|
||||
}
|
||||
Err(e) => {
|
||||
changes.clear();
|
||||
events.retain(|e| !closing(e));
|
||||
app.status(e);
|
||||
refused = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut closing_scope = scope.clone();
|
||||
let changes: Vec<_> = changes
|
||||
.into_iter()
|
||||
.map(|event| {
|
||||
let typed = match &event {
|
||||
UiEvent::Change(i, _) => w.nodes.get(*i).and_then(|n| draft_scopes.get(&n.id)),
|
||||
_ => None,
|
||||
};
|
||||
let narrowed = pass_scope.clone().run(|| typed.map_or_else(|| pass_scope.clone(), |t| t.clone().within_current()));
|
||||
closing_scope = narrowed.clone().run(|| closing_scope.clone().within_current());
|
||||
(narrowed, event)
|
||||
})
|
||||
.collect();
|
||||
events.sort_by_key(closing);
|
||||
let at = events.iter().position(closing).unwrap_or(events.len());
|
||||
let mut given: Vec<_> = events.drain(..at).map(|e| (scope.clone(), e)).collect();
|
||||
given.extend(changes);
|
||||
given.extend(events.drain(..).map(|e| (closing_scope.clone(), e)));
|
||||
(given, refused)
|
||||
}
|
||||
|
||||
/// Puts the events the person gave the palette `p` in line, or shows why one was refused. A
|
||||
/// refused text goes back in its field (`drafts`), and once a change is refused, the clicks and
|
||||
/// closes after it are not given, so no handler runs without the change before it.
|
||||
fn give(
|
||||
app: &mut VectorcraftApp,
|
||||
ctx: &egui::Context,
|
||||
p: &ScriptPalette,
|
||||
drafts: &mut BTreeMap<u64, String>,
|
||||
events: Vec<UiEvent>,
|
||||
change_refused: &mut bool,
|
||||
accepted: &mut BTreeMap<u64, String>,
|
||||
) {
|
||||
for e in events {
|
||||
if *change_refused && matches!(e, UiEvent::Click(_) | UiEvent::Close) {
|
||||
continue;
|
||||
}
|
||||
let change = match &e {
|
||||
UiEvent::Change(i, value) => Some((*i, if let UiValue::Text(t) = value { Some(t.clone()) } else { None })),
|
||||
_ => None,
|
||||
};
|
||||
match app.session.script_palette_event(p.id, e) {
|
||||
// The next frame starts its run.
|
||||
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);
|
||||
}
|
||||
if let Some((i, Some(text))) = change
|
||||
&& let Some(n) = p.dialog.nodes.get(i)
|
||||
{
|
||||
accepted.insert(n.id, text);
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
Err(error) => {
|
||||
if let Some((i, text)) = change {
|
||||
// A text typed after the refused one stays in the field.
|
||||
if let Some((n, text)) = p.dialog.nodes.get(i).zip(text) {
|
||||
drafts.entry(n.id).or_insert(text);
|
||||
}
|
||||
*change_refused = true;
|
||||
}
|
||||
app.status(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f` on palette `id`'s dialog; `None` when it is not open.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_palette<R>(app: &VectorcraftApp, id: u64, f: impl FnOnce(&mut PaletteWindow) -> R) -> Option<R> {
|
||||
with_host(app, |host, _| host.get_mut_by_id::<PaletteWindow>(palette_id(id)).map(f)).flatten()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub(crate) fn can_start(app: &VectorcraftApp) -> bool {
|
||||
app.session.script_palette_can_start() && !crate::script_runs::waiting_for_print(app)
|
||||
}
|
||||
|
||||
/// Starts the run of the oldest waiting palette event when no run is going. → whether one started.
|
||||
/// A run that could not begin shows its own error: the last report is an earlier run's. The run
|
||||
/// lists the printers it may print to ([`crate::print::script_printers`]), as `script.run` does.
|
||||
pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool {
|
||||
if !can_start(app) {
|
||||
return false;
|
||||
}
|
||||
app.session.script_printers = crate::print::script_printers(app);
|
||||
let started = app.session.script_palette_start();
|
||||
app.session.script_printers = None;
|
||||
match started {
|
||||
None => false,
|
||||
Some(Ok(_)) => true,
|
||||
Some(Err(e)) => {
|
||||
app.status(e.to_string());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
//! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with
|
||||
//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog,
|
||||
//! waits for the person's answer. A run that prepared jobs for a printer ends with the question
|
||||
//! before they are sent.
|
||||
//! before they are sent. With no run going, the oldest event a ScriptUI palette waits with starts
|
||||
//! its run ([`crate::script_palettes`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::WindowView;
|
||||
@@ -21,7 +22,8 @@ pub(crate) fn waiting_for_print(app: &VectorcraftApp) -> bool {
|
||||
pub fn poll(app: &mut VectorcraftApp) {
|
||||
startup_failures(app);
|
||||
script_run::ask_print(app);
|
||||
if !app.session.script_running() {
|
||||
// With no run going, a waiting palette event starts its run.
|
||||
if !app.session.script_running() && !crate::script_palettes::start_next(app) {
|
||||
return;
|
||||
}
|
||||
script_run::settle_close(app);
|
||||
|
||||
@@ -46,6 +46,7 @@ mod saveext;
|
||||
mod screenmode;
|
||||
mod script_check;
|
||||
mod script_dialogs;
|
||||
mod script_palettes;
|
||||
mod script_print;
|
||||
mod script_run;
|
||||
mod script_window;
|
||||
|
||||
@@ -0,0 +1,878 @@
|
||||
//! A script's ScriptUI palette in the app: it stays open on the dialog host after the run, follows
|
||||
//! the session's palette, and a click on it waits in line and starts its handler's run on the next
|
||||
//! frame.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::script::{UiEvent, UiKind, UiValue};
|
||||
|
||||
use super::script_dialogs::{app, is_open};
|
||||
use crate::dialogs::script_run::ScriptNotice;
|
||||
use crate::script_palettes::{self, PaletteWindow, with_palette};
|
||||
use crate::{VectorcraftApp, menus, script_runs};
|
||||
|
||||
const TOOLS: &str = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \
|
||||
go.onClick = function () { vc.log('clicked'); }; p.show();";
|
||||
|
||||
fn start(app: &mut VectorcraftApp, source: &str) {
|
||||
menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap();
|
||||
}
|
||||
|
||||
fn run_to_end(app: &mut VectorcraftApp) {
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
return;
|
||||
}
|
||||
script_runs::poll(app);
|
||||
}
|
||||
panic!("the script did not end");
|
||||
}
|
||||
|
||||
/// Runs `source`, then follows its palettes into the dialog host. → the first palette's id.
|
||||
fn shown(app: &mut VectorcraftApp, source: &str) -> u64 {
|
||||
start(app, source);
|
||||
run_to_end(app);
|
||||
follow(app);
|
||||
app.session.script_palettes()[0].id
|
||||
}
|
||||
|
||||
/// The frame's follow of the session's palettes into the dialog host.
|
||||
fn follow(app: &mut VectorcraftApp) {
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
script_palettes::show(app, &ctx);
|
||||
}
|
||||
|
||||
/// One headless pass in which `f` runs. → how long until the pass asked for the next one;
|
||||
/// `Duration::MAX` when it asked for none.
|
||||
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 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)
|
||||
}
|
||||
|
||||
/// Runs passes of `f` until one asks for no frame at once. → whether one did.
|
||||
fn settle(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &egui::Context)) -> bool {
|
||||
(0..10).any(|_| !frame_delay(app, &mut f).is_zero())
|
||||
}
|
||||
|
||||
fn give(app: &VectorcraftApp, id: u64, event: UiEvent) {
|
||||
with_palette(app, id, |w| w.give(event)).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shown_palette_opens_on_the_dialog_host_and_closes_when_hidden() {
|
||||
let mut app = app();
|
||||
let id = shown(&mut app, TOOLS);
|
||||
assert!(is_open::<PaletteWindow>(&app), "the palette stays open after the run");
|
||||
start(&mut app, "#targetengine tools\np.hide();");
|
||||
run_to_end(&mut app);
|
||||
follow(&mut app);
|
||||
assert!(with_palette(&app, id, |_| ()).is_none(), "a hidden palette's dialog closes");
|
||||
start(&mut app, "#targetengine tools\np.show();");
|
||||
run_to_end(&mut app);
|
||||
follow(&mut app);
|
||||
assert!(with_palette(&app, id, |_| ()).is_some(), "showing it again opens it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_dialog_opens_while_a_palette_is_open() {
|
||||
let mut app = app();
|
||||
shown(&mut app, TOOLS);
|
||||
start(&mut app, "vc.log(confirm('Go?'));");
|
||||
for _ in 0..10_000 {
|
||||
if is_open::<ScriptNotice>(&app) {
|
||||
break;
|
||||
}
|
||||
assert!(app.session.script_running(), "the run waits at its confirm");
|
||||
script_runs::poll(&mut app);
|
||||
}
|
||||
assert!(is_open::<ScriptNotice>(&app), "the palette beside the documents does not keep the confirm from opening");
|
||||
assert!(is_open::<PaletteWindow>(&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::<PaletteWindow>(&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();
|
||||
let id = shown(&mut app, TOOLS);
|
||||
assert!(settle(&mut app, |_, _| {}), "an idle pass asks for no other");
|
||||
give(&app, id, UiEvent::Click(1));
|
||||
assert!(frame_delay(&mut app, script_palettes::show).is_zero(), "the click asks for the next frame");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
script_runs::poll(&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 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_typed_text_goes_to_the_script_in_the_scope_it_was_typed_in() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
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'); 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")).unwrap());
|
||||
unconfined(|| {
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text and the click that gave it wait in the confined scope");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
for expected in ["changed", "clicked"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palettes()[0].dialog.nodes[1].text, "typed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_or_close_narrows_the_scope_of_the_draft_it_commits() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
for closing in [UiEvent::Click(2), UiEvent::Close] {
|
||||
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'); t.onChange = function () { vc.log('changed'); }; \
|
||||
go.onClick = function () { vc.log('clicked ' + t.text); }; \
|
||||
p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();",
|
||||
);
|
||||
unconfined(|| with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap());
|
||||
confine(Some(&roots), || give(&app, id, closing.clone()));
|
||||
unconfined(|| {
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the committed draft waits in the confined scope");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
let last = if matches!(closing, UiEvent::Close) { "closed typed" } else { "clicked typed" };
|
||||
for expected in ["changed", last] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
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};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
t.onChange = function () { vc.log('changed'); }; p.show();",
|
||||
);
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
unconfined(|| with_palette(&app, id, |w| w.type_text(1, "ty")).unwrap());
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text waits in the confined scope");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_in_the_pass_that_gives_a_text_runs_after_the_text() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
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'); t.onChange = function () { vc.log('changed'); }; \
|
||||
go.onClick = function () { vc.log('clicked ' + t.text); }; 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")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.pass(&[(1, None)], vec![UiEvent::Change(1, UiValue::Text("typed".into())), UiEvent::Click(2)])).unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the click waits with the text it follows");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_reported_before_a_text_commit_waits_in_the_texts_scope() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var go = p.add('button', undefined, 'Go'); \
|
||||
var t = p.add('edittext', undefined, 'a'); t.onChange = function () { vc.log('changed'); }; \
|
||||
go.onClick = function () { vc.log('clicked ' + t.text); }; p.show();",
|
||||
);
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "typed")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.pass(&[(2, None)], vec![UiEvent::Click(1), UiEvent::Change(2, UiValue::Text("typed".into()))])).unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "both events wait in the text's confined scope");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
for expected in ["changed", "clicked typed"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_orders_changes_before_a_click_before_splitting_scopes() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \
|
||||
var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \
|
||||
a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + b.text); }; \
|
||||
go.onClick = function () { vc.log(a.text + ' ' + b.text); }; p.show();",
|
||||
);
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
unconfined(|| with_palette(&app, id, |w| w.type_text(1, "first")).unwrap());
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| {
|
||||
w.pass(
|
||||
&[(1, None), (2, None)],
|
||||
vec![UiEvent::Click(3), UiEvent::Change(1, UiValue::Text("first".into())), UiEvent::Change(2, UiValue::Text("second".into()))],
|
||||
);
|
||||
})
|
||||
.unwrap();
|
||||
follow(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 3);
|
||||
for expected in ["first first", "second second", "first second"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_focus_loss_and_click_or_close_keep_another_drafts_scope_independent() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
for closing in [UiEvent::Click(3), UiEvent::Close] {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \
|
||||
var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \
|
||||
a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + b.text); }; \
|
||||
go.onClick = function () { vc.log(a.text + ' ' + b.text); }; \
|
||||
p.onClose = function () { vc.log(a.text + ' ' + b.text); return false; }; p.show();",
|
||||
);
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(1, "first")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| {
|
||||
w.type_text(2, "second");
|
||||
w.pass(&[(1, None)], vec![UiEvent::Change(1, UiValue::Text("first".into())), closing]);
|
||||
})
|
||||
.unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(a.text + ' ' + b.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["second second", "a second"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
for expected in ["first first", "first second"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffered_passes_keep_a_click_or_close_before_a_later_text_commit() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
for confined in [false, true] {
|
||||
for closing in [UiEvent::Click(2), UiEvent::Close] {
|
||||
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'); t.onChange = function () { vc.log('changed ' + t.text); }; \
|
||||
go.onClick = function () { vc.log('clicked ' + t.text); }; \
|
||||
p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();",
|
||||
);
|
||||
let first = if matches!(closing, UiEvent::Close) { "closed a" } else { "clicked a" };
|
||||
let record = || {
|
||||
with_palette(&app, id, |w| {
|
||||
w.pass(&[], vec![closing]);
|
||||
w.type_text(1, "typed");
|
||||
w.commit_text(1, "typed");
|
||||
})
|
||||
.unwrap();
|
||||
};
|
||||
if confined {
|
||||
confine(Some(&roots), record);
|
||||
} else {
|
||||
unconfined(record);
|
||||
}
|
||||
unconfined(|| follow(&mut app));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
for expected in [first, "changed typed"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffered_click_or_close_does_not_give_a_text_typed_after_it() {
|
||||
for closing in [UiEvent::Click(2), UiEvent::Close] {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine later\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 ' + t.text); }; \
|
||||
go.onClick = function () { vc.log('clicked ' + t.text); }; \
|
||||
p.onClose = function () { vc.log('closed ' + t.text); return false; }; p.show();",
|
||||
);
|
||||
let first = if matches!(closing, UiEvent::Close) { "closed" } else { "clicked" };
|
||||
with_palette(&app, id, |w| {
|
||||
w.type_text(1, "early");
|
||||
w.pass(&[], vec![closing]);
|
||||
w.type_text(1, "later");
|
||||
})
|
||||
.unwrap();
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2);
|
||||
for expected in ["changed early".to_string(), format!("{first} early")] {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap().as_deref(), Some("later"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_or_close_commits_drafts_in_dialog_order_across_scopes() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
for closing in [UiEvent::Click(3), UiEvent::Close] {
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \
|
||||
var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \
|
||||
a.onChange = function () { vc.log('first ' + a.text); }; b.onChange = function () { vc.log('second ' + a.text); }; \
|
||||
go.onClick = function () { vc.log(a.text + ' ' + b.text); }; \
|
||||
p.onClose = function () { vc.log(a.text + ' ' + b.text); return false; }; p.show();",
|
||||
);
|
||||
let long = "x".repeat(16 * 1024 + 1);
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, &long)).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.type_text(1, "first")).unwrap();
|
||||
give(&app, id, closing.clone());
|
||||
follow(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "every draft is validated before any is queued");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap(), Some("first".into()));
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(2).map(str::to_string)).unwrap(), Some(long));
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap());
|
||||
unconfined(|| {
|
||||
give(&app, id, closing);
|
||||
follow(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 3);
|
||||
for expected in ["first first", "second first", "first second"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_that_flushes_two_scopes_keeps_each_texts_scope() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var a = p.add('edittext', undefined, 'a'); \
|
||||
var b = p.add('edittext', undefined, 'b'); var go = p.add('button', undefined, 'Go'); \
|
||||
a.onChange = function () { vc.log('wide ' + a.text); }; b.onChange = function () { vc.log('narrow ' + b.text); }; \
|
||||
go.onClick = function () { vc.log(a.text + ' ' + b.text); }; p.show();",
|
||||
);
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
unconfined(|| with_palette(&app, id, |w| w.type_text(1, "first")).unwrap());
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.type_text(2, "second")).unwrap());
|
||||
unconfined(|| {
|
||||
give(&app, id, UiEvent::Click(3));
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(a.text + ' ' + b.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["wide first", "first b"]), "the wide change runs in the wide scope");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2, "the narrow change and the click still wait");
|
||||
for expected in ["narrow second", "first second"] {
|
||||
unconfined(|| {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!([expected]));
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_that_leaves_a_typed_text_as_it_was_keeps_its_scope() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
t.onChange = function () { vc.log('changed'); }; p.show();",
|
||||
);
|
||||
let roots = AutomationRoots::new(&[&std::env::temp_dir()], &[]).unwrap().unwrap();
|
||||
unconfined(|| with_palette(&app, id, |w| w.type_text(1, "typed")).unwrap());
|
||||
confine(Some(&roots), || with_palette(&app, id, |w| w.pass(&[(1, Some("typed"))], Vec::new())).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["changed", "typed"]));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_given_at_enter_goes_to_the_script_in_the_scope_it_was_typed_in() {
|
||||
use vectorcraft_engine::file_access::{AutomationRoots, confine, unconfined};
|
||||
|
||||
let mut app = app();
|
||||
let id = shown(
|
||||
&mut app,
|
||||
"#targetengine drafts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
t.onChange = function () { vc.log('changed'); }; 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")).unwrap());
|
||||
unconfined(|| {
|
||||
with_palette(&app, id, |w| w.commit_text(1, "typed")).unwrap();
|
||||
follow(&mut app);
|
||||
start(&mut app, "#targetengine drafts\np.update(); vc.log(t.text);");
|
||||
run_to_end(&mut app);
|
||||
});
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["a"]), "the text waits in its confined scope");
|
||||
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"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() {
|
||||
let mut app = app();
|
||||
let id = shown(&mut app, TOOLS);
|
||||
start(&mut app, "vc.log(confirm('Go?'));");
|
||||
for _ in 0..10_000 {
|
||||
if app.session.script_dialog().is_some() {
|
||||
break;
|
||||
}
|
||||
script_runs::poll(&mut app);
|
||||
}
|
||||
assert!(app.session.script_dialog().is_some(), "the run waits at its confirm");
|
||||
give(&app, id, UiEvent::Click(1));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
let delay = settled_delay(&mut app);
|
||||
assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the run waits for its answer");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits");
|
||||
}
|
||||
|
||||
/// Runs the app's ticks until one asks for no later frame, at most five. → the last one's delay.
|
||||
fn settled_delay(app: &mut VectorcraftApp) -> std::time::Duration {
|
||||
let mut delay = std::time::Duration::ZERO;
|
||||
for _ in 0..5 {
|
||||
delay = frame_delay(app, |app, ctx| app.tick(ctx));
|
||||
if delay == std::time::Duration::MAX {
|
||||
break;
|
||||
}
|
||||
}
|
||||
delay
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() {
|
||||
let mut app = app();
|
||||
let id = shown(&mut app, TOOLS);
|
||||
app.run("edit.undoGroup.begin", json!({})).unwrap();
|
||||
give(&app, id, UiEvent::Click(1));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
let delay = settled_delay(&mut app);
|
||||
assert_eq!(delay, std::time::Duration::MAX, "the waiting click asks for no frames, now or later, while the undo group is open");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits");
|
||||
app.run("edit.undoGroup.end", json!({})).unwrap();
|
||||
frame_delay(&mut app, |app, ctx| app.tick(ctx));
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "with the group ended the next frame starts the click's run");
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["clicked"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_text_stays_in_its_field_while_its_change_waits_for_a_run() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \
|
||||
t.onChange = function () { vc.log(t.text); }; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
start(&mut app, "while (true) {}");
|
||||
script_runs::poll(&mut app);
|
||||
assert!(app.session.script_running());
|
||||
with_palette(&app, id, |w| w.commit_text(1, "new")).unwrap();
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the change waits for the run");
|
||||
follow(&mut app);
|
||||
let shown = |app: &VectorcraftApp| with_palette(app, id, |w| w.shown_text(1)).flatten();
|
||||
assert_eq!(shown(&app).as_deref(), Some("new"), "the field keeps the given text while its change waits");
|
||||
assert!(app.session.script_abandon());
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["new"]));
|
||||
follow(&mut app);
|
||||
follow(&mut app);
|
||||
assert_eq!(shown(&app).as_deref(), Some("new"), "the field holds the text the script took");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_text_stays_in_its_field_while_its_change_waits_after_a_run_set_the_field_to_it() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \
|
||||
t.onChange = function () { vc.log('change ' + t.text); }; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
start(&mut app, "while (true) {}");
|
||||
script_runs::poll(&mut app);
|
||||
with_palette(&app, id, |w| w.commit_text(1, "A")).unwrap();
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the change waits for the run");
|
||||
assert!(app.session.script_abandon());
|
||||
let shown = |app: &VectorcraftApp| with_palette(app, id, |w| w.shown_text(1)).flatten();
|
||||
// Runs before the change's set the field to the given text, then to another one.
|
||||
for text in ["A", "B"] {
|
||||
start(&mut app, &format!("#targetengine fields\nt.text = '{text}';"));
|
||||
run_to_end(&mut app);
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the change still waits after the run that set {text}");
|
||||
assert_eq!(shown(&app).as_deref(), Some("A"), "the field keeps the given text after the run that set {text}");
|
||||
}
|
||||
assert!(script_palettes::start_next(&mut app));
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["change A"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_a_click_gives_stays_in_its_field_while_its_change_waits_for_a_run() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \
|
||||
var b = p.add('button', undefined, 'Go'); b.onClick = function () { vc.log(t.text); }; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
start(&mut app, "while (true) {}");
|
||||
script_runs::poll(&mut app);
|
||||
assert!(app.session.script_running());
|
||||
with_palette(&app, id, |w| w.type_text(1, "new")).unwrap();
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2, "the typed change and the click wait for the run");
|
||||
follow(&mut app);
|
||||
let shown = with_palette(&app, id, |w| w.shown_text(1)).flatten();
|
||||
assert_eq!(shown.as_deref(), Some("new"), "the field keeps the typed text the click gave");
|
||||
assert!(app.session.script_abandon());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_text_leaves_its_field_once_a_running_update_took_its_change() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); \
|
||||
var b = p.add('button', undefined, 'Go'); t.onChange = function () { t.text = t.text.toUpperCase(); }; \
|
||||
b.onClick = function () {}; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
start(&mut app, "#targetengine fields\nwhile (true) { p.update(); }");
|
||||
script_runs::poll(&mut app);
|
||||
with_palette(&app, id, |w| w.commit_text(1, "new")).unwrap();
|
||||
follow(&mut app);
|
||||
// The palette's controls go to the app before the click after the change is taken.
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
for _ in 0..10_000 {
|
||||
if app.session.script_palette_events_waiting() == 0 {
|
||||
break;
|
||||
}
|
||||
script_runs::poll(&mut app);
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "update() took both events");
|
||||
assert!(app.session.script_running());
|
||||
follow(&mut app);
|
||||
let shown = with_palette(&app, id, |w| w.shown_text(1)).flatten();
|
||||
assert_eq!(shown.as_deref(), Some("NEW"), "the field shows the text the handler set");
|
||||
assert!(app.session.script_abandon());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_given_text_the_script_refuses_stays_in_its_field_after_the_next_pass() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine fields\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'old'); p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
let long = "x".repeat(crate::dialogs::script_window::DRAFT_CHARS / 2 + 1);
|
||||
with_palette(&app, id, |w| w.commit_text(1, &long)).unwrap();
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "the text is too long for the script");
|
||||
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));
|
||||
});
|
||||
follow(&mut app);
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).flatten().as_deref(), Some(long.as_str()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_whose_run_cannot_begin_after_a_stopped_run_shows_its_own_error() {
|
||||
let mut app = app();
|
||||
let id = shown(&mut app, TOOLS);
|
||||
start(&mut app, "while (true) {}");
|
||||
script_runs::poll(&mut app);
|
||||
assert!(app.session.script_abandon());
|
||||
assert_eq!(app.session.script_report().unwrap()["kind"], "stopped");
|
||||
// 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));
|
||||
follow(&mut app);
|
||||
assert!(!script_palettes::start_next(&mut app));
|
||||
assert!(app.ui.status.contains("recovery copy"), "{}", app.ui.status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \
|
||||
var t = p.add('edittext', undefined, ''); p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
assert_eq!(app.session.script_palettes()[0].dialog.nodes[3].kind, UiKind::EditText);
|
||||
with_palette(&app, id, |w| w.type_text(3, "typed")).unwrap();
|
||||
start(&mut app, "#targetengine places\ng.add('button', undefined, 'Added');");
|
||||
run_to_end(&mut app);
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palettes()[0].dialog.nodes[4].kind, UiKind::EditText, "the added button comes before the field");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(4).map(str::to_string)).unwrap().as_deref(), Some("typed"));
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(3).map(str::to_string)).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_click_given_before_a_run_removes_a_control_before_it_reaches_its_button() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine moves\nvar p = new Window('palette'); var a = p.add('button', undefined, 'A'); \
|
||||
var b = p.add('button', undefined, 'B'); a.onClick = function () { vc.log('a'); }; \
|
||||
b.onClick = function () { vc.log('b'); }; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
// A run removes A before the app takes the click, so B is now the palette's first control.
|
||||
start(&mut app, "#targetengine moves\np.remove(a);");
|
||||
run_to_end(&mut app);
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1, "the click waits for its run");
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["b"]), "the click reaches the button it was given to");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_the_full_line_refuses_stays_in_its_field() {
|
||||
use vectorcraft_engine::script::palettes::MAX_WAITING;
|
||||
let mut app = app();
|
||||
let source = format!(
|
||||
"#targetengine full\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () {{ vc.log(t.text); }}; \
|
||||
for (var k = 0; k < {MAX_WAITING}; k++) {{ p.add('button', undefined, 'B' + k); }} p.show();"
|
||||
);
|
||||
let id = shown(&mut app, &source);
|
||||
for c in 3..3 + MAX_WAITING {
|
||||
app.session.script_palette_event(id, UiEvent::Click(c)).unwrap();
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "the line is full");
|
||||
give(&app, id, UiEvent::Change(1, UiValue::Text("typed".into())));
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(
|
||||
with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap().as_deref(),
|
||||
Some("typed"),
|
||||
"the refused text goes back in its field"
|
||||
);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "neither the text nor the click is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() {
|
||||
let mut app = app();
|
||||
let source = "#targetengine texts\nvar p = new Window('palette'); var t = p.add('edittext', undefined, 'a'); \
|
||||
var go = p.add('button', undefined, 'Go'); go.onClick = function () { vc.log(t.text); }; p.show();";
|
||||
let id = shown(&mut app, source);
|
||||
let long = "x".repeat(16 * 1024 + 1);
|
||||
with_palette(&app, id, |w| w.type_text(1, &long)).unwrap();
|
||||
give(&app, id, UiEvent::Change(1, UiValue::Text(long.clone())));
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0, "neither the long text nor the click is given");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap(), Some(long), "the refused text stays in its field");
|
||||
with_palette(&app, id, |w| w.type_text(1, "fine")).unwrap();
|
||||
give(&app, id, UiEvent::Click(2));
|
||||
follow(&mut app);
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 2, "the typed text, then the click");
|
||||
assert_eq!(with_palette(&app, id, |w| w.typed(1).map(str::to_string)).unwrap(), None, "the text is given once");
|
||||
// The change's run, then the click's.
|
||||
for _ in 0..2 {
|
||||
script_runs::poll(&mut app);
|
||||
run_to_end(&mut app);
|
||||
}
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 0);
|
||||
assert_eq!(app.session.script_report().unwrap()["log"], json!(["fine"]), "the click's handler reads the given text");
|
||||
}
|
||||
@@ -256,6 +256,29 @@ fn the_print_question_waits_while_a_text_field_has_the_keyboard() {
|
||||
assert!(sent.borrow().is_empty());
|
||||
}
|
||||
|
||||
/// A palette's click waits while the last run's print jobs wait for their answer, and runs after it.
|
||||
#[test]
|
||||
fn a_palette_click_waits_for_the_answer_to_the_last_runs_print_jobs() {
|
||||
let (mut app, _, _) = print_app(true);
|
||||
run(
|
||||
&mut app,
|
||||
"#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \
|
||||
go.onClick = function () { vc.log('clicked'); }; p.show();",
|
||||
);
|
||||
let id = app.session.script_palettes()[0].id;
|
||||
run(&mut app, PRINT_TO_LAB);
|
||||
assert!(app.session.script_prints_waiting() || asking(&app), "the jobs wait for their answer");
|
||||
app.session.script_palette_event(id, vectorcraft_engine::script::UiEvent::Click(1)).unwrap();
|
||||
for _ in 0..5 {
|
||||
script_runs::poll(&mut app);
|
||||
}
|
||||
assert!(!app.session.script_running(), "the palette's run does not start while the jobs wait");
|
||||
assert_eq!(app.session.script_palette_events_waiting(), 1);
|
||||
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");
|
||||
}
|
||||
|
||||
/// Cancel, from anyone, drops the jobs and keeps the run's changes.
|
||||
#[test]
|
||||
fn cancel_drops_a_scripts_print_jobs_and_keeps_its_changes() {
|
||||
|
||||
@@ -523,6 +523,125 @@ fn until_growth(app: &mut VectorcraftApp) {
|
||||
panic!("the run did not ask about its growth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_waiting_at_its_dialog_asks_for_no_frames() {
|
||||
let mut app = app();
|
||||
start(&mut app, &format!("{FORM} vc.log(w.show());"));
|
||||
assert!(until_window(&mut app));
|
||||
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 delay = std::time::Duration::ZERO;
|
||||
for _ in 0..5 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
assert_eq!(delay, std::time::Duration::MAX, "the app idles until the person answers");
|
||||
assert!(app.session.script_window().is_some(), "the run still waits at its dialog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_request_while_a_run_waits_at_its_dialog_asks_for_the_next_frame() {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut app = app().with_control(rx);
|
||||
start(&mut app, &format!("{FORM} vc.log(w.show());"));
|
||||
assert!(until_window(&mut app));
|
||||
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 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.
|
||||
let mut settled = false;
|
||||
for _ in 0..10 {
|
||||
if !drain(&mut app).is_zero() {
|
||||
settled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(settled, "nothing asks for a frame while the run waits");
|
||||
// What MCP's `answer_dialog` sends, which a later pass gives the run.
|
||||
let (req, _reply) = ControlRequest::new("ui.dialog.confirm", json!({}));
|
||||
tx.send(req).unwrap();
|
||||
let delay = drain(&mut app);
|
||||
assert!(delay.is_zero(), "the answer is taken in the next frame: {delay:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pass_that_gives_the_dialog_s_queued_event_asks_for_the_next_frame() {
|
||||
let mut app = app();
|
||||
start(&mut app, &format!("{FORM} vc.log(w.show());"));
|
||||
assert!(until_window(&mut app));
|
||||
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)));
|
||||
// One pass of the frame's pump, which gives the run the dialog's next queued event.
|
||||
let pass = |app: &mut VectorcraftApp| {
|
||||
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;
|
||||
for _ in 0..40 {
|
||||
if !pass(&mut app).is_zero() {
|
||||
settled = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(settled, "the pump stops asking for the very next frame while nothing waits in the dialog");
|
||||
// A click on Bold that waited in line behind a typed text.
|
||||
with_window(&app, |d| d.queue(&UiEvent::Click(2))).unwrap();
|
||||
assert!(pass(&mut app).is_zero(), "the run the click let go on asks for its next slice");
|
||||
assert!(app.session.script_window().is_none(), "the run took the click and has not waited again yet");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() {
|
||||
let mut app = app();
|
||||
start(
|
||||
&mut app,
|
||||
"var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); var swap = w.add('button', undefined, 'Swap'); \
|
||||
w.add('button', undefined, 'OK'); swap.onClick = function () { l.removeAll(); l.add('item', 'x'); l.add('item', 'y'); }; \
|
||||
vc.log([w.show(), String(l.selection)]);",
|
||||
);
|
||||
assert!(until_window(&mut app));
|
||||
// A click on Swap, then a choice in the list as it was before Swap's handler ran, both given
|
||||
// in one frame. Swap puts back items with other texts.
|
||||
with_window(&app, |d| {
|
||||
d.queue(&UiEvent::Click(2));
|
||||
d.queue(&UiEvent::Change(1, UiValue::Index(Some(1))));
|
||||
})
|
||||
.unwrap();
|
||||
step(&mut app, Vec::new());
|
||||
assert!(until_window(&mut app), "the script takes the click and waits again");
|
||||
assert_eq!(app.session.script_window().unwrap().nodes[1].items, ["x", "y"]);
|
||||
step(&mut app, Vec::new());
|
||||
assert!(queued(&app).is_empty(), "the choice left the line");
|
||||
assert!(until_window(&mut app));
|
||||
give(&mut app, json!({"event": "click", "control": "OK"})).unwrap();
|
||||
assert!(!until_window(&mut app));
|
||||
assert_eq!(log(&app), json!([[1, "null"]]), "the choice for the old items was not given");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queued_list_choice_is_given_while_its_list_is_unchanged() {
|
||||
let mut app = app();
|
||||
start(
|
||||
&mut app,
|
||||
"var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); w.add('button', undefined, 'OK'); \
|
||||
vc.log([w.show(), String(l.selection)]);",
|
||||
);
|
||||
assert!(until_window(&mut app));
|
||||
with_window(&app, |d| d.queue(&UiEvent::Change(1, UiValue::Index(Some(1))))).unwrap();
|
||||
step(&mut app, Vec::new());
|
||||
assert!(queued(&app).is_empty(), "the choice left the line");
|
||||
assert!(until_window(&mut app), "the script takes the choice and waits again");
|
||||
give(&mut app, json!({"event": "click", "control": "OK"})).unwrap();
|
||||
assert!(!until_window(&mut app));
|
||||
assert_eq!(log(&app), json!([[1, "b"]]), "the choice for the same items was given");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() {
|
||||
let mut app = app();
|
||||
|
||||
+97
-8
@@ -2734,8 +2734,8 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
|
||||
- `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects,
|
||||
syntax and directives, such as `$`, `alert`, `UnitValue`, `reflect`, the XML object and E4X, `#target` and
|
||||
`#targetengine`), `dom` (the reference app's document model, `app.selectTool` included), `files`, `menuCommands`,
|
||||
`dialogs`, and `hostOnly` (features only the reference app has: palettes, BridgeTalk, sockets, native code, XMP,
|
||||
operator overloading and actions).
|
||||
`dialogs` (dialogs and palettes), and `hostOnly` (features only the reference app has: BridgeTalk, sockets, native
|
||||
code, XMP, operator overloading and actions).
|
||||
- `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines,
|
||||
and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and
|
||||
`locale`. A directive is read where it starts a line, written `#name` or `//@name`.
|
||||
@@ -4389,8 +4389,9 @@ https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and
|
||||
https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its
|
||||
controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it:
|
||||
|
||||
- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) throws
|
||||
an `Error` that says it is not available yet.
|
||||
- `new Window("dialog"[, title, bounds, properties])` makes a dialog, and `new Window("palette", ...)` a palette,
|
||||
which is described after the dialogs below. The type `window` throws an `Error` that says it is not available
|
||||
yet.
|
||||
- `new Window` and `add` also take a resource specification in place of the type, as
|
||||
https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/ describes it:
|
||||
`"dialog { text: 'Settings', g: Group { label: StaticText { text: 'Name:' }, ok: Button { text: 'OK' } } }"`, or
|
||||
@@ -4422,14 +4423,20 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s
|
||||
object whose `width` and `height` are -1, so a script can set one side, as in `preferredSize.width = 100`; a side
|
||||
of 0 or less is left to the layout (VectorCraft's own starting values). A container also has `children`,
|
||||
`orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column),
|
||||
`alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and
|
||||
`remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item
|
||||
`alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)`, `update()`
|
||||
and `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item
|
||||
or a control that is not there does nothing. A removed control has no `parent`, it and the controls it holds have
|
||||
no `window`, and its events no longer reach the containers it was in, also when a handler removes it while its
|
||||
event runs; `add`, `remove` and `removeAll` on it, or on a control it holds, throw an `Error`. When a `text`
|
||||
getter changes the list or container while `remove(text)` looks for a match, `remove` throws an `Error` and
|
||||
removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])`
|
||||
and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing.
|
||||
removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])`, `hide()` and `update()`.
|
||||
`center()`, `layout.layout()` and `layout.resize()` do nothing.
|
||||
- `update()` on the showing dialog, or on a group or panel in it, runs without an error and does nothing more: a handler
|
||||
runs to its end before the app draws again, so the dialog shows the handler's changes when the handler
|
||||
returns, and a progress bar that a handler moves shows only its last value. On a window that is not showing
|
||||
it throws an `Error`, and on a control that is not a container it throws a `TypeError`. It does not take the
|
||||
person's clicks or changes: the dialog takes them once the running handler returns, so a loop that waits for
|
||||
a Cancel button's `onClick` to set a flag does not see the click.
|
||||
- Radio buttons added one after another in a container form a set: setting one's `value` to true, or clicking it,
|
||||
sets the others in the set to false. A control of another kind between two radio buttons starts a new set, as
|
||||
the JavaScript Tools Guide describes radio buttons
|
||||
@@ -4511,6 +4518,88 @@ an error in a handler ends `show()`, with steps it did not use.
|
||||
vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}'
|
||||
```
|
||||
|
||||
A palette is a ScriptUI window that stays open beside the documents after the script that showed it has ended, and
|
||||
that the person can use while they work (the window-object help page above). A script builds it like a dialog, with
|
||||
the same controls, handlers and limits:
|
||||
|
||||
- A palette needs a named engine, which keeps its controls and handlers after the run. In a script without
|
||||
`#targetengine`, or with `#targetengine main`, `new Window("palette")` throws an `Error` that says to add a
|
||||
`#targetengine` line (see [Script engines](#script-engines)).
|
||||
- `show()` runs `onShow` and returns `undefined` at once. `hide()` hides the palette, and `show()` shows it again.
|
||||
While a palette is hidden, `script.palettes` lists its controls as they were when it was hidden; `show()` gives
|
||||
the controls as they are then. `close()` runs `onClose` and closes the palette unless `onClose` returns `false`; the close box does the same.
|
||||
A palette also closes when `script.engine.drop` drops its engine, when its engine ends with an internal error,
|
||||
and when the session ends. The palette shows its controls as `show()`, `add()`, each event's handlers and each
|
||||
run of its engine leave them; a run that a limit or `script.stop` ended can leave it showing them as they were.
|
||||
`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/).
|
||||
`update()` takes eligible events oldest first. Events whose recorded file access scopes do not reach the same
|
||||
files as 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
|
||||
(VectorCraft's own interval); an `update()` within the same 16 ms does not pause the run, and the app draws
|
||||
its changes at the next pause or when the run ends. An `update()` in a handler, in a callback of a built-in
|
||||
function such as `forEach`, in a getter or in a conversion does not pause the run, since the run cannot
|
||||
pause there, and on the web `update()` does not pause the run; the app draws those changes when the run ends.
|
||||
On a palette that `hide()` hid, or that is not shown, it throws an `Error`; setting the palette's `visible`
|
||||
does not change this.
|
||||
A handler's run reads and writes the files the person allowed the script that first showed the palette with
|
||||
Always. A file allowed once stays with the run whose dialog allowed it, as for any later run. Its
|
||||
`app.doScript` plays the actions the run that first showed the palette had (`script.run`'s `actions`, or in
|
||||
the app the Actions panel's actions when the palette was first shown).
|
||||
- Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's
|
||||
engine, with its own report and, when it changes a document, its own Run Script undo step. While another run
|
||||
goes on, the event waits and runs after it; events run one at a time, oldest first. A run of the same engine
|
||||
whose own code calls `update()` takes a waiting event inside that run instead: the event then has no report or
|
||||
undo step of its own, and its changes are part of that run's. An `update()` in the handler of a palette event
|
||||
that waited for a run of its own takes no waiting event, so the event waits until that run ends. With nobody to ask, `script.palette.event` answers
|
||||
with the report of the run that handled the event it gave. While an event waits, a
|
||||
newer click on the same control, change of the same control or close of the same palette replaces the most
|
||||
recent waiting event of that kind for that control or palette only when it has the same file access scope.
|
||||
Otherwise the new event waits at the end of the line (`merged: false`). A click or close takes its place only if no
|
||||
change of its palette waits after it, and a change takes its place only if no click or close of its palette waits
|
||||
after it; otherwise it waits as a new event (`merged: false`). A text typed in
|
||||
a field goes to the script under what both its typing scope and the scope that commits it allow. A click
|
||||
or close waits under what its scope and all the texts it commits allow. A text edited in several scopes
|
||||
goes under what all of them allow. A waiting click or change, and a text typed in a field, stay with their control when a
|
||||
run adds controls before it. A waiting event whose control is gone, or that its control can no longer take
|
||||
because a handler, or a getter read while the palette is described for the event, disabled or hid it or a group
|
||||
above it, is dropped. A palette's control or group whose `enabled`
|
||||
or `visible` state a getter gives is shown disabled or hidden, and its events are dropped. A list's change is dropped, with no error and no handler run,
|
||||
when a script added or removed the list's items after the person chose and before the app put the change in
|
||||
line. Once the change waits in line, it ends its run with an error when a script added or removed the list's
|
||||
items or changed an item's text, even if the list again holds the same texts, and when an item's text comes from a getter rather than a
|
||||
plain value. A text typed in a palette's field that is longer than 16 KiB stays in the field with the error in the status bar, and the click or close
|
||||
given with it is dropped: correct the text, then click or close again. An error in a handler that ends its run fails that run like any failed run, puts the
|
||||
documents back, and leaves the palette open. A handler that a palette's `update()` runs throws its error from
|
||||
that `update()` call: when the script catches it, the run goes on and keeps the handler's changes. In the app, `alert`, `confirm`, `prompt` and a dialog's `show()` throw inside a
|
||||
handler; with nobody to ask, a handler's run has no `answers` and ends at the first of them.
|
||||
- A session keeps at most 16 palettes, shown or hidden, past which `show()` throws a `RangeError`, and at most 64
|
||||
waiting events, past which an event is refused. Hiding or closing a palette drops its waiting events. These
|
||||
limits are VectorCraft's own.
|
||||
|
||||
`script.palettes {}` lists the palettes in the order they were first shown: `{palettes: [{id, engine, title,
|
||||
visible, controls: [{index, kind, name, text, enabled, visible, value?, items?, selection?}]}], waiting, limit: 16,
|
||||
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
|
||||
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
|
||||
a run, it ends with that error and this event no longer waits. A hidden palette, a disabled or hidden
|
||||
control, and a control that cannot take the event are errors, and with nobody to ask so is an event while an undo
|
||||
group or a drag in a document other than the active one is open.
|
||||
|
||||
```sh
|
||||
vectorcraft-cli run --cmd script.run --params '{"source": "#targetengine tools\nvar p = new Window(\"palette\", \"Tools\"); var go = p.add(\"button\", undefined, \"Add\"); go.onClick = function () { vc.run(\"shape.rectangle\", {x: 0, y: 0, width: 20, height: 20}); }; p.show();"}'
|
||||
```
|
||||
|
||||
The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and
|
||||
https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A
|
||||
script reads files with them:
|
||||
|
||||
@@ -1185,7 +1185,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`).
|
||||
- Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`).
|
||||
- Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`.
|
||||
- Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Palettes and other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`.
|
||||
- Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`.
|
||||
- Scripts: ScriptUI's `new Window("palette")` makes a palette in a script whose `#targetengine` names an engine other than `main`, and the palette's `show()` shows it beside the documents, where it stays open after the run (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). Each click, change or close runs its handler as a run of its own in that engine, after any run that is going, unless a run of that engine takes it first with `update()` (below), which runs the handler during that run. A click or change is dropped when its control, or a group above it, is disabled or hidden once the palette is described for the event, or when a getter gives that `enabled` or `visible` state. A newer change for the same control takes a waiting change's place only when no click or close of that palette waits after the waiting change, and a newer click or close takes a waiting one's place only when no change of that palette waits after it; in both cases the two must be given under the same file access scope. `update()` on a palette, or on a group or panel in one, runs the handlers of the events that wait for the engine's palettes whose file access scopes reach the same files as the run's scope, so a Cancel button can stop a loop; an event given under other roots or another script gate waits for a run of its own instead. `update()` in the script's own code in the app also pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. `close()` and the close box close a palette unless its `onClose` returns `false`; the end of its engine or the session closes it too. A session keeps at most 16 palettes and 64 waiting events. `script.palettes` and `script.palette.event` list and drive them. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_palettes.rs`.
|
||||
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
|
||||
- Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse.
|
||||
- Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).
|
||||
|
||||
Reference in New Issue
Block a user