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:
.CooCoo authored and GitHub committed 2026-12-03 11:24:20 -08:00
commit 64a7515fea
59 files changed
+5507 -248

No files matched your search

+8 -3
View File
@@ -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))));
}
+24 -9
View File
@@ -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);
}
}
+9 -1
View File
@@ -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 {
+84 -3
View File
@@ -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`].
+536
View File
@@ -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()))
})
}
}
+141 -2
View File
@@ -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> {