mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Scripts: palette handlers play the showing run's actions, and a given text stays in its field
- A palette's handler runs take the actions of the run that first showed the palette (script.run's actions, or the Actions panel's in the app), so app.doScript in a handler plays them after that run ends too. - An edit field keeps showing the text it gave the script while that change waits for a run. The text goes once the session no longer holds the change, or the field holds the text; a text the script refuses goes back in the field as typed.
This commit is contained in:
1 parent
77cc99b2bd
commit
95847e92db
6 files changed
+171
-13
No files matched your search
@@ -24,6 +24,7 @@ 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};
|
||||
|
||||
@@ -88,6 +89,9 @@ pub(crate) struct Queued {
|
||||
#[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`]).
|
||||
@@ -124,12 +128,13 @@ impl Palettes {
|
||||
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`. → its id.
|
||||
/// `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): (Option<String>, String),
|
||||
(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)) {
|
||||
@@ -142,6 +147,9 @@ impl Palettes {
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -165,7 +173,11 @@ impl Palettes {
|
||||
let before = self.list.len();
|
||||
self.list.retain(|p| !(p.id == id && p.engine == engine));
|
||||
self.waiting.retain(|q| q.palette != id);
|
||||
self.list.len() != before
|
||||
let closed = self.list.len() != before;
|
||||
if closed {
|
||||
self.actions.retain(|(p, _)| *p != id);
|
||||
}
|
||||
closed
|
||||
}
|
||||
|
||||
/// Closes the palettes of the engines `keep` does not keep, with their waiting events.
|
||||
@@ -173,6 +185,7 @@ impl Palettes {
|
||||
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.
|
||||
@@ -397,6 +410,16 @@ impl Session {
|
||||
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,
|
||||
@@ -439,6 +462,7 @@ impl Session {
|
||||
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,
|
||||
@@ -450,7 +474,7 @@ impl Session {
|
||||
locale,
|
||||
answers: Vec::new(),
|
||||
module: false,
|
||||
actions: Vec::new(),
|
||||
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();
|
||||
|
||||
@@ -767,7 +767,7 @@ fn palette_show(host: &Host, args: &[Data]) -> Result<Data, HostError> {
|
||||
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), dialog);
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -658,6 +658,22 @@ fn with_nobody_to_ask_an_event_whose_open_edit_cannot_be_settled_ends_with_that_
|
||||
assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after it ran");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_handler_plays_the_actions_of_the_run_that_showed_its_palette() {
|
||||
let mut s = one_doc();
|
||||
let actions =
|
||||
json!([{"set": "Set", "name": "Box", "steps": [{"command": "shape.rectangle", "params": {"x": 40, "y": 0, "width": 5, "height": 5}}]}]);
|
||||
let source = "#targetengine acts\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \
|
||||
b.onClick = function () { app.doScript('Box', 'Set'); vc.log('played'); }; p.show();";
|
||||
s.execute("script.run", &json!({"source": source, "name": "p.js", "actions": actions})).unwrap();
|
||||
let id = only_palette(&s);
|
||||
let objects = |s: &Session| s.documents()[0].doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::<usize>();
|
||||
let before = objects(&s);
|
||||
let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap();
|
||||
assert_eq!(clicked["log"], json!(["played"]));
|
||||
assert_eq!(objects(&s), before + 1, "the action drew its rectangle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_does_not_take_the_place_of_a_change_that_waits_before_a_click() {
|
||||
let mut s = one_doc();
|
||||
|
||||
@@ -46,19 +46,39 @@ pub(crate) struct PaletteWindow {
|
||||
/// and a list's change with the items the person saw, so a run that changes the palette before
|
||||
/// the app takes them leaves each with its own control.
|
||||
given: Vec<(ScopeHandle, ScopeHandle, Vec<Queued>)>,
|
||||
/// The text each edit field gave the script, by the field's id, while its change waits: the
|
||||
/// field shows it until the palette's field holds it or no event waits.
|
||||
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(), open: true }
|
||||
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.
|
||||
fn sync(&mut self, palette: ScriptPalette) {
|
||||
/// dropped, and so is a given text once the field holds it, or 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, text| (given || waiting.contains(&(palette, *id))) && nodes.iter().any(|n| n.id == *id && n.text != *text));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -123,6 +143,13 @@ impl PaletteWindow {
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -184,15 +211,16 @@ impl StackDialog for PaletteWindow {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
|
||||
let heading = script_window::heading(&self.palette.dialog);
|
||||
let PaletteWindow { palette, drafts, open, .. } = self;
|
||||
let (palette, drafts_now) = (&*palette, &*drafts);
|
||||
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, &palette.dialog, drafts_now, true));
|
||||
.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
|
||||
@@ -206,6 +234,21 @@ impl StackDialog for PaletteWindow {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
@@ -215,6 +258,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
// 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() {
|
||||
@@ -227,7 +271,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
for p in &shown {
|
||||
match host.get_mut_by_id::<PaletteWindow>(palette_id(p.id)) {
|
||||
Some(w) => {
|
||||
w.sync(p.clone());
|
||||
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 => {
|
||||
@@ -257,6 +301,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
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.retain(|field, _| !drafts.contains_key(field));
|
||||
w.drafts = drafts;
|
||||
w.draft_scopes = draft_scopes;
|
||||
}
|
||||
|
||||
@@ -623,6 +623,75 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it()
|
||||
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_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();
|
||||
|
||||
+3
-1
@@ -3884,7 +3884,9 @@ the same controls, handlers and limits:
|
||||
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.
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user