From fdad498dbc15f22757be41cc64653cff9910a37b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:46:59 -0800 Subject: [PATCH] Scripts: doScript keeps the run's artboard picks and a batch's artboard - The Artboard tool's selection as script.run starts is kept for the steps app.doScript plays: the run gives the tool fresh state, which dropped it, so a paste or Fit to Artwork Bounds step acted on the active artboard only. - A step of a command.batch step that names its artboard acts on that artboard, past the last one the last, as command.batch gives it. - The app leaves out every action of a set that shares a name with an action it cannot pass, so that name is never one a script can play. - The host name check lists doScript, loadAction and unloadAction. --- crates/engine/src/script/actions.rs | 58 ++++++++++---- crates/engine/src/script/mod.rs | 8 ++ crates/engine/src/tests/script_actions.rs | 75 ++++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/ui-egui/src/panels/actions.rs | 43 ++++++++++- docs/mcp.md | 10 ++- 6 files changed, 174 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index a0fabf2103..b4a7a743a3 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -52,13 +52,14 @@ pub struct Playable { /// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a /// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and -/// their size as JSON. +/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names. #[derive(Clone, Debug)] struct Step { place: String, id: String, params: Value, bytes: u64, + artboard: Option, } /// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the @@ -100,6 +101,9 @@ pub fn parse(v: Option<&Value>) -> Result, String> { let (id, params) = command_of(s, &at)?; match params.get("commands") { Some(Value::Array(inner)) if id == "command.batch" => { + // The batch's `artboard`, for its steps that act on the active artboard, as + // `command.batch` reads it. + let artboard = params.get("artboard").and_then(Value::as_u64); for (k, c) in inner.iter().enumerate() { let at = format!("{at}.params.commands[{k}]"); let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; @@ -107,11 +111,11 @@ pub fn parse(v: Option<&Value>) -> Result, String> { if id == "command.batch" { return Err(format!("{at} is a command.batch inside a command.batch")); } - steps.push(step(format!("{place}.{}", k + 1), id, params)); + steps.push(step(format!("{place}.{}", k + 1), id, params, artboard)); } } _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), - _ => steps.push(step(place, id, params)), + _ => steps.push(step(place, id, params, None)), } if steps.len() > MAX_ACTION_STEPS { return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); @@ -167,9 +171,9 @@ fn command_of(o: &Map, at: &str) -> Result<(String, Value), Strin Ok((id, params)) } -fn step(place: String, id: String, params: Value) -> Step { +fn step(place: String, id: String, params: Value, artboard: Option) -> Step { let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); - Step { place, id, params, bytes } + Step { place, id, params, bytes, artboard } } /// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters @@ -248,7 +252,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { h.charge_call(16 + s.id.len() as u64 + s.bytes)?; // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. - let params = on_active_artboard(&h.session.borrow(), &h.active_artboards, &s.id, &s.params); + let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); h.session.borrow_mut().set_replaying(outer); @@ -289,16 +294,24 @@ fn refused_step(s: &Step) -> Option<(String, String)> { /// run started, which the view keeps), past the last artboard the last one, as the view shows it /// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While /// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its -/// `indices` instead, and a paste step gets none (it pastes on them). A paste step in a document -/// without artboards, or one that names `artboards`, and a Fit to Artwork Bounds step that names -/// `indices`, get none. A key the step gives is kept. -pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: &str, params: &Value) -> Value { +/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh +/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the +/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork +/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the +/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch` +/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past +/// the last artboard the last one, and none in a document without artboards, as `command.batch` +/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit +/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value { let mut params = params.clone(); let Some(st) = s.active() else { return params }; let n = st.doc.artboards.len(); - let active = match start.iter().find(|(uid, _)| *uid == st.uid) { - Some((_, i)) => (*i).min(n.saturating_sub(1)), - None => super::dom::active_artboard(st), + let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) { + (Some(_), _) if n == 0 => return params, + (Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)), + (None, Some((_, i))) => (*i).min(n.saturating_sub(1)), + (None, None) => super::dom::active_artboard(st), }; let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); let fit_art = id == "artboard.fitToArt"; @@ -314,10 +327,27 @@ pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: return params; } let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; - if picks.is_empty() { + let kept: Vec = match start.picks { + Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => { + list.iter().copied().filter(|i| *i < n).collect() + } + _ => Vec::new(), + }; + if kept.len() >= 2 { + p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept)); + } else if picks.is_empty() { p.insert(key.into(), json!(active)); } else if fit_art { p.insert("indices".into(), json!(picks)); } params } + +/// What [`on_active_artboard`] reads besides the session: the index of each open document's active +/// artboard as the run started, by document uid; the Artboard tool's selection as the run started, +/// with its document's uid; and the `artboard` a step's recorded `command.batch` names. +pub(crate) struct Start<'a> { + pub active: &'a [(u64, usize)], + pub picks: Option<&'a (u64, Vec)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 770934ce98..f2eeaa57ee 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -810,6 +810,10 @@ struct Host { /// 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)>, + /// The artboards the Artboard tool had selected in the active document as the run starts (two or + /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the + /// steps `app.doScript` plays read them here. + artboard_picks: Option<(u64, Vec)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1963,6 +1967,9 @@ impl Session { if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); } + // The Artboard tool's selection, which the fresh tool state below drops. + let picks = cmd::artboard_tool_picks(self); + let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); @@ -2075,6 +2082,7 @@ impl Session { dom: dom::State::default(), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 4fbcd55751..1432b8671b 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -262,6 +262,31 @@ fn steps_act_on_the_artboard_active_as_they_run() { assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); } +/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, +/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. +#[test] +fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 1); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let mut own = align.clone(); + own["params"]["artboard"] = json!(1); + let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}}); + let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "app.doScript('First', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "the batch's artboard 0"); + log_with(&mut s, "app.doScript('Past', 'Set');", &actions); + assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one"); + log_with(&mut s, "app.doScript('Own', 'Set');", &actions); + assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it"); +} + /// The active artboard a step gets is the index it had as the run started: after a step deletes an /// artboard before it, the artboard now at that index, as the view shows it. #[test] @@ -269,7 +294,8 @@ fn steps_keep_the_active_artboards_index() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); let uid = s.active().unwrap().uid; - let add = |s: &Session| script::actions::on_active_artboard(s, &[(uid, 1)], "object.align", &json!({})); + let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None }; + let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({})); assert_eq!(add(&s), json!({"artboard": 1})); s.execute("artboard.delete", &json!({"index": 0})).unwrap(); assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); @@ -310,7 +336,8 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); make_active(&mut s, 1); - let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &[], id, &json!({})); + let start = script::actions::Start { active: &[], picks: None, batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); @@ -323,3 +350,47 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); assert_eq!(add(&s, "shape.rectangle"), json!({})); } + +/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays, +/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to +/// Artwork Bounds step fits them. +#[test] +fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { + // Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2. + let setup = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + s.execute("edit.copy", &json!({})).unwrap(); + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + (s, was, art) + }; + let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + let (mut s, ..) = setup(); + let before = objects(&s); + log_with(&mut s, "app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 2, "one copy on each selected artboard"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // A kept artboard past the last one is left out; with fewer than two left, the active one applies. + let (mut s, ..) = setup(); + s.reset_tool(); + let uid = s.active().unwrap().uid; + let kept = (uid, vec![0, 2]); + let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..8bf497bafe 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -80,8 +80,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + getIsFileOpen loadAction loadAction= selection typename unloadAction unloadAction=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 9c0563b849..e77eb31143 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -589,15 +589,25 @@ pub(crate) fn has_stop(commands: &[Value]) -> bool { /// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel /// order, with its steps as playback runs them ([`Action::playback_steps`]) and each step's place in /// the action. An action that `actions` cannot hold (a step that is not a command, a name that is -/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out, and so +/// is every other action of its set with its name, so that a name two actions share is never one a +/// script can play. pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use std::collections::HashMap; use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, parse}; let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; if p.contains_key("actions") { return; } + let all = || app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))); + // How many actions of the panel have each set's name and action's name, and how many of them + // `actions` holds. + let mut named: HashMap<(&str, &str), (usize, usize)> = HashMap::new(); + for (set, a) in all() { + named.entry((set.name.as_str(), a.name.as_str())).or_default().0 += 1; + } let (mut list, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); - for (set, a) in app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))) { + for (set, a) in all() { if list.len() >= MAX_ACTIONS { break; } @@ -636,10 +646,18 @@ pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Va } steps += count; bytes += size; + if let Some(n) = named.get_mut(&(set.name.as_str(), a.name.as_str())) { + n.1 += 1; + } if let Value::Array(mut one) = one { list.append(&mut one); } } + let partly = |e: &Value| { + let key = (e["set"].as_str().unwrap_or_default(), e["name"].as_str().unwrap_or_default()); + named.get(&key).is_some_and(|(panel, held)| held < panel) + }; + list.retain(|e| !partly(e)); p.insert("actions".into(), Value::Array(list)); } @@ -7542,6 +7560,27 @@ mod tests { assert_eq!(objects(&app), 2); } + /// A name two actions of a set share stays a name a script can't play when `actions` leaves one + /// of them out: the other is left out too. + #[test] + fn a_script_cant_play_a_name_two_actions_share() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = ("shape.rectangle".to_string(), json!({"x": 0, "y": 10, "width": 10, "height": 10})); + let good = Action::new("Twin", vec![rect.clone()]); + let odd = Action::new("Twin", vec![rect.clone(), ("select.none".to_string(), json!(5))]); + app.ui.action_sets.push(ActionSet::new("Mine", vec![good, odd, Action::new("Other", vec![rect])])); + let mut params = json!({}); + add_script_actions(&app, "script.run", &mut params); + let mine: Vec<_> = params["actions"].as_array().into_iter().flatten().filter(|a| a["set"] == "Mine").map(|a| a["name"].clone()).collect(); + assert_eq!(mine, [json!("Other")]); + app.session.script_frames = false; + let source = "try { app.doScript('Twin', 'Mine'); vc.log('ran'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Twin”"])); + assert_eq!(app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()), 0); + } + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6b507eab99..0062ea6218 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2689,10 +2689,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one - past the end. While the Artboard tool has several artboards selected, a paste step and a Fit to Artwork Bounds step - act on those instead, as in the panel's playback. VectorCraft's own rules: the action and its set are matched by - their exact names, and a name that matches no action or more than one throws an error before any step runs, as does - an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's + own rules: the action and its set are matched by their exact names, and a name that matches no action or more than + one throws an error before any step runs, as does an action with no included step. When the app leaves an action + out of `actions`, it also leaves out every other action of that set with the same name. A stop, and a step whose command a script may not run or the engine does not have (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an action cannot play itself.