From 5294f0560d5ba26af0550f72368d31ad91eb18c0 Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:36:02 +0530 Subject: [PATCH 001/334] 5547: show missing-link markers on canvas --- ROADMAP.md | 5 +- crates/engine/src/cmd/links.rs | 58 +++++++++ crates/engine/src/doc_state.rs | 30 +++++ crates/engine/src/link_watch.rs | 37 ++++-- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/missing_links.rs | 135 +++++++++++++++++++++ crates/mcp/src/tests/links.rs | 9 ++ crates/ui-egui/src/canvas.rs | 4 + crates/ui-egui/src/canvas/missing_links.rs | 98 +++++++++++++++ crates/ui-egui/src/canvas/panes.rs | 1 + crates/ui-egui/src/keymap.rs | 1 + crates/ui-egui/src/menus/labels.rs | 5 + crates/ui-egui/src/menus/tree.rs | 1 + crates/ui-egui/src/panels/links.rs | 5 + docs/gaps.md | 5 +- docs/mcp.md | 20 +++ docs/roadmap.md | 7 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 6 +- 19 files changed, 421 insertions(+), 14 deletions(-) create mode 100644 crates/engine/src/tests/missing_links.rs create mode 100644 crates/ui-egui/src/canvas/missing_links.rs diff --git a/ROADMAP.md b/ROADMAP.md index 74909b123a..6e06b62d1b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,5 +1,7 @@ # VectorCraft Roadmap +**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. + - Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. - Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. @@ -14,7 +16,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -223,6 +225,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | | 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index bcda11c2bd..6608b0f4fd 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -35,6 +35,12 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do pub fn specs() -> Vec { vec![ + cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None, + "{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step → {on}", + has_doc, show_missing_links), + cmd!(query "links.marked", "Marked Missing Links", [], None, + "{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}", + has_doc, marked), cmd!( query "links.check", "Check Links", @@ -895,6 +901,7 @@ fn update(s: &mut Session, p: &Value) -> Result { if !reads.is_empty() { s.edit("Update Links", |d, _| reads.into_iter().try_for_each(|(ids, read)| install_read(d, &ids, read, None)))?; } + clear_markers(s, &updated)?; Ok(json!({ "updated": updated, "missing": missing })) } @@ -1015,6 +1022,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { } not_found.sort(); not_found.dedup(); + clear_markers(s, &relinked)?; let mut out = json!({ "relinked": relinked, "notFound": not_found }); if copy_to.is_some() { out["copied"] = json!(copied); @@ -1121,6 +1129,56 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap) -> Vec { + groups(doc, None) + .iter() + .filter(|g| !g.ids.is_empty() && probe(g, path).0 == Status::Missing) + .flat_map(|g| g.ids.iter().copied()) + .filter(|id| doc.is_visible(*id)) + .collect() +} + +fn show_missing_links(s: &mut Session, p: &Value) -> Result { + let st = s.doc_mut()?; + let on = super::switch_or(p, "on", !st.show_missing_links, "view.showMissingLinks")?; + // An explicit command answers immediately. Subsequent external changes are scanned by + // the existing link watch worker, even when the Links panel is closed. + if on { + st.missing_link_markers = Some((st.doc.clone(), missing_markers(&st.doc, st.path.as_deref()))); + } else { + st.missing_link_markers = None; + } + st.show_missing_links = on; + Ok(json!({"on": on})) +} + +fn marked(s: &mut Session, _: &Value) -> Result { + let st = s.doc_mut()?; + let ids = if st.show_missing_links { missing_markers(&st.doc, st.path.as_deref()) } else { vec![] }; + let images: Vec = ids + .iter() + .filter_map(|id| { + let b = st.doc.node(*id)?.geometric_bounds()?; + Some(json!({"id": id.0, "bounds": [b.x0, b.y0, b.x1, b.y1]})) + }) + .collect(); + st.missing_link_markers = Some((st.doc.clone(), ids)); + Ok(json!({"on": st.show_missing_links, "images": images})) +} + +/// Successful repair clears its decoration even when the file's metadata is unchanged. +fn clear_markers(s: &mut Session, repaired: &[u64]) -> Result<()> { + if !repaired.is_empty() + && let Some((_, ids)) = &mut s.doc_mut()?.missing_link_markers + { + let repaired: std::collections::HashSet<_> = repaired.iter().copied().collect(); + ids.retain(|id| !repaired.contains(&id.0)); + } + Ok(()) +} + /// The format of the file image `im` of `d` shows: its link's extension, else its pixels' type. fn format_label(d: &Document, im: &ImageObject) -> &'static str { im.link diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 3d1c4be89b..f06765f480 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -60,6 +60,10 @@ pub struct DocState { pub mask_view: Option, /// View → Show Transparency Grid, per document (saved view state, not undoable). pub transparency_grid: bool, + /// View → Show Missing Links: transient canvas decoration, never document artwork. + pub show_missing_links: bool, + /// Last worker scan, tied to the exact document snapshot it inspected. + pub missing_link_markers: Option<(Arc, Vec)>, /// The format Save writes ([`cmd::fileio::SAVE_FORMATS`]): the one the document was opened /// from or last saved as. pub format: &'static str, @@ -230,6 +234,30 @@ impl SameContent { } impl DocState { + /// Cached missing links still present and visible in the current art. Geometry-only edits + /// keep their markers moving with the objects; relinking or embedding drops them immediately. + pub fn marked_missing_links(&self) -> Vec { + if !self.show_missing_links { + return vec![]; + } + let Some((before, ids)) = &self.missing_link_markers else { return vec![] }; + fn link(n: &vectorcraft_doc::Node) -> Option<&vectorcraft_doc::LinkInfo> { + match &n.kind { + NodeKind::Image(im) => im.link.as_ref(), + NodeKind::PlacedDocument(p) => Some(&p.link), + _ => None, + } + } + ids.iter() + .copied() + .filter(|id| { + let old = before.node(*id).and_then(link); + let now = self.doc.node(*id).and_then(link); + now.is_some() && now == old && self.doc.is_visible(*id) + }) + .collect() + } + pub fn new(mut doc: Document, path: Option) -> Self { let active_layer = doc.default_layer(); // Saved view state lives here while the document is open (saves write it back). @@ -261,6 +289,8 @@ impl DocState { opened_as_tab: true, mask_view: None, transparency_grid, + show_missing_links: false, + missing_link_markers: None, format: "vectorcraft", save_options: Default::default(), save_artboards: vec![], diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index 44b1bd86a9..ce4f2677ee 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -27,9 +27,16 @@ use crate::{Result, Session}; /// A file's size and modification time (nanoseconds since 1970). pub type Stamp = (u64, u128); -/// Stamps of a document's linked files taken on a worker thread: (document uid, [(file, -/// object ids, stamp)]), the condition the worker signals when it ends, and whether it has. -pub type LinkScan = Arc<(Mutex, Option)>)>>, Condvar, AtomicBool)>; +/// A document's linked-file scan, the condition the worker signals when it ends, and whether +/// it has. Includes missing-link marker ids when their view toggle is enabled. +pub type LinkScan = Arc<(Mutex>, Condvar, AtomicBool)>; + +/// A worker's stamps and optional missing-link overlay scan of the same document snapshot. +pub struct LinkScanResult { + uid: u64, + stamps: Vec<(String, Vec, Option)>, + markers: Option<(Arc, Vec)>, +} /// Held by a look's worker: marks the look as ended and wakes [`Session::wait_link_scan`] when /// dropped, whether the worker returned or unwound. @@ -86,7 +93,11 @@ impl Session { // A confined caller's roots, else what the caller that opened the document may read (the // desktop frame is unconfined). let opened_by = st.opened_by.clone(); + let marker_doc = st.show_missing_links.then(|| st.doc.clone()); if files.is_empty() { + if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) { + st.missing_link_markers = None; + } return; } let slot: LinkScan = Arc::default(); @@ -95,12 +106,17 @@ impl Session { let spawned = std::thread::Builder::new().name("link-watch".into()).spawn(move || { // Marks the look as ended when the worker returns or unwinds. let _ended = Ended(out.clone()); - let stamps = scope.run(|| { + let (stamps, markers) = scope.run(|| { crate::file_access::confine(crate::file_access::current().or(opened_by).as_ref(), || { - files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect() + let stamps = files.into_iter().map(|(p, ids)| (p.clone(), ids, stamp(&p, doc_path.as_deref()))).collect(); + let markers = marker_doc.map(|doc| { + let ids = crate::cmd::links::missing_markers(&doc, doc_path.as_deref()); + (doc, ids) + }); + (stamps, markers) }) }); - *out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some((uid, stamps)); + *out.0.lock().unwrap_or_else(PoisonError::into_inner) = Some(LinkScanResult { uid, stamps, markers }); }); if spawned.is_ok() { self.link_scan = Some(slot); @@ -110,8 +126,15 @@ impl Session { /// Apply a finished look (`None` while there is none, or it is still running): see /// [`Session::apply_link_stamps`]. pub fn poll_link_scan(&mut self) -> Option> { - let (uid, stamps) = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?; + let LinkScanResult { uid, stamps, markers } = self.link_scan.as_ref()?.0.lock().unwrap_or_else(PoisonError::into_inner).take()?; self.link_scan = None; + if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) + && st.show_missing_links + && let Some((doc, ids)) = markers + && Arc::ptr_eq(&st.doc, &doc) + { + st.missing_link_markers = Some((doc, ids)); + } Some(self.apply_link_stamps(uid, stamps, false)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 812a6282f2..3c5c149ce1 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -95,6 +95,7 @@ mod live; mod livecorners; mod maskview; pub(super) mod menucmds; +mod missing_links; mod nativefile; mod newart; mod newdoc; diff --git a/crates/engine/src/tests/missing_links.rs b/crates/engine/src/tests/missing_links.rs new file mode 100644 index 0000000000..be7244e532 --- /dev/null +++ b/crates/engine/src/tests/missing_links.rs @@ -0,0 +1,135 @@ +//! Canvas marker state and command API, independent of artwork and link update preferences. + +use serde_json::json; + +use crate::tests_links::{Folder, RED, place, png, session, write}; +use crate::*; + +fn marked(s: &mut Session) -> Vec { + s.execute("links.marked", &json!({})).unwrap()["images"].as_array().unwrap().iter().map(|r| r["id"].as_u64().unwrap()).collect() +} + +#[test] +fn missing_link_toggle_is_transient_per_document_and_validated() { + let mut s = session(); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + assert!(marked(&mut s).is_empty()); + assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true})); + for p in [json!({"on": "false"}), json!({"on": 1}), json!({"on": []})] { + assert!(s.execute("view.showMissingLinks", &p).is_err()); + assert!(s.doc().unwrap().show_missing_links); + } + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + assert!(!s.doc().unwrap().is_dirty()); + s.execute("file.new", &json!({})).unwrap(); + assert!(!s.doc().unwrap().show_missing_links); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(s.doc().unwrap().show_missing_links); + assert_eq!(s.execute("view.showMissingLinks", &json!({})).unwrap(), json!({"on": false})); + assert!(s.doc().unwrap().missing_link_markers.is_none()); +} + +#[test] +fn missing_link_markers_follow_files_relink_update_and_embed() { + let dir = Folder::new("marker-lifecycle"); + let path = dir.file("art.png"); + let replacement = dir.file("replacement.png"); + let bytes = png(40, 40, RED); + write(&path, &bytes); + write(&replacement, &bytes); + let mut s = session(); + let id = place(&mut s, &path); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert!(marked(&mut s).is_empty()); + std::fs::remove_file(&path).unwrap(); + assert_eq!(marked(&mut s), vec![id.0]); + let doc = s.doc().unwrap().doc.clone(); + let selection = s.doc().unwrap().selection.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let saved = vectorcraft_format::save_file(&doc); + let pixels = vectorcraft_render::Renderer::new().render_region(&doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels; + s.execute("view.showMissingLinks", &json!({"on": false})).unwrap(); + assert!(marked(&mut s).is_empty()); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert_eq!(marked(&mut s), vec![id.0]); + let st = s.doc().unwrap(); + assert_eq!(st.selection, selection); + assert_eq!(st.history.undo.len(), undo); + assert_eq!(vectorcraft_format::save_file(&st.doc), saved); + assert_eq!( + vectorcraft_render::Renderer::new().render_region(&st.doc, vectorcraft_geom::Rect::new(0.0, 0.0, 400.0, 300.0), 1.0, true).pixels, + pixels + ); + s.execute("links.relink", &json!({"ids": [id.0], "path": replacement})).unwrap(); + assert!(s.doc().unwrap().marked_missing_links().is_empty()); + assert!(marked(&mut s).is_empty()); + std::fs::remove_file(&replacement).unwrap(); + assert_eq!(marked(&mut s), vec![id.0]); + write(&replacement, &bytes); + s.execute("links.update", &json!({"ids": [id.0]})).unwrap(); + assert!(s.doc().unwrap().marked_missing_links().is_empty()); + assert!(marked(&mut s).is_empty()); + s.execute("links.embed", &json!({"ids": [id.0]})).unwrap(); + std::fs::remove_file(&replacement).unwrap(); + assert!(marked(&mut s).is_empty()); +} + +#[test] +fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() { + for mode in ["automatically", "askWhenModified", "manually"] { + let dir = Folder::new(&format!("marker-watch-{mode}")); + let path = dir.file("art.png"); + let bytes = png(20, 20, RED); + write(&path, &bytes); + let mut s = session(); + s.prefs.update_links = mode.into(); + let id = place(&mut s, &path); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + let undo = s.doc().unwrap().history.undo.len(); + std::fs::remove_file(&path).unwrap(); + s.start_link_scan(); + s.wait_link_scan(); + s.poll_link_scan().unwrap().unwrap(); + assert_eq!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1, vec![id]); + write(&path, &bytes); + s.start_link_scan(); + s.wait_link_scan(); + s.poll_link_scan().unwrap().unwrap(); + assert!(s.doc().unwrap().missing_link_markers.as_ref().unwrap().1.is_empty()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + std::fs::remove_file(&path).unwrap(); + s.start_link_scan(); + s.wait_link_scan(); + let seen = s.doc().unwrap().missing_link_markers.as_ref().unwrap().0.clone(); + s.execute("shape.rectangle", &json!({"x": 1, "y": 1, "width": 3, "height": 4})).unwrap(); + s.poll_link_scan().unwrap().unwrap(); + assert!(std::sync::Arc::ptr_eq(&seen, &s.doc().unwrap().missing_link_markers.as_ref().unwrap().0)); + assert!(s.doc().unwrap().marked_missing_links().is_empty()); + s.start_link_scan(); + s.wait_link_scan(); + // Switching the toggle off while a look is pending must not resurrect its markers. + s.execute("view.showMissingLinks", &json!({"on": false})).unwrap(); + s.poll_link_scan().unwrap().unwrap(); + assert!(s.doc().unwrap().missing_link_markers.is_none()); + } +} + +#[test] +fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() { + let dir = Folder::new("marker-placed"); + let path = dir.file("placed.vectorcraft"); + write(&path, &vectorcraft_format::save_file(&vectorcraft_doc::Document::new(40.0, 20.0))); + let mut s = session(); + let id = place(&mut s, &path); + assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::PlacedDocument(_))); + std::fs::remove_file(&path).unwrap(); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert_eq!(marked(&mut s), vec![id.0]); + s.execute("object.move", &json!({"ids": [id.0], "dx": 15, "dy": 10})).unwrap(); + assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]); + s.execute("object.hide", &json!({"ids": [id.0]})).unwrap(); + assert!(s.doc().unwrap().marked_missing_links().is_empty()); + assert!(marked(&mut s).is_empty()); +} diff --git a/crates/mcp/src/tests/links.rs b/crates/mcp/src/tests/links.rs index 20298fc612..ffb2f8d986 100644 --- a/crates/mcp/src/tests/links.rs +++ b/crates/mcp/src/tests/links.rs @@ -27,8 +27,17 @@ fn headless_links_report_missing_files_and_relink() { let r = run(&mut h, "document.open", json!({"path": file("doc.vectorcraft")})); assert_eq!(r["missingLinks"][0]["ids"], json!([id]), "{r}"); assert_eq!(run(&mut h, "links.check", json!({}))["missing"], 1); + assert_eq!(run(&mut h, "links.marked", json!({})), json!({"on": false, "images": []})); + assert_eq!(run(&mut h, "view.showMissingLinks", json!({"on": true})), json!({"on": true})); + let markers = run(&mut h, "links.marked", json!({})); + assert_eq!(markers["images"][0]["id"], id); + assert_eq!(markers["images"][0]["bounds"].as_array().unwrap().len(), 4); + run(&mut h, "view.showMissingLinks", json!({"on": false})); + assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([])); + run(&mut h, "view.showMissingLinks", json!({"on": true})); let r = run(&mut h, "links.relink", json!({"ids": [id], "path": file("b.png")})); assert_eq!(r["relinked"], json!([id])); assert_eq!(run(&mut h, "links.check", json!({}))["links"][0]["status"], "ok"); + assert_eq!(run(&mut h, "links.marked", json!({}))["images"], json!([])); let _ = std::fs::remove_dir_all(dir); } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8e3315e357..9cb17deeae 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -24,6 +24,7 @@ mod fill; mod grid; mod home; mod input; +mod missing_links; mod outline; mod overlays; mod panes; @@ -341,6 +342,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if !revolve_edit { shaper_widget_overlay(app, &painter, &xf); } + if let Some(st) = app.session.active() { + missing_links::paint(st, &painter, &xf, &t); + } } ime_geometry(app, ui.ctx(), &xf); crate::place::paint_drop_highlight(app, ui.ctx(), &painter, rect); diff --git a/crates/ui-egui/src/canvas/missing_links.rs b/crates/ui-egui/src/canvas/missing_links.rs new file mode 100644 index 0000000000..7a25af311e --- /dev/null +++ b/crates/ui-egui/src/canvas/missing_links.rs @@ -0,0 +1,98 @@ +//! Transient, non-interactive decoration. Only canvas painters call this; artwork renderers, +//! printing and export never see it. The link watch worker refreshes the ids off the UI thread. + +use super::{Point, Shape, Stroke, Tokens, Xf}; + +pub(super) fn paint(st: &vectorcraft_engine::DocState, p: &egui::Painter, xf: &Xf, t: &Tokens) { + for id in st.marked_missing_links() { + let Some(b) = st.doc.node(id).and_then(vectorcraft_doc::Node::geometric_bounds) else { continue }; + let pts = xf.quad(b); + let rect = egui::Rect::from_points(&pts); + if !p.clip_rect().intersects(rect.expand(8.0)) { + continue; + } + p.add(Shape::closed_line(pts, Stroke::new(2.0, t.error))); + let at = xf.to_screen(Point::new(b.x0, b.y0)); + p.circle_filled(at, 7.0, t.error); + p.text(at, egui::Align2::CENTER_CENTER, "?", crate::theme::semibold(11.0), egui::Color32::WHITE); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_doc::{Document, ImageObject, LinkInfo, Node, NodeKind}; + + fn state() -> vectorcraft_engine::DocState { + let mut doc = Document::new(200.0, 150.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + doc.insert( + Some(layer), + 0, + Node::new( + id, + NodeKind::Image(Box::new(ImageObject { + key: "original-test-image".into(), + width: 40, + height: 20, + xf: vectorcraft_geom::Affine::IDENTITY, + link: Some(LinkInfo { path: "missing-marker-test.png".into(), ..Default::default() }), + placement: Default::default(), + pixels: None, + })), + ), + ) + .unwrap(); + let mut st = vectorcraft_engine::DocState::new(doc, None); + st.show_missing_links = true; + st.missing_link_markers = Some((st.doc.clone(), vec![id])); + st + } + + #[test] + fn missing_link_canvas_decoration_tracks_the_view_and_can_be_cleared() { + let mut st = state(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for (zoom, rotation) in [(0.25, 0.0), (1.0, 37.0), (8.0, 90.0)] { + let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let bounds = st.doc.node(st.marked_missing_links()[0]).unwrap().geometric_bounds().unwrap(); + let view = crate::state::View { zoom, rotation, center: bounds.center(), ..Default::default() }; + let xf = Xf::new(rect, &view); + let raw = egui::RawInput { screen_rect: Some(rect), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| paint(&st, ui.painter(), &xf, &Tokens::get(ui.ctx()))); + let outline = out + .shapes + .iter() + .find_map(|s| match &s.shape { + Shape::Path(path) if path.closed && path.stroke.width == 2.0 => Some(path), + _ => None, + }) + .expect("missing image has a red closed outline"); + assert_eq!(outline.points, xf.quad(bounds)); + assert_eq!(outline.stroke.color, egui::epaint::ColorMode::Solid(Tokens::get(&ctx).error)); + assert!(out.shapes.iter().any(|s| matches!(&s.shape, Shape::Circle(c) if c.radius == 7.0)), "fixed-size badge at every zoom"); + out.textures_delta.clear(); + } + st.show_missing_links = false; + let mut out = ctx.run_ui(Default::default(), |ui| { + let xf = Xf::new(ui.max_rect(), &Default::default()); + paint(&st, ui.painter(), &xf, &Tokens::get(ui.ctx())); + }); + assert!(!out.shapes.iter().any(|s| matches!(&s.shape, Shape::Path(_) | Shape::Circle(_)))); + out.textures_delta.clear(); + } + + #[test] + fn missing_link_menu_command_uses_the_engine_toggle() { + let mut app = crate::VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + assert_eq!(crate::menus::dynamic_label(&app, "view.showMissingLinks", ""), "Show Missing Links"); + app.run("view.showMissingLinks", serde_json::json!({"on": true})).unwrap(); + assert!(app.session.active().unwrap().show_missing_links); + assert_eq!(crate::menus::dynamic_label(&app, "view.showMissingLinks", ""), "Hide Missing Links"); + app.run("view.showMissingLinks", serde_json::json!({"on": false})).unwrap(); + assert!(!app.session.active().unwrap().show_missing_links); + } +} diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 5bd974bf92..8fb597488f 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -323,6 +323,7 @@ pub(crate) fn pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) if app.ui.view.edges { selected_objects(st, &painter, &xf); } + super::missing_links::paint(st, &painter, &xf, &t); if app.ui.view.rulers && app.ui.screen_mode < 3 { rulers(ui, full, &xf, None, RulerScale::document(app.session.general_unit(), st.doc.ruler_origin_for(v.artboard)), &t); } diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rs index 572c6b175d..e3d23a1aaa 100644 --- a/crates/ui-egui/src/keymap.rs +++ b/crates/ui-egui/src/keymap.rs @@ -26,6 +26,7 @@ pub const TOGGLES: &[&str] = &[ "view.rulers", "view.boundingBox", "view.transparencyGrid", + "view.showMissingLinks", "view.guides", "view.grid", "view.slices.hide", diff --git a/crates/ui-egui/src/menus/labels.rs b/crates/ui-egui/src/menus/labels.rs index 5820ded942..26353c0bcf 100644 --- a/crates/ui-egui/src/menus/labels.rs +++ b/crates/ui-egui/src/menus/labels.rs @@ -48,6 +48,9 @@ fn window_toggle_label(app: &VectorcraftApp, id: &str) -> Option { "view.transparencyGrid" => { if app.session.active().is_some_and(|d| d.transparency_grid) { "Hide Transparency Grid" } else { "Show Transparency Grid" }.into() } + "view.showMissingLinks" => { + if app.session.active().is_some_and(|d| d.show_missing_links) { "Hide Missing Links" } else { "Show Missing Links" }.into() + } "view.guides" => if v.guides { "Hide Guides" } else { "Show Guides" }.into(), "view.grid" => if v.grid { "Hide Grid" } else { "Show Grid" }.into(), "view.guides.lock" => if app.session.guides_locked() { "Unlock Guides" } else { "Lock Guides" }.into(), @@ -270,6 +273,8 @@ pub const DYNAMIC_LABELS: &[&str] = &[ "Show Bounding Box", "Hide Transparency Grid", "Show Transparency Grid", + "Show Missing Links", + "Hide Missing Links", "Hide Guides", "Show Guides", "Hide Grid", diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 3a55ab37c0..3d6201eb60 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -560,6 +560,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ), c("Hide Bounding Box", "view.boundingBox"), c("Show Transparency Grid", "view.transparencyGrid"), + c("Show Missing Links", "view.showMissingLinks"), c("Hide Text Threads", "view.textThreads"), c("Hide Gradient Annotator", "view.gradientAnnotator"), c("Hide Corner Widget", "view.cornerWidget"), diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index a7fe30185f..0743dc83b7 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -538,6 +538,11 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { /// The panel's flyout menu: the link commands for the selected rows, Select Linked / Embedded / /// Missing / Modified for the whole document, and the Show, Sort and thumbnail options. pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { + let on = app.session.active().is_some_and(|st| st.show_missing_links); + if menu_item(ui, tl!("Show Missing Links"), app.session.active().is_some(), on) { + crate::menus::invoke(app, "view.showMissingLinks", json!({"on": !on})); + } + ui.separator(); let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). let list = pstate::(ui.ctx(), "links-cache").list; diff --git a/docs/gaps.md b/docs/gaps.md index adb50d60fe..f29697d26f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,9 +1,11 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged ## Feature submission evidence +**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -36,6 +38,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-05 | minor | G15: long open strokes with an undashed width profile are outlined near the view while keeping profile positions on the full path; a 200,000-segment outline took 59.95 ms before and 8.44 ms after in local median runs. Closed and dashed profile strokes remain whole; estimate unchanged. | | 2026-11-05 | minor | G15: Direct Selection reuses one document hit result when choosing the cursor over a path; a 200,000-anchor path's segment cursor took 58.15 ms before and 29.33 ms after in local median runs. Cursor behavior is unchanged; estimate unchanged. | | 2026-11-05 | minor | G15: Selection skips building corner and pie widgets when the pointer is well outside a large selection; empty-canvas hover with 20,000 selected paths took 28.72 ms before and 16.41 ms after in local median runs. Other cursor targets remain active; estimate unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 6400a90994..d9bace9acb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -14,6 +14,26 @@ It has two backends: With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries only protocol messages. +## Missing-link canvas markers + +Use `run_command` (or its `command_run` alias) with these engine commands: + +```json +{"command":"view.showMissingLinks","params":{"on":true}} +{"command":"links.marked","params":{}} +{"command":"view.showMissingLinks","params":{"on":false}} +``` + +`links.marked` refreshes file status and returns `{on, images: [{id, bounds: [x0, y0, +x1, y1]}]}` for visible missing linked images and placed documents in the active document. +When the toggle is off, `images` is empty; `links.list {show: "missing"}` still lists missing +links independently. Neither command changes selection or undo history. The desktop canvas +draws a red outline and badge, checks files in the background about every two seconds even +with the Links panel closed, and removes markers after repair. The toggle is per open +document and starts off on reopen. Markers are never saved as artwork, rendered into exports +or printing, or exposed as selectable objects. Headless mode exposes the same state and +queries; it has no canvas on which to draw decorations. + ## Install and register From the repository root, with Rust 1.95+ and the platform's source-build prerequisites installed: diff --git a/docs/roadmap.md b/docs/roadmap.md index f3ad64942a..b7758f7036 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,9 +1,11 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged ## Feature submission evidence +**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -36,6 +38,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path (#5752); scores and estimates unchanged. | @@ -121,7 +124,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M2 | Drawing tools + smart guides | ✅ mostly done (Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537); no View submenu | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M2 | Drawing tools + smart guides | ✅ mostly done (Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending) | 12–18 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; #5547 adds transient missing-link canvas markers with View/Links controls and command access (focused tests, visual check and full CI pass) | 3–6 (existing scope; Affinity export unestimated) | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 49824735f9..0976bc79a0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,9 +1,11 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged ## Feature submission evidence +**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -31,6 +33,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-05 | minor | A nearby hit on a plain long stroke or outline avoids assembling its whole path. A hit near the middle of a 200,000-anchor path took about 11–13 ms before and 1.0–1.4 ms after in paired runs on a busy Windows machine; a miss inside the path's box fell from 18.7 ms to 1.6 ms, while a distant miss was unchanged. Other stroke styles and fill hits keep their existing checks. Scores and estimates unchanged; idle performance budgets remain unverified. | | 2026-11-05 | minor | Translating a type object without changing its text or formatting reuses glyph geometry and expanded character-stroke outlines between frames. The text appears at its new position with unchanged pixels. Scaling the type, editing its content or formatting, or changing installed fonts rebuilds the geometry; scores and estimates unchanged. | | 2026-11-05 | minor | Moving a large selection reuses the object locations found during command validation. A 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs; object positions, selection, and undo behavior stay the same. Scores and estimates unchanged. | @@ -208,7 +211,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Print, colour management, separations, flattener | 3 | 80% | print preview fidelity | 2–4 | estimated | | Automation (Actions, Variables, scripting, batch) | 3 | 60% | a scripting surface (Illustrator: JavaScript/ExtendScript), Batch, image and graph variables, dataset import/export | 8–14 | estimated; MCP `add_text` exposes existing vertical type; score and hours unchanged | | UI chrome (panels, Properties, workspaces, preferences) | 6 | 80% | Properties per context, 3 Preferences options stored but unused (#394, audited 2026-10-30: Open Documents As Tabs, Scratch Disks, legacy vector clipboard), SVG Interactivity, context menus beyond the canvas, accessibility | 13–20 | estimated; floating panels in OS windows of their own on the desktop (#4135), score and hours unchanged; macOS save Format menu implemented (#866), score and hours unchanged; Eyedropper cursor and precise setting checked (#1269), OS visual QA unverified; numeric-field focus and normal text drags regression-tested (#1326, in part); movements below the click threshold still select all; artboard navigation synchronizes the tool selection before destructive actions; status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates (sample widths cached by language/unit/DPI; regression and contributor original-file evidence below; scores/hours unchanged); effect dialogs' colour fields show a swatch that opens the Color Picker (#5365), score and hours unchanged | -| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated | +| Libraries, Links, Package | 2 | 82% | shared libraries, linked graphics, gradients and patterns as library items (no cloud by design) | 2–3 | estimated; #5547: missing-link canvas outlines and badges, View/Links toggles and command API; focused regressions, headless visual check and full CI pass; score and hours unchanged | | Generative AI (Text to Vector, Generative Recolor, Shape Fill, Concept to Vector, Prompt to Edit, Rewrite Text) | 2 | 0% | a pluggable provider and the panels; needs an owner decision on models | 30–60 | measured (absent) | | **Feature depth** | **105** | **~75%** | | **~250–420** | | | Interaction-fidelity pass (every tool's modifiers, cursors, Properties per context) | | | [ui-parity.md](ui-parity.md) | 60–90 | estimated | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index abe967692d..15c2f7bd8e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,9 +1,11 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged ## Feature submission evidence +**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. + Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -38,6 +40,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-06 | minor | Properties panel in Edit Artboards (Shift+O): a Transform section with the shared reference point, X, Y, W and H, the preset and orientation, and Move and Scale Artwork with Artboard, above the Artboards section with the name, Artboard Options and Fill (#5219); scores and estimates unchanged | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged | | 2026-11-05 | minor | Direct Selection: Shift-click picks several points of a blend's spine and dragging one moves them all, with the key objects on them, in one undo step (#5285); scores and estimates unchanged | @@ -419,6 +422,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Artwork Cleanup add-on text tools (VectorCraft addition): the panel's Text row, which the panel can hide, and Object › Plug-ins › Artwork Cleanup set the alignment of point type keeping its place, break type into lines (Shift-click: paragraphs), words or glyphs, split type at the cursor, reset a text transform (Alt-click: and its horizontal scale), combine point type, remove line or paragraph breaks and replace missing fonts, each one undo step | done | `addon.cleanup.*` text commands, `crates/ui-egui/src/addons/cleanup.rs` and its tests; a VectorCraft addition, so it is not scored | | Color Effects add-on (VectorCraft addition): live Exposure, Desaturate and Invert Colors in Effect › Color Effects and Object › Plug-ins › Color Effects; its panel picks a colour adjustment and its values and adds it as a live effect or applies it as a filter, into the colours, as one undo step; Select by Color Kind selects the objects that use spot colours, carry colour effects, or are RGB, CMYK or grayscale images; Vector Halftone draws an object as halftone dots live (the dots Object › Vector Halftone makes), which Expand Appearance and the exporters write as paths; Duotone prints each colour's tone with one to four inks (a tint of a spot tone's swatch, or the CMYK mix of several), live or as a filter, its dialog a row per tone and the picked tone's curve; Print Ink Fixes (a CMYK document's ink limit, white overprint removed, black overprint set) opens its options from the submenu and the panel's Inks | done | `addon.color.*`, `crates/ui-egui/src/addons/color.rs` and its tests; not a feature of the reference app, so it is not scored | | Color Effects add-on (VectorCraft addition): Object › Plug-ins › Color Effects › Find Nearest Swatch… picks a Library (Document Swatches, a built-in library, or a library or colour book the user saved or loaded) and Fill and Stroke, lists each colour of the selection with its three closest swatches (chip, name, ΔE 2000), and Apply gives each colour its nearest swatch (global and spot swatches linked; a library's swatches added to the document first), one undo step | done | #4923; `addon.color.nearestSwatch`, `addon.color.applyNearestSwatch`, `crates/engine/src/cmd/addons/color/nearest.rs`, `crates/ui-egui/src/addons/color/nearest.rs` and their tests; not a feature of the reference app, so it is not scored | +| Missing linked images and placed documents can show red canvas bounds and a badge; View and Links panel toggles share transient per-document state; command API can set and list markers | done | #5547; `cmd/links.rs`, `link_watch.rs`, `canvas/missing_links.rs`; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass | | Selection Tools add-on (VectorCraft addition): Object › Plug-ins › Selection Tools › Select by Artboards… lists every artboard (number, name, width × height in the document's units), filters them by name, chooses several (click, Shift-click for a range, Cmd/Ctrl-click to toggle; Select All / None act on the rows shown; a count of those chosen), fits a row's artboard in the window on double-click and makes it active, and on OK selects the objects overlapping, fully inside or fully outside the chosen artboards (Overlapping is All on Active Artboard's test) | done | #5525, #5548, #5549; `addon.select.byArtboards`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select.rs` and their tests; not a feature of the reference app | | Selection Tools add-on (VectorCraft addition): Select Linked, Select Embedded, Select Missing and Select Modified in Object › Plug-ins › Selection Tools and the Links panel menu (off when no image has that status; Shift adds to the selection) select the images and placed documents with that link status, leaving out hidden, locked, template-layer and outside-isolation ones, which the status bar counts (e.g. "Selected 9 missing images; 3 more are hidden or locked"); Select by Link Status… lists them with name, status and format, searches by name, filters by status, picks with checkboxes and All / None, and selects with Zoom to Selection on by default | done | #5526; `addon.select.byLinkStatus`, `crates/engine/src/cmd/addons/select.rs`, `crates/ui-egui/src/addons/select/link_status.rs` and their tests; not a feature of the reference app | From 8767f7c5726a590e35fb09a78aafe724807ed2fd Mon Sep 17 00:00:00 2001 From: ruchirguitar <113586074+ruchirguitar@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:44:07 +0530 Subject: [PATCH 002/334] 5547: replace local drafting notes with revision entries --- ROADMAP.md | 6 ++---- docs/gaps.md | 6 ++---- docs/roadmap.md | 8 +++----- docs/target-app-parity.md | 6 ++---- docs/ui-parity.md | 6 ++---- 5 files changed, 11 insertions(+), 21 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 6e06b62d1b..7701b6fe72 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,7 +1,5 @@ # VectorCraft Roadmap -**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. - - Contour add-on (beyond Illustrator): drag a selected shape's edge outward or inward for a live, editable offset copy, with a floating bar for distance and Sharp, Round or Square corners; Bake turns it into paths. Scores and estimates unchanged. - Compound Shapes add-on (beyond Illustrator): a menu for Make, Release and Expand Compound Shape and a setting, off by default, that makes the Pathfinder panel's Shape Mode buttons create compound shapes on a click. Scores and estimates unchanged. @@ -16,7 +14,7 @@ **Stage: alpha** · next: beta, ~13 points (ready for real work ~62% → ~75%, and reliable `.ai` exchange) and ~170–270 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog draft complete under the translation tests; contributor loanword terminology reviewed; wider proofreading welcome; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; new gradients follow document color mode; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) VectorCraft is a clean-room, open-source, pure-Rust reimplementation of the Adobe Illustrator workflow. It runs on macOS, Windows, Linux, FreeBSD and the web (WASM), and agents can drive all of it over MCP, the CLI and a JSON @@ -225,7 +223,7 @@ The full earlier record of what landed is kept in [docs/roadmap.md](docs/roadmap | Date | Change | Summary | |---|---|---| -| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | +| 2026-11-06 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Regression, visual and full CI checks passed; scores and estimates unchanged. | | 2026-11-06 | minor | Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged | | 2026-11-05 | minor | Progress log row for the Type Tools add-on's Release Type on a Path (#5532); headline numbers unchanged. | | 2026-11-03 | minor | Progress log row for the Type Tools add-on's Text Tweaker (#4924); headline numbers unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index f29697d26f..8a4e5f9f0f 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,11 +1,9 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. - Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -38,7 +36,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | +| 2026-11-06 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Regression, visual and full CI checks passed; scores and estimates unchanged. | | 2026-11-05 | minor | G15: long open strokes with an undashed width profile are outlined near the view while keeping profile positions on the full path; a 200,000-segment outline took 59.95 ms before and 8.44 ms after in local median runs. Closed and dashed profile strokes remain whole; estimate unchanged. | | 2026-11-05 | minor | G15: Direct Selection reuses one document hit result when choosing the cursor over a path; a 200,000-anchor path's segment cursor took 58.15 ms before and 29.33 ms after in local median runs. Cursor behavior is unchanged; estimate unchanged. | | 2026-11-05 | minor | G15: Selection skips building corner and pie widgets when the pointer is well outside a large selection; empty-canvas hover with 20,000 selected paths took 28.72 ms before and 16.41 ms after in local median runs. Other cursor targets remain active; estimate unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index b7758f7036..06c12a3b8a 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,11 +1,9 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) ## Feature submission evidence -**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. - Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -38,7 +36,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| -| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | +| 2026-11-06 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Regression, visual and full CI checks passed; scores and estimates unchanged. | | 2026-11-05 | minor | Effect dialogs: a colour swatch beside a hex colour field follows typed values, and a double-click opens the Color Picker over the dialog, whose OK fills the field (#5365); scores and estimates unchanged. | | 2026-11-05 | minor | Selection Tools add-on: Select Linked, Embedded, Missing and Modified select the images and placed documents with that link status (Object › Plug-ins › Selection Tools and the Links panel menu; Shift adds), and Select by Link Status… lists them by name, status and format to pick from, optionally zooming to them; what is hidden, locked, on a template layer or outside the isolated group is left out and the status bar says how many (#5526, a VectorCraft addition); scores and estimates unchanged (estimated). | | 2026-11-05 | minor | Pencil and Paintbrush: a new stroke with Keep selected off leaves nothing selected, the earlier selection included, while Keep selected on selects only the new path (#5752); scores and estimates unchanged. | @@ -124,7 +122,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | M2 | Drawing tools + smart guides | ✅ mostly done (Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537); no View submenu | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M2 | Drawing tools + smart guides | ✅ mostly done (Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending) | 12–18 | -| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; #5547 adds transient missing-link canvas markers with View/Links controls and command access (focused tests, visual check and full CI pass) | 3–6 (existing scope; Affinity export unestimated) | +| M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; View and Links controls and command access for transient missing-link canvas markers (#5547) | 3–6 (existing scope; Affinity export unestimated) | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel, Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default | 4–8 | | M5 | Performance | 🟡 background render + caches + MT done; `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0976bc79a0..287983bf9a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,11 +1,9 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026) ## Feature submission evidence -**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. - Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -33,7 +31,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | +| 2026-11-06 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Regression, visual and full CI checks passed; scores and estimates unchanged. | | 2026-11-05 | minor | A nearby hit on a plain long stroke or outline avoids assembling its whole path. A hit near the middle of a 200,000-anchor path took about 11–13 ms before and 1.0–1.4 ms after in paired runs on a busy Windows machine; a miss inside the path's box fell from 18.7 ms to 1.6 ms, while a distant miss was unchanged. Other stroke styles and fill hits keep their existing checks. Scores and estimates unchanged; idle performance budgets remain unverified. | | 2026-11-05 | minor | Translating a type object without changing its text or formatting reuses glyph geometry and expanded character-stroke outlines between frames. The text appears at its new position with unchanged pixels. Scaling the type, editing its content or formatting, or changing installed fonts rebuilds the geometry; scores and estimates unchanged. | | 2026-11-05 | minor | Moving a large selection reuses the object locations found during command validation. A 20,000-object nudge took 58.07 ms before and 51.26 ms after in paired median runs; object positions, selection, and undo behavior stay the same. Scores and estimates unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 15c2f7bd8e..8c3ecf8eeb 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,11 +1,9 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) · **Local draft:** #5547; full CI and headless visual check pass; scores unchanged +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-06 · **Change:** minor (Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) ## Feature submission evidence -**#5547 local feature draft — 2026-11-06:** Show Missing Links in View and the Links panel decorates missing linked images and placed documents with a red outline and badge. Markers are transient canvas state; `view.showMissingLinks {on}` controls them and `links.marked` lists their ids and bounds. File checks refresh on the link watch worker with the panel closed; repair clears markers, and artwork rendering, save and undo stay separate. Engine, canvas and MCP focused regressions pass; headless canvas renders with markers on and off were inspected. All 12 `cargo xtask ci` steps pass, including WebAssembly. Scores and estimates unchanged. - Raster rendering fits and preflattens curved stroke outlines more tightly only below four times the raster tolerance, retaining thin-band coverage without changing stroke weight or vector export geometry. Current cached character/object outlines, cropped long strokes, gradient clips and effect rasters share the helper; cropped-region reuse and guarded flattening remain. The unchanged `fractional_curved_strokes_retain_coverage_between_notches` regression covers fractional weights, rotation, phase, opacity and f32-rounded endpoints. This is a quality/cost tradeoff, not a speed claim. Scores and estimates unchanged. **PR #3273 revision — 2026-11-04:** Thin curved stroke coverage ported to the current raster-only cache, cropped-long-stroke and effect paths with guarded flattening; vector export geometry unchanged. Scores and estimates unchanged. @@ -40,8 +38,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| -| 2026-11-06 | minor | #5547: missing-link canvas markers, View/Links toggles and command API drafted locally; focused engine/canvas/MCP regressions, headless visual check and full CI (including WebAssembly) pass; scores and estimates unchanged. | | 2026-11-06 | minor | Properties panel in Edit Artboards (Shift+O): a Transform section with the shared reference point, X, Y, W and H, the preset and orientation, and Move and Scale Artwork with Artboard, above the Artboards section with the name, Artboard Options and Fill (#5219); scores and estimates unchanged | +| 2026-11-06 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Regression, visual and full CI checks passed; scores and estimates unchanged. | | 2026-11-06 | minor | Scrubby labels: the Control bar's Stroke: and Opacity: and the Properties panel's Stroke, links to their panels, scrub the field after them as other labels do; a click still opens the panel (#4088); scores and estimates unchanged | | 2026-11-05 | minor | Direct Selection: Shift-click picks several points of a blend's spine and dragging one moves them all, with the key objects on them, in one undo step (#5285); scores and estimates unchanged | | 2026-11-05 | minor | Direct Selection: Cmd/Ctrl held lends the Selection tool, whose bounding box shows while the key is down over objects selected whole; its handles scale and rotate, and a Cmd drag moves the whole object with its direct-selected anchors kept (#3901); scores and estimates unchanged | From 26e0cef48dad241c0e387c6dbb101c91c9a9f06c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:19:11 -0800 Subject: [PATCH 003/334] Scripts: ScriptUI palettes stay open after the run and run their handlers in line new Window("palette") in a script with a named #targetengine shows a palette that stays open beside the documents after the run ends. show() runs onShow and returns at once; hide(), show() and close() work as for a dialog, and close() and the close box run onClose. Each click, change or close on a palette runs its handler as a run of its own in the palette's engine, with its own report and undo step. While another run goes on, the event waits and runs after it, oldest first; a newer event for the same control or close replaces a waiting one. An error in a handler ends that run and leaves the palette open. A palette in a script without #targetengine, or with #targetengine main, throws an Error that asks for a #targetengine line. Palettes close when their engine is dropped or ends with an internal error, and when the session ends. A session keeps at most 16 palettes and 64 waiting events. script.palettes lists the palettes and their controls, and script.palette.event gives a palette a click, change or close. The script checker lists palettes under dialogs instead of hostOnly. --- crates/engine/src/cmd/scripts.rs | 45 +- crates/engine/src/lib.rs | 3 + crates/engine/src/script/files.rs | 10 +- crates/engine/src/script/mod.rs | 35 +- crates/engine/src/script/palettes.rs | 347 ++++++++++++++ crates/engine/src/script/scriptui.rs | 93 +++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_palettes.rs | 312 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/realm.rs | 10 + crates/js/src/scriptui.rs | 425 ++++++++++++++---- crates/js/src/scriptui_tests.rs | 126 +++++- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/lib.rs | 4 +- crates/scriptcheck/src/tests.rs | 6 + crates/ui-egui/src/app.rs | 6 + crates/ui-egui/src/dialogs/script_window.rs | 8 +- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 33 ++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/script_palettes.rs | 93 ++++ crates/ui-egui/src/script_runs.rs | 6 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_palettes.rs | 109 +++++ docs/mcp.md | 50 ++- docs/target-app-parity.md | 3 +- 51 files changed, 1649 insertions(+), 108 deletions(-) create mode 100644 crates/engine/src/script/palettes.rs create mode 100644 crates/engine/src/tests/script_palettes.rs create mode 100644 crates/ui-egui/src/script_palettes.rs create mode 100644 crates/ui-egui/src/tests/script_palettes.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index fd02b3a9a1..831b56c586 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar, at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, windows and resource strings throw that they are not available yet); new Window(\"palette\", title) builds a palette the same way, only in a script with #targetengine and a name other than main (elsewhere it throws an error that says so): its show() returns at once and the palette stays open after the run, beside the documents, until close(), the close box (each runs onClose, which can keep it open by returning false) or the end of its engine or the session; each click, change or close the person gives it runs its handler as a run of its own in that engine, once no run is going, oldest first, and a newer one for the same control or the same close takes a waiting one's place (script.palettes, script.palette.event; at most 16 palettes and 64 waiting events); show() on a dialog waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -63,6 +63,24 @@ pub fn specs() -> Vec { always, engine_drop ), + cmd!( + query "script.palettes", + "List Script Palettes", + [], + None, + "{} the ScriptUI palettes that runs in named engines showed and have not closed, shown or hidden, in the order they were first shown, and the events that wait for a run → {palettes: [{id, engine, title, visible, controls: [{index, kind, name, text, enabled, visible, value (check box, radio button, slider, progress bar), items and selection (lists)}]}], waiting: events waiting, limit: 16, waitingLimit: 64}", + always, + palettes + ), + cmd!( + query "script.palette.event", + "Script Palette Event", + [], + None, + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + always, + palette_event + ), cmd!( query "script.console", "Script Console", @@ -245,6 +263,31 @@ fn engine_drop(s: &mut Session, p: &Value) -> Result { Ok(json!({"dropped": true, "name": name})) } +fn palettes(s: &mut Session, _: &Value) -> Result { + let list: Vec = s.script_palettes().iter().map(script::palettes::palette_json).collect(); + Ok(json!({ + "palettes": list, + "waiting": s.script_palette_events_waiting(), + "limit": script::palettes::MAX_PALETTES, + "waitingLimit": script::palettes::MAX_WAITING, + })) +} + +fn palette_event(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.palette.event"; + let Some(id) = p.get("palette").and_then(Value::as_u64) else { + return Err(bad(C, "`palette` must be a palette's id, as script.palettes lists it")); + }; + let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; + let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; + let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; + if s.script_frames { + return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); + } + s.script_palette_run_waiting() +} + fn console_lines(s: &mut Session, _: &Value) -> Result { Ok(s.script_console().to_json()) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 68067dc697..5a790a06d9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -312,6 +312,9 @@ pub struct Session { pub(crate) script_high_water: std::collections::HashMap, /// 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, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 94ef3bdf9e..467e148696 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -216,6 +216,9 @@ pub(crate) struct Setup { pub script: Option, /// 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, /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). pub data_dir: Option, /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source @@ -302,7 +305,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(); @@ -373,6 +376,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 { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index cb0398500a..de8f299cec 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -47,14 +47,20 @@ //! run. An engine keeps no document and no run: its host functions reach the run through a link //! 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 +//! palette closes with its engine. pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod palettes; 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}; @@ -801,6 +807,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, + /// The script file the run was read from; `None` for a script given as text. + file: Option, + /// For the run of a palette's handler, the palette's id and the event, until the palette takes + /// it ([`palettes`]). + palette_event: RefCell>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1686,6 +1699,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:?}"))), @@ -1933,6 +1947,7 @@ impl Session { lost }); drop(lost); + self.keep_engines_palettes(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -1954,6 +1969,7 @@ impl Session { /// Begins a run of `request`. → the run's name. pub(crate) fn script_start(&mut self, request: Request) -> Result { + 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() { @@ -2048,6 +2064,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(); @@ -2068,6 +2085,9 @@ impl Session { 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), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { @@ -2122,6 +2142,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); @@ -2212,6 +2233,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(); raise_ids(self); self.script_stop.clear(); self.reset_tool(); @@ -2481,6 +2503,7 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result std::result::Result realm.refresh_script_ui().map(|()| 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. + Err(e) if named && e.kind != RunErrorKind::Internal => { + let _ = realm.refresh_script_ui(); + Err(e) + } + r => r, + } }) }); if let Some(started) = started { diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs new file mode 100644 index 0000000000..d6ff578f29 --- /dev/null +++ b/crates/engine/src/script/palettes.rs @@ -0,0 +1,347 @@ +//! 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. While an event waits, another click +//! on the same control, another change of it or another close of the same palette takes its place +//! in line, with the newer value, instead of waiting as well. +//! +//! 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::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, + /// 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. + 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, + /// 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, 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, +} + +/// The palettes of a session, and the events that wait for a run. +#[derive(Debug, Default)] +pub(crate) struct Palettes { + list: Vec, + waiting: VecDeque, + last_id: u64, + /// The event the run that starts next handles ([`Session::script_palette_start`]). + pub(crate) starting: Option, +} + +/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? +fn same_place(a: &UiEvent, b: &UiEvent) -> bool { + match (a, b) { + (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, + (UiEvent::Close, UiEvent::Close) => true, + _ => false, + } +} + +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`. → its id. + pub(crate) fn show( + &mut self, + id: Option, + engine: &str, + (file, grants): (Option, String), + dialog: ScriptUiDialog, + ) -> std::result::Result { + 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 }); + 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)); + self.waiting.retain(|q| q.palette != id); + self.list.len() != before + } + + /// 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 = self.list.iter().map(|p| p.id).collect(); + self.waiting.retain(|q| open.contains(&q.palette)); + } + + /// 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 { + 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 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, + }; + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + slot.event = event; + slot.list = list; + 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, list, grants: None }); + Ok(Waiting::Added) + } + + /// The oldest waiting event whose palette is still shown, and that palette. + fn next(&mut self) -> Option<(ScriptPalette, Queued)> { + while let Some(q) = self.waiting.pop_front() { + if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { + return Some((p.clone(), q)); + } + } + None + } +} + +/// `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!("{}\nWindow.__vcPaletteEvent();\n", engine_line(engine)) +} + +/// 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 { + 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 v.as_u64() { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + 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 = 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() + } + + /// 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 { + 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. + pub fn script_palette_start(&mut self) -> Option> { + // An event waits while a drag or an undo group is open, which a run cannot start in. + if self.script_running() || self.script_palettes.waiting.is_empty() || self.settle_for_script().is_err() { + return None; + } + let (palette, mut queued) = self.script_palettes.next()?; + 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 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(), + }; + self.script_palettes.starting = Some(queued); + let r = 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 = 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, + /// the one just given last. → that one's report. + pub(crate) fn script_palette_run_waiting(&mut self) -> Result { + let mut last = Err(EngineError::Other("no script palette event waits".into())); + while let Some(started) = self.script_palette_start() { + last = started.and_then(|_| self.script_run_to_end()); + } + last + } +} diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 2f77fbb5b8..8ca7154e47 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -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 @@ -136,6 +139,9 @@ pub struct UiNode { pub max: f64, pub items: Vec, pub selection: Option, + /// 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, @@ -497,6 +503,7 @@ pub fn parse(d: &Data) -> Result { max, items, selection, + revision: number(field(f, "revision")).unwrap_or(0.0), multiline: flag("multiline"), readonly: flag("readonly"), rect: UiRect::default(), @@ -668,7 +675,89 @@ fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result /// 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)), + ]) +} + +/// 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 { + 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 { + 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 { + 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), dialog); + shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) +} + +/// The palette `id`'s controls as a handler or `add()` left them. +fn palette_update(host: &Host, args: &[Data]) -> Result { + 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) +} + +fn palette_hide(host: &Host, args: &[Data]) -> Result { + 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 { + 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, items}`, as `show()` +/// takes a dialog's event with the palette's id added, 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 { + let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; + let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; + fields.push(("palette".into(), Data::Number(queued.palette 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))); + } + Ok(Data::Object(fields)) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 1685adc40f..55395c0d01 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -170,6 +170,7 @@ impl Session { script_frames: false, script_high_water: Default::default(), script_in_run: false, + script_palettes: Default::default(), script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 58addcd9fe..c655eea8b5 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -176,6 +176,7 @@ mod script_engines; mod script_folder; mod script_include; mod script_io; +mod script_palettes; mod script_run; mod script_scriptui; mod scripts; diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs new file mode 100644 index 0000000000..006f022627 --- /dev/null +++ b/crates/engine/src/tests/script_palettes.rs @@ -0,0 +1,312 @@ +//! ScriptUI palettes in a script: a named engine to show them in, the events that wait for a run +//! and run one at a time after it, the events that take a waiting one's place, `close()` and the +//! close box, the engine's end, and the limits. + +use serde_json::{Value, json}; + +use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; +use crate::script::scriptui::PALETTE_NEEDS_ENGINE; +use crate::script::{DialogAnswer, UiEvent, Waiting}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "p.js"})) +} + +/// Pumps the run in the app until it ends, or until it waits at a dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_dialog().is_some() || s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Runs `source` in the app to its end. +fn run_in_app(s: &mut Session, source: &str) -> Value { + s.script_frames = true; + assert_eq!(run(s, source).unwrap()["running"], true); + pump(s).expect("the run ended").unwrap() +} + +/// A palette in the engine `tools` with a button (control 1) whose handler counts its clicks and +/// adds a rectangle, and a field (control 2). +const TOOLS: &str = "#targetengine tools\n\ + var clicks = 0; var p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + var field = p.add('edittext', undefined, ''); \ + go.onClick = function () { clicks++; vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); vc.log('click ' + clicks); }; \ + field.onChange = function () { vc.log('change ' + field.text); }; p.show(); vc.log('shown');"; + +fn only_palette(s: &Session) -> u64 { + let list = s.script_palettes(); + assert_eq!(list.len(), 1, "{list:?}"); + list[0].id +} + +#[test] +fn show_returns_at_once_and_the_palette_stays_after_the_run() { + let mut s = one_doc(); + let r = run(&mut s, TOOLS).unwrap(); + assert_eq!(r["log"], json!(["shown"]), "show() did not wait: {r}"); + let id = only_palette(&s); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["engine"], "tools"); + assert_eq!(listed["palettes"][0]["title"], "Tools"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Go"); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"])); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a handler's run is one undo step"); + let changed = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 2, "value": "abc"})).unwrap(); + assert_eq!(changed["log"], json!(["change abc"])); +} + +#[test] +fn a_later_run_in_the_engine_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + run(&mut s, "#targetengine tools\ngo.enabled = false; go.text = 'Wait';").unwrap(); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); + assert_eq!(listed["palettes"][0]["controls"][0]["text"], "Wait"); + assert!(s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).is_err(), "a disabled button takes no click"); +} + +#[test] +fn a_handler_keeps_the_file_grants_of_the_script_that_showed_the_palette() { + let base = std::env::temp_dir().join(format!("vc-script-palette-grants-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + std::fs::create_dir_all(base.join("picked")).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let data = base.join("picked/data.txt"); + std::fs::write(&data, "hello").unwrap(); + let path = serde_json::to_string(&data.to_string_lossy()).unwrap(); + let main = base.join("main/main.jsx"); + let source = format!( + "#targetengine grants\nif (typeof picked == 'undefined') {{ var picked = File.openDialog('p'); }} \ + var p = new Window('palette'); var b = p.add('button', undefined, 'Read'); \ + b.onClick = function () {{ var f = new File({path}); vc.log(f.open('r') ? f.read() : f.error); }}; p.show();" + ); + std::fs::write(&main, source).unwrap(); + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + break; + } + assert!(s.script_pump().is_none(), "the run waits at its file dialog"); + } + let picked = data.to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked], always: true })); + pump(&mut s).expect("the run ended").unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("the handler ended").unwrap()["log"], json!(["hello"])); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn a_failed_run_in_the_engine_still_changes_what_the_palette_shows() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + assert!(run(&mut s, "#targetengine tools\ngo.enabled = false; throw new Error('after');").is_err()); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["enabled"], false, "{listed}"); +} + +#[test] +fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine lists\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine lists\nconfirm('Go?'); l.removeAll(); l.add('item', 'a'); l.add('item', 'b');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + let pick = UiEvent::Change(1, crate::script::UiValue::Index(Some(1))); + assert_eq!(s.script_palette_event(id, pick.clone()), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(s.script_palette_event(id, pick), Ok(Waiting::Added), "a change given after it is for the new items"); + assert!(s.script_palette_start().unwrap().is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); +} + +#[test] +fn a_palette_click_during_another_run_runs_after_it() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "var a = confirm('Go?'); vc.log('busy done');").unwrap()["running"], true); + assert!(pump(&mut s).is_none(), "the run waits at its confirm"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().is_none(), "the click waits while another run holds the lease"); + assert_eq!(s.script_palette_events_waiting(), 1); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["busy done"])); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["click 1"])); + assert_eq!(s.script_palette_events_waiting(), 0); +} + +#[test] +fn double_clicks_while_queued_run_once() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged)); + let text = |t: &str| UiEvent::Change(2, crate::script::UiValue::Text(t.into())); + assert_eq!(s.script_palette_event(id, text("a")), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, text("ab")), Ok(Waiting::Merged), "a later change takes the waiting one's place"); + assert_eq!(s.script_palette_events_waiting(), 2); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + let mut logs = vec![]; + while let Some(started) = s.script_palette_start() { + started.unwrap(); + logs.push(pump(&mut s).unwrap().unwrap()["log"].clone()); + } + assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); +} + +#[test] +fn a_palette_from_a_script_without_a_named_engine_is_refused() { + let mut s = one_doc(); + for source in ["", "#targetengine main\n"] { + let r = run(&mut s, &format!("{source}try {{ new Window('palette'); }} catch (e) {{ vc.log(e.message); }}")).unwrap(); + assert_eq!(r["log"], json!([PALETTE_NEEDS_ENGINE]), "{source:?}"); + } + assert!(s.script_palettes().is_empty()); +} + +#[test] +fn close_fires_on_close_and_frees_the_window() { + let mut s = one_doc(); + run(&mut s, &format!("{TOOLS} p.onClose = function () {{ vc.log('closing'); }};")).unwrap(); + let id = only_palette(&s); + let closed = s.execute("script.palette.event", &json!({"palette": id, "event": "close"})).unwrap(); + assert_eq!(closed["log"], json!(["closing"])); + assert!(s.script_palettes().is_empty(), "the close box freed the palette"); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains(&format!("there is no script palette {id}")), "{e}"); + + run(&mut s, TOOLS).unwrap(); + let r = + run(&mut s, "#targetengine tools\nvar asked = 0; p.onClose = function () { asked++; return asked > 1; }; p.close(); vc.log(asked);").unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(s.script_palettes().len(), 1, "onClose returned false: the palette stays open"); + run(&mut s, "#targetengine tools\np.close();").unwrap(); + assert!(s.script_palettes().is_empty(), "close() freed the palette"); +} + +#[test] +fn dropping_the_engine_closes_its_palettes() { + let mut s = one_doc(); + run_in_app(&mut s, TOOLS); + run_in_app(&mut s, "#targetengine other\nnew Window('palette').show();"); + let id = s.script_palettes()[0].id; + s.script_palette_event(id, UiEvent::Click(1)).unwrap(); + s.execute("script.engine.drop", &json!({"name": "tools"})).unwrap(); + let left: Vec<&str> = s.script_palettes().iter().map(|p| p.engine.as_str()).collect(); + assert_eq!(left, ["other"]); + assert_eq!(s.script_palette_events_waiting(), 0, "the dropped palette's event no longer waits"); + assert!(s.script_palette_start().is_none()); +} + +#[test] +fn an_erroring_handler_ends_its_run_and_leaves_the_palette_open() { + let mut s = one_doc(); + let before = s.documents()[0].history.undo.len(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5}); throw new Error('broken'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("broken"), "{e}"); + assert_eq!(s.documents()[0].history.undo.len(), before, "the failed handler's rectangle was rolled back"); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_dialog_in_a_handler_throws_in_the_app() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); var b = p.add('button', undefined, 'Go'); \ + b.onClick = function () { try { confirm('Sure?'); } catch (e) { vc.log('confirm'); } \ + try { var d = new Window('dialog'); d.add('button', undefined, 'OK'); d.show(); } catch (e) { vc.log('dialog'); } }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).expect("no dialog waits").unwrap()["log"], json!(["confirm", "dialog"])); + assert_eq!(only_palette(&s), id); +} + +#[test] +fn a_handler_with_nobody_to_ask_ends_at_its_dialog() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); p.add('button', undefined, 'Go').onClick = function () { alert('hi'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("no answer left"), "{e}"); + assert_eq!(only_palette(&s), id, "the palette stays open"); +} + +#[test] +fn palettes_and_waiting_events_have_limits() { + let mut s = one_doc(); + let r = run( + &mut s, + "#targetengine many\nfor (var i = 0; i < 40; i++) { try { new Window('palette').show(); } catch (e) { vc.log([i, e.name]); break; } }", + ) + .unwrap(); + assert_eq!(r["log"], json!([[MAX_PALETTES, "RangeError"]])); + s.execute("script.engine.drop", &json!({"name": "many"})).unwrap(); + assert!(s.script_palettes().is_empty()); + + run_in_app( + &mut s, + "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + for c in 1..=MAX_WAITING { + assert_eq!(s.script_palette_event(id, UiEvent::Click(c)), Ok(Waiting::Added)); + } + let e = s.script_palette_event(id, UiEvent::Click(MAX_WAITING + 1)).unwrap_err(); + assert!(e.contains("this one was not kept"), "{e}"); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Merged), "a waiting control still takes a click"); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 800b0f35df..08badaae56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,7 +44,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), - ("Window.", "length prototype"), + ("Window.", "__vcPaletteEvent length prototype"), ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ad8d10acce..117ae759b6 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -502,6 +502,16 @@ 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, and what it throws ends the run. + pub fn refresh_script_ui(&mut self) -> Result<(), RunError> { + match crate::scriptui::refresh(&mut self.interp) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// 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`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index f2f8a33b2c..52f42ee49c 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -2,10 +2,11 @@ //! describes it, whose //! drawing a host does ([`crate::Realm::define_script_ui`]). //! -//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A -//! window of type `palette` or `window`, and a resource specification in place of the type, throw -//! an `Error` that says they are not available yet. `add(type[, bounds, text, properties])` adds a -//! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, +//! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`, and +//! `new Window("palette", ...)` a palette, once the host's `palette` allows it. A window of type +//! `window`, and a resource specification in place of the type, throw an `Error` that says they are +//! not available yet. `add(type[, bounds, text, properties])` adds a +//! control to a dialog, a palette, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet. A @@ -24,6 +25,15 @@ //! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether //! it ended normally. //! +//! A palette's `show()` gives the host's `paletteShow` its description and its id (none the first +//! time), which gives back the id, then runs `onShow` and returns `undefined` without waiting. +//! `hide()` gives `paletteHide` the id, and `close()` runs `onClose`, and unless it returns `false` +//! gives `paletteClose` the id; a `close()` while `onClose` runs does nothing more. The realm keeps +//! each palette the host shows until it closes. `Window.__vcPaletteEvent()` takes an event from the +//! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a +//! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown +//! palette does the same for that palette, so the host's list of its controls stays in step. +//! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] @@ -66,8 +76,14 @@ const CLOSING: &str = "__vcClosing"; const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const PALETTE_ID: &str = "__vcPaletteId"; +const IN_CLOSE: &str = "__vcInClose"; +/// How many times a list's items were added or removed: a palette's waiting change of the list is +/// for the items it had then. +const REVISION: &str = "__vcRevision"; -/// The objects of `Window`, kept by the realm, and the dialog that is showing. +/// The objects of `Window`, kept by the realm, the dialog that is showing, and the palettes the +/// host shows, shown or hidden. #[derive(Clone, Debug)] pub(crate) struct Classes { window_proto: ObjId, @@ -78,6 +94,7 @@ pub(crate) struct Classes { selection_get: ObjId, selection_set: ObjId, showing: Option, + palettes: Vec, } impl Classes { @@ -85,10 +102,21 @@ impl Classes { pub(crate) fn objects(&self) -> Vec { let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; all.extend(self.showing); + all.extend(self.palettes.iter().copied()); all } } +/// Is `kind` a window's: a dialog's or a palette's? +fn is_window(kind: &str) -> bool { + kind == "dialog" || kind == "palette" +} + +/// Does `kind` hold controls? +fn is_container(kind: &str) -> bool { + is_window(kind) || kind == "group" || kind == "panel" +} + /// Forgets the dialog that was showing when a run ended where it was. pub(crate) fn end_run(i: &mut Interp) { if let Some(c) = i.script_ui.as_mut() { @@ -254,7 +282,7 @@ fn new_element( set_open(i, o, "bounds", bounds.clone())?; } set_open(i, o, "layout", Value::Object(layout))?; - if matches!(kind, "dialog" | "group" | "panel") { + if is_container(kind) { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; let children = list(i, &[], true)?; @@ -274,16 +302,24 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult if ty.to_lowercase() != "item" { return Err(error(i, "add: a list holds only items")); } - return add_item(i, o, &arg(args, 1)); + let item = add_item(i, o, &arg(args, 1))?; + if let Some(win) = object_slot(i, o, WINDOW)? { + i.rooted(std::slice::from_ref(&item), |i| update_palette(i, win))?; + } + return Ok(item); } - if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + if !is_container(&kind) { return Err(error(i, &format!("add: a {kind} holds no controls"))); } if ty.contains('{') { @@ -401,6 +441,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult append(i, o, KIDS, "children", Value::Object(c))?; set_slot(i, win, COUNT, Value::Number(count + 1.0))?; set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?; + // The host's copy of a shown palette keeps each control's place in the list, which events + // name it by. + update_palette(i, win)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -433,6 +476,7 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; append(i, o, ITEMS, "items", Value::Object(item))?; + bump_revision(i, o)?; Ok(Value::Object(item)) }) }) @@ -530,9 +574,16 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult<()> { + let r = number_slot(i, o, REVISION)?; + set_slot(i, o, REVISION, Value::Number(r + 1.0)) +} + fn kids_of(i: &Interp, o: ObjId) -> JsResult> { match object_slot(i, o, KIDS)? { Some(a) => list_values(i, a), @@ -597,29 +648,158 @@ fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { Ok(Value::Undefined) } -fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { +/// `this` as a window, and whether it is a palette. +fn window_of(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, bool)> { match kind_of(i, this)? { - Some((o, kind)) if kind == "dialog" => Ok(o), + Some((o, kind)) if is_window(&kind) => Ok((o, kind == "palette")), _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), } } -/// `close([result])`: closes the dialog that is showing once the running handler returns. +/// `close([result])`: closes the dialog that is showing once the running handler returns, or the +/// palette at once. fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let o = dialog_of(i, &this, "close")?; + let (o, palette) = window_of(i, &this, "close")?; let result = match arg(args, 0) { Value::Undefined => 0.0, v => number_arg(i, &v, "close: the result")?, }; - if classes(i)?.showing == Some(o) { + if palette { + close_palette(i, o)?; + } else if classes(i)?.showing == Some(o) { set_slot(i, o, CLOSING, Value::Number(result))?; } Ok(Value::Undefined) } -/// `hide()`: closes the dialog that is showing with the result 0. +/// `hide()`: closes the dialog that is showing with the result 0, or hides the palette, which a +/// later `show()` shows again as it was. fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - close(i, this, &[], false) + let (o, palette) = window_of(i, &this, "hide")?; + if !palette { + return close(i, this, &[], false); + } + if let Value::Number(id) = slot(i, o, PALETTE_ID)? { + let f = host_fn(i, "paletteHide")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(Value::Undefined) +} + +fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { + if let Some(c) = i.script_ui.as_mut() { + f(&mut c.palettes); + } +} + +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its +/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + if slot(i, win, IN_CLOSE)?.truthy() { + return Ok(()); + } + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let allowed = may_close(i, win); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + if !allowed? { + return Ok(()); + } + if let Value::Number(id) = slot(i, win, PALETTE_ID)? { + set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_palettes(i, |p| p.retain(|o| *o != win)); + let f = host_fn(i, "paletteClose")?; + i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + } + Ok(()) +} + +/// Gives the host the controls of the palette `win` as they are now, when it shows the palette. +fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { + let Value::Number(id) = slot(i, win, PALETTE_ID)? else { return Ok(()) }; + let (desc, ..) = describe(i, win)?; + let f = host_fn(i, "paletteUpdate")?; + i.rooted(std::slice::from_ref(&desc), |i| i.call(&f, &Value::Undefined, &[desc.clone(), Value::Number(id)]))?; + Ok(()) +} + +/// Gives the host the controls of every palette it shows, after a handler may have changed them. +fn update_palettes(i: &mut Interp) -> JsResult<()> { + for win in classes(i)?.palettes { + update_palette(i, win)?; + } + Ok(()) +} + +/// Gives the host the controls of every palette the realm keeps, as a run left them +/// ([`crate::Realm::refresh_script_ui`]); nothing without palettes. +pub(crate) fn refresh(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_none_or(|c| c.palettes.is_empty()) { + return Ok(()); + } + update_palettes(i) +} + +/// A palette's `show()`: the host shows its description at once, then `onShow` runs, and `show()` +/// returns `undefined` without waiting. +fn show_palette(i: &mut Interp, win: ObjId) -> JsResult { + let (desc, ..) = describe(i, win)?; + let id = slot(i, win, PALETTE_ID)?; + let f = host_fn(i, "paletteShow")?; + Ok(Pause { host: f, args: vec![desc, id], keep: vec![Value::Object(win)], resume: palette_shown, failed: None }) +} + +fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its palette".into())) }; + let Value::Number(_) = id else { return Err(Abrupt::Internal("the host gave the palette no id".into())) }; + set_slot(i, win, PALETTE_ID, id)?; + if !classes(i)?.palettes.contains(&win) { + set_palettes(i, |p| p.push(win)); + } + handler(i, win, "onShow")?; + update_palette(i, win)?; + Ok(Value::Undefined) +} + +/// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the +/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and +/// gives the host every palette's controls afterward. An event for a palette that has closed does +/// nothing. +fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + let f = host_fn(i, "paletteEvent")?; + let answer = i.call(&f, &Value::Undefined, &[])?; + let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; + let mark = i.temp_roots.len(); + i.temp_roots.push(answer.clone()); + let r = (|| { + let id = slot(i, ev, "palette")?; + let palettes = classes(i)?.palettes; + let mut win = None; + for p in palettes { + if matches!((slot(i, p, PALETTE_ID)?, &id), (Value::Number(a), Value::Number(b)) if a == *b) { + win = Some(p); + } + } + let Some(win) = win else { return Ok(Value::Undefined) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + close_palette(i, win)?; + } else { + let (_, nodes, ..) = describe(i, win)?; + i.temp_roots.push(Value::Object(nodes)); + let count = list_values(i, nodes)?.len(); + if !matches!(slot(i, ev, "id")?, Value::Number(n) if n >= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + return Err(error(i, "a palette event names a control the palette no longer holds")); + } + take_event(i, win, nodes, ev, &event, None)?; + } + update_palettes(i)?; + Ok(Value::Undefined) + })(); + i.temp_roots.truncate(mark); + r } fn host_fn(i: &mut Interp, name: &str) -> JsResult { @@ -633,9 +813,13 @@ fn set_showing(i: &mut Interp, showing: Option) { } } -/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). On a +/// palette: [`show_palette`]. fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { - let win = dialog_of(i, &this, "show")?; + let (win, palette) = window_of(i, &this, "show")?; + if palette { + return show_palette(i, win); + } match classes(i)?.showing { Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), @@ -745,75 +929,123 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { } return next(i, win); } - let id = match slot(i, ev, "id")? { - Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, - _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), - }; - let nodes = list_values(i, nodes)?; - let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { - return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); - }; - let value = slot(i, ev, "value")?; - match event.as_str() { - "click" => { - if kind == "checkbox" { - let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); - i.put(c, key("value"), Value::Bool(!on), true)?; - } else if kind == "radiobutton" { - let parent = object_slot(i, c, PARENT)?; - for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { - if !same(&other, &Value::Object(c)) - && let Some((o, k)) = kind_of(i, &other)? - && k == "radiobutton" - { - i.put(o, key("value"), Value::Bool(false), true)?; - } - } - i.put(c, key("value"), Value::Bool(true), true)?; - } - if handler(i, c, "onClick")?.is_none() && kind == "button" { - let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); - if is(2) { - set_slot(i, win, CLOSING, Value::Number(1.0))?; - } else if is(3) { - set_slot(i, win, CLOSING, Value::Number(2.0))?; - } - } - } - "change" => { - match kind.as_str() { - "edittext" => { - i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; - } - "slider" => { - i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; - } - _ => { - let n = match value { - Value::Number(n) => n, - _ => -1.0, - }; - // The index is into the items the person saw. - let shown = match arg(keep, 4).as_object() { - Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), - None => Value::Undefined, - }; - if !same(&slot(i, c, ITEMS)?, &shown) { - return Err(error(i, "show: a list's items changed before the person's choice was taken")); - } - set_slot(i, c, SELECTION, Value::Number(n))?; - } - } - handler(i, c, "onChange")?; - } - _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), - } + take_event(i, win, nodes, ev, &event, Some(keep))?; next(i, win) }) } +/// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of +/// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks +/// to close it with 1 when it is the default element and 2 when it is the cancel element, which +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event { + "click" => { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + let parent = object_slot(i, c, PARENT)?; + for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { + if !same(&other, &Value::Object(c)) + && let Some((o, k)) = kind_of(i, &other)? + && k == "radiobutton" + { + i.put(o, key("value"), Value::Bool(false), true)?; + } + } + i.put(c, key("value"), Value::Bool(true), true)?; + } + if handler(i, c, "onClick")?.is_none() + && kind == "button" + && let Some(keep) = keep + { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + handler(i, c, "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + handler(i, c, "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + match keep { + // The index is into the items the person saw. + Some(keep) => { + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } + } + // A palette's list may have changed while the event waited: the host gives + // the items the person saw and the list's revision then. + None => { + let revised = match slot(i, ev, "revision")? { + Value::Number(r) => r != number_slot(i, c, REVISION)?, + _ => false, + }; + if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + return Err(error(i, "a palette's list changed before the person's choice was taken")); + } + } + } + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + Ok(()) +} + +/// Does the list `c` hold items with the texts in `seen` (an array of strings), in that order? True +/// when `seen` is not an array. +fn same_items(i: &mut Interp, c: ObjId, seen: &Value) -> JsResult { + let Some(seen) = seen.as_object() else { return Ok(true) }; + let seen = list_values(i, seen)?; + let items = items_of(i, c)?; + if seen.len() != items.len() { + return Ok(false); + } + i.rooted(&items, |i| { + for (item, want) in items.iter().zip(&seen) { + let Some(item) = item.as_object() else { return Ok(false) }; + let text = get(i, item, "text")?; + if i.to_str(&text)?.to_rust_string() != i.to_str(want)?.to_rust_string() { + return Ok(false); + } + } + Ok(true) + }) +} + fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { let s = i.to_str(v)?; let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; @@ -963,8 +1195,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; let text = text_of(i, &text_v, "a control's text")?; + // A palette is described as a dialog is; the host knows which it shows. + let shown_kind = if kind == "palette" { "dialog" } else { kind.as_str() }; let mut d: Vec<(String, Data)> = vec![ - ("kind".into(), Data::String(kind.clone())), + ("kind".into(), Data::String(shown_kind.to_string())), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), @@ -981,7 +1215,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); - if matches!(kind.as_str(), "dialog" | "group" | "panel") { + if is_container(kind) { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); let ac = get_kept(i, o, "alignChildren")?; @@ -1026,6 +1260,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { d.push(("items".into(), Data::Array(texts))); let sel = selection_index(i, o)?.filter(|n| *n < items.len()); d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + d.push(("revision".into(), Data::Number(number_slot(i, o, REVISION)?))); } _ => {} } @@ -1079,9 +1314,21 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul i.temp_roots.push(Value::Object(selection_get)); let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; i.temp_roots.push(Value::Object(selection_set)); - i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + i.script_ui = Some(Classes { + window_proto, + control_proto, + item_proto, + layout, + host, + selection_get, + selection_set, + showing: None, + palettes: Vec::new(), + }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; + let event = native(i, "__vcPaletteEvent", palette_event, 0, NativeKind::Plain, false)?; + i.define(window, key("__vcPaletteEvent"), Prop::Data { value: Value::Object(event), flags: 0 })?; method(i, window_proto, "add", add, 4)?; method(i, window_proto, "findElement", find_element, 1)?; method(i, window_proto, "close", close, 1)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7d0d8376a3..76a70d331d 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -232,7 +232,8 @@ fn a_dialog_can_be_shown_again_after_it_closed() { #[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('window')", "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('dialog { b: Button {} }')", "Window: resource specifications are not available yet; build the dialog with add()"), ("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"), @@ -373,6 +374,129 @@ 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>>; + +/// 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) -> (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 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)), + ]; + 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 { + 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())); + assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event 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 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"); + 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!(calls.borrow().iter().filter(|(n, _)| n == "paletteClose").count(), 1); + assert!(calls.borrow().contains(&("paletteClose".into(), 1.0))); +} + +#[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())); +} + +#[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 = 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()); diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..9854310ff5 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -179,7 +179,7 @@ features! { Reflection "reflection" HostOnly, ScriptuiDialog "scriptui.dialog" Dialogs, ScriptuiDrawing "scriptui.drawing" Dialogs, - ScriptuiPalette "scriptui.palette" HostOnly, + ScriptuiPalette "scriptui.palette" Dialogs, ScriptuiWindow "scriptui.window" Dialogs, SelectTool "selectTool" HostOnly, Socket "socket" HostOnly, diff --git a/crates/scriptcheck/src/lib.rs b/crates/scriptcheck/src/lib.rs index 2bd8c60fba..c0d626c998 100644 --- a/crates/scriptcheck/src/lib.rs +++ b/crates/scriptcheck/src/lib.rs @@ -119,8 +119,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, E4X, actions). + /// Features only the reference app has (messages to other apps, network connections, native + /// code, E4X, actions). HostOnly, } diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index b771cc6417..8b216bcc48 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1369,6 +1369,12 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { assert_eq!(notify(five, &Limits::default()).0, Vec::::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"); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bba6a5d83d..bd2bba2159 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -368,6 +368,11 @@ impl VectorcraftApp { crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::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. + if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint(); + } if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() @@ -638,6 +643,7 @@ impl VectorcraftApp { egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.pasteboard)).show(ui, |ui| panel_docking::show(self, ui)); panels::learn::locate::tidy(self, &ctx); crate::doc_windows::show(self, &ctx); + crate::script_palettes::show(self, &ctx); dialogs::show(self, &ctx); updates_ui::show(self, &ctx); export_progress::show(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 158a86ea5b..9aea178b9a 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -215,7 +215,13 @@ pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { /// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place from `origin`. → the /// event it gives. -fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt): (usize, &UiNode, &str), default: bool) -> Option { +pub(crate) fn control( + ui: &mut egui::Ui, + d: &mut Dialog, + origin: egui::Pos2, + (i, n, prompt): (usize, &UiNode, &str), + default: bool, +) -> Option { let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); let t = Tokens::get(ui.ctx()); let mut event = None; diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 9d442848ce..51a518f798 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6582,6 +6582,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index ee8b68af7d..9457178baf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8986,6 +8986,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index cc03e6ef1b..1ef0d2169d 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -225,6 +225,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index e92726501f..935a135c4b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8426,6 +8426,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 12d3aba3c5..aa30a34709 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2779,6 +2779,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index c404d6ed6e..5cc8d86fdf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5054,6 +5054,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 2ae421c004..1205c1dc9d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5295,6 +5295,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index aa2a24c90d..dbdca9ca76 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8853,6 +8853,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 5bdc231564..8c5e1f5602 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7728,6 +7728,7 @@ 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 `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` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af96effe62..6f7ce5a4ca 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8857,6 +8857,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 87d73912db..25e340bec0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -133,6 +133,7 @@ @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 `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` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5aab7c3e3d..ea73cf2b91 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8467,6 +8467,7 @@ 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 `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} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index ef0740a8bb..0b73565e9a 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7293,6 +7293,7 @@ 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 `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` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e7223c60c8..541d871302 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -176,6 +176,7 @@ @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 `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` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e40e7055a2..07bde95166 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8625,6 +8625,7 @@ 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 `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`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index d52992f4a9..9287dd44e3 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6493,6 +6493,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 1a2148f0e1..fd7342da72 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8670,6 +8670,7 @@ 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 `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} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 82cdb0a2b2..4aa2697468 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9039,6 +9039,7 @@ 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 `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} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 6f351f1d76..ac74d5747a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5076,6 +5076,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 532e1ade50..dc74ea16ce 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4951,6 +4951,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index daba147a6d..955a2662d8 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5760,6 +5760,39 @@ fn f(p: &Value) -> Result<()> { assert_eq!(source_messages(code, &engine, &consts), ["the name is too long", "`path` is empty"]); } +/// The status a ScriptUI palette's click shows when the line of waiting events is full is +/// translated in every language that translates every message, with the count kept. +#[test] +fn script_palette_line_full_is_translated() { + use serde_json::json; + use vectorcraft_engine::script::UiEvent; + let template = "{MAX_WAITING} script palette events already wait; this one was not kept"; + assert!(message_literals().contains(template)); + let mut s = vectorcraft_engine::Session::new(); + let source = "#targetengine tools\nvar p = new Window('palette'); for (var i = 0; i < 70; i++) p.add('button', undefined, 'B' + i); p.show();"; + s.execute("script.run", &json!({"source": source})).unwrap(); + let id = s.script_palettes()[0].id; + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": "confirm('Go?');"})).unwrap()["running"], true); + while s.script_dialog().is_none() { + assert!(s.script_pump().is_none(), "the run waits at its confirm"); + } + let mut full = None; + for c in 1..=70 { + if let Err(e) = s.script_palette_event(id, UiEvent::Click(c)) { + full = Some(e); + break; + } + } + let full = full.expect("the line filled"); + assert_eq!(full, template.replace("{MAX_WAITING}", "64")); + for code in COMPLETE_MESSAGES { + let shown = message(Lang::from_code(code).expect("registered"), &full); + assert_ne!(shown, full, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// `script.run`'s refusals of `answers`, the list's own, an answer's at its index and the refusal /// of `answers` in the app, are translated in every language that translates every message, with /// the index, the counts and the code names kept. The command's error stays in English. diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 22568734be..109ef0345a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7669,6 +7669,7 @@ 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 `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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1c44123d26..20e6a222ab 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8626,6 +8626,7 @@ 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 `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} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 2758865931..173c74895c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5575,6 +5575,7 @@ 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 `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` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index dac4499a58..129b2fff68 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8676,6 +8676,7 @@ 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 `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} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index bf6ee14a81..b11084d879 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8621,6 +8621,7 @@ 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 `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` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a50527cede..5bbfae206c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -70,6 +70,7 @@ pub mod print; pub mod recovery; pub mod render_worker; pub mod screen_color; +pub mod script_palettes; pub mod script_runs; pub mod scripts_menu; mod scrub; diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs new file mode 100644 index 0000000000..125adf0365 --- /dev/null +++ b/crates/ui-egui/src/script_palettes.rs @@ -0,0 +1,93 @@ +//! The ScriptUI palettes a script shows with `new Window("palette")` in a named engine +//! ([`vectorcraft_engine::script::palettes`]): each shown palette is a window beside the documents +//! that stays open after the run, with the controls the engine laid out. A click, a change or the +//! window's 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`]); 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 stays in its field with the error in the status bar. + +use serde_json::json; +use vectorcraft_engine::script::{ScriptPalette, UiEvent}; + +use crate::VectorcraftApp; +use crate::dialogs::script_window; +use crate::state::Dialog; + +/// The largest part of a palette's content shown at once; a larger palette scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +/// Where the text typed in a palette's fields is kept between frames. +fn drafts_id(id: u64) -> egui::Id { + egui::Id::unique(("script-palette-drafts", id)) +} + +/// Draws each shown palette, and puts the events the person gives in line. +pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { + let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); + for p in shown { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut events = Vec::new(); + let mut open = true; + let title = p.dialog.title(); + let title = if title.is_empty() { tl!("Script Alert").to_string() } else { vectorcraft_engine::script::dialogs::shown_text(title, false) }; + let (width, height) = p.dialog.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::Window::new(title).id(egui::Id::unique(("script-palette", p.id))).open(&mut open).collapsible(false).resizable(false).show(ctx, |ui| { + egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { + let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + for (i, n) in p.dialog.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = script_window::control(ui, &mut drafts, area.min, (i, n, script_window::prompt_of(&p.dialog, i)), false) + { + events.push(e); + } + } + }); + }); + if !open { + events.push(UiEvent::Close); + } + drafted(app, &p, &mut drafts, &mut events); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + give(app, ctx, p.id, events); + } +} + +/// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in +/// `events`. A text the script would refuse stays in its field with its error in the status bar, +/// and a click or a close waits for the person to fix it. +pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut Dialog, events: &mut Vec) { + if let Some(e) = script_window::keep_refused_texts(&p.dialog, drafts, events) { + app.status(e); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_) | UiEvent::Close)) + && let Err(e) = script_window::commit_drafts(&p.dialog, drafts, events) + { + events.retain(|e| !matches!(e, UiEvent::Click(_) | UiEvent::Close)); + app.status(e); + } +} + +/// Puts the events the person gave the palette `id` in line, or shows why one was refused. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { + for e in events { + match app.session.script_palette_event(id, e) { + // The next frame starts its run. + Ok(_) => ctx.request_repaint(), + Err(e) => app.status(e), + } + } +} + +/// Starts the run of the oldest waiting palette event when no run is going. → whether one started. +pub(crate) fn start_next(app: &mut VectorcraftApp) -> bool { + match app.session.script_palette_start() { + None => false, + Some(Ok(_)) => true, + Some(Err(e)) => { + crate::script_runs::failed(app, e.to_string()); + false + } + } +} diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 27e74d820e..c40c4a2f6e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -2,7 +2,8 @@ //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! 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. +//! waits for the person's answer. With no run going, the oldest event a ScriptUI palette waits +//! with starts its run ([`crate::script_palettes`]). use serde_json::json; @@ -13,7 +14,8 @@ use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. pub fn poll(app: &mut VectorcraftApp) { script_run::drain(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); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index ac934f6d18..2c79788097 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -42,6 +42,7 @@ mod screenmode; mod screenshots; mod script_check; mod script_dialogs; +mod script_palettes; mod script_run; mod script_window; mod scripts_menu; diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs new file mode 100644 index 0000000000..113c501162 --- /dev/null +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -0,0 +1,109 @@ +//! A script's ScriptUI palette in the app: it stays open after the run, 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::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_window; +use crate::state::Dialog; +use crate::{VectorcraftApp, menus, script_palettes, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +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"); +} + +/// One headless frame in which `f` runs. → whether the frame asked for the next one at once. +fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) +} + +#[test] +fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + for _ in 0..3 { + frame(&ctx, |_| {}); + } + assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); + assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "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 a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": "vc.log(confirm('Go?'));", "name": "d.js"})).unwrap().unwrap(); + 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"); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames while the run waits for its answer"); + assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); +} + +#[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();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let p = app.session.script_palettes()[0].clone(); + let long = "x".repeat(16 * 1024 + 1); + let mut drafts = Dialog::new(script_window::KIND, json!({})); + drafts.fields.insert("text1".into(), json!(long)); + let mut events = vec![UiEvent::Change(1, UiValue::Text(long.clone())), UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert!(events.is_empty(), "neither the long text nor the click is given: {events:?}"); + assert_eq!(drafts.fields.get("text1"), Some(&json!(long)), "the refused text stays in its field"); + drafts.fields.insert("text1".into(), json!("fine")); + let mut events = vec![UiEvent::Click(2)]; + script_palettes::drafted(&mut app, &p, &mut drafts, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("fine".into())), UiEvent::Click(2)]); + assert!(!drafts.fields.contains_key("text1"), "the text is given once"); +} diff --git a/docs/mcp.md b/docs/mcp.md index 951edebb05..36f0993663 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2547,9 +2547,9 @@ 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 and directives, such as `$`, `alert`, `UnitValue`, `#target` and `#targetengine`), `dom` (the reference app's - document model), `files`, `menuCommands`, `dialogs`, and `hostOnly` (features only the reference app has: - palettes, BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, reflection, actions - and `selectTool`). + document model), `files`, `menuCommands`, `dialogs` (dialogs and palettes), and `hostOnly` (features only the + reference app has: BridgeTalk, sockets, native code, XMP, the XML object and E4X, operator overloading, + reflection, actions and `selectTool`). - `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`. @@ -2902,8 +2902,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`) or a - resource string 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` and a resource string throw an `Error` that says + it is not available yet. - `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, @@ -2967,6 +2968,45 @@ 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. + `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. + A handler's run reads and writes the files the person allowed the script that first showed the palette. +- 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. While an event waits, a + newer click on the same control, change of the same control or close of the same palette takes its place, + with the newer value. A list's change ends its run with an error when a script added or removed the list's + items after the person chose, even if the list again holds the same texts. 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 a click or close waits + until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and + leaves the palette open. 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 and returns the report of this one, +or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. + +```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: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 939047032e..c8f4bb0095 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,7 +1066,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, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings 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, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Other control types and resource strings 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")` in a script with `#targetengine` shows a palette that stays open beside the documents 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; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; 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`). From 9beb3bb5f9c579eee1ba86e45e5dfa5ff9207090 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 11:57:39 -0800 Subject: [PATCH 004/334] Scripts: a ScriptUI dialog shown in place of another gives its first field the focus A dialog a script shows right after closing the open one now counts as newly opened: the control used in the first dialog gives up the keyboard focus, and the first editable field of the new dialog takes it. ScriptUI edit fields now take the first-field focus like the app's other dialogs. --- crates/ui-egui/src/dialogs.rs | 23 +++++++--- crates/ui-egui/src/dialogs/script_window.rs | 12 +++++- crates/ui-egui/src/tests/script_window.rs | 47 +++++++++++++++++++++ 3 files changed, 76 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6b59f7bd88..20f57ad04f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -929,7 +929,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { revolve_gizmo::clear(ctx); app.ui.dialog_file = None; ctx.data_mut(|m| { - m.remove::(shown_id); + m.remove::<(String, Option)>(shown_id); m.remove::(focus_id); }); return; @@ -937,13 +937,26 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !revolve_gizmo::active(&d) { revolve_gizmo::clear(ctx); } - let focus_first = ctx.data_mut(|m| { - if m.get_temp::(shown_id).as_deref() != Some(d.kind.as_str()) { - m.insert_temp(shown_id, d.kind.clone()); + // A ScriptUI dialog that a script showed in place of the one open is a new dialog too. + let shown_as = (d.kind.clone(), script_window::shown_of(&d)); + let (focus_first, replaced) = ctx.data_mut(|m| { + let before = m.get_temp::<(String, Option)>(shown_id); + let replaced = before.as_ref().is_some_and(|b| b.0 == shown_as.0 && *b != shown_as); + if before.as_ref() != Some(&shown_as) { + m.insert_temp(shown_id, shown_as); m.insert_temp(focus_id, true); } - m.get_temp::(focus_id).unwrap_or(false) + (m.get_temp::(focus_id).unwrap_or(false), replaced) }); + // It draws in the same window with the same control ids, so the control used in the dialog + // before it gives up the keyboard focus. + if replaced { + ctx.memory_mut(|m| { + if let Some(id) = m.focused() { + m.surrender_focus(id); + } + }); + } // Not in the frame of a click (the one on the menu item that opened it): egui takes the focus // from a field the click missed, so the field takes it a frame later (#1367). let clicked = ctx.input(|i| i.pointer.any_click()); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 9aea178b9a..a1ea69f620 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -54,6 +54,11 @@ pub(crate) fn is_open_for(d: &Dialog, w: &ScriptUiDialog) -> bool { d.kind == KIND && d.fields.get(SHOWN_KEY).and_then(Value::as_u64) == Some(w.shown) } +/// Which `show()` of the run `d` is open for, when it is a ScriptUI dialog. +pub(crate) fn shown_of(d: &Dialog) -> Option { + if d.kind == KIND { d.fields.get(SHOWN_KEY).and_then(Value::as_u64) } else { None } +} + fn heading(d: &Dialog) -> String { let title = d.str("title"); if title.is_empty() { tl!("Script Alert").into() } else { vectorcraft_engine::script::dialogs::shown_text(&title, false) } @@ -357,8 +362,13 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (usize, &UiNode, &str)) -> Option { let key = draft_key(i); let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); + let id = ui.make_persistent_id("edit"); + // The first field that can be typed in takes the keyboard focus as the dialog opens. + if !n.readonly { + widgets::take_dialog_focus(ui, id, &text); + } let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; - let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); + let r = ui.put(rect, field.id(id).interactive(!n.readonly).desired_width(rect.width())); name_for_screen_readers(ui, &r, n, prompt); if r.changed() { d.fields.insert(key.clone(), json!(text)); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 2e2cd186ca..5a0b7aeeac 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -210,6 +210,53 @@ fn a_second_dialog_replaces_the_first() { assert_eq!(log(&app), json!([[1, "y"]])); } +/// Draws one frame of the dialog layer for screen readers. → The role of the control with the +/// keyboard focus. +fn focused_role(app: &mut VectorcraftApp) -> Option { + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + let update = out.platform_output.accesskit_update?; + update.nodes.iter().find(|(id, _)| *id == update.focus).map(|(_, n)| n.role()) +} + +#[test] +fn a_dialog_shown_in_place_of_another_gives_its_first_field_the_focus() { + use egui::accesskit::Role; + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('statictext', undefined, 'Name'); b.add('button', undefined, 'Back'); \ + b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log(b.show());", + ); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the first dialog's field has the focus, not {role:?}"); + let mut on_button = false; + for _ in 0..4 { + frame(&mut app, vec![key(egui::Key::Tab)]); + on_button = focused_role(&mut app) == Some(Role::Button); + if on_button { + break; + } + } + assert!(on_button, "Tab puts the focus on the first dialog's button"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "B"); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let role = focused_role(&mut app); + assert!(matches!(role, Some(Role::TextInput | Role::MultilineTextInput)), "the second dialog's field has the focus, not {role:?}"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn a_dialog_function_after_show_opens_its_own_dialog() { let mut app = app(); From d814cb77f3cf3431b6b8ac50a34d927459777a41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 13:09:54 -0800 Subject: [PATCH 005/334] Scripts: palette events and typed texts stay with their control when a run adds controls A click or change that waits for a palette's run now keeps where its control sits in the palette, and a text typed in a palette's field keeps where its field sits, so both reach the same control after a run adds controls before it. A waiting event whose control is gone is dropped. ScriptUiDialog::place_of and control_at move to the engine so the palette queue and the dialog's queued events use the same rule. --- crates/engine/src/script/palettes.rs | 45 ++++++++++++++------ crates/engine/src/script/scriptui.rs | 27 ++++++++++++ crates/engine/src/tests/script_palettes.rs | 21 ++++++++++ crates/ui-egui/src/dialogs/script_window.rs | 46 +++++---------------- crates/ui-egui/src/script_palettes.rs | 18 +++++++- crates/ui-egui/src/tests/script_palettes.rs | 23 +++++++++++ docs/mcp.md | 7 ++-- 7 files changed, 133 insertions(+), 54 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index d6ff578f29..5da1b6e888 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -61,6 +61,10 @@ pub enum Waiting { pub(crate) struct Queued { pub(crate) palette: u64, pub(crate) event: UiEvent, + /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), + /// by which the event finds its control again when a run adds controls before it; empty for a + /// close. + place: Vec, /// 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. @@ -80,12 +84,21 @@ pub(crate) struct Palettes { pub(crate) starting: Option, } -/// Do `a` and `b` share one place in line: a click on the same control, a change of it, or a close? -fn same_place(a: &UiEvent, b: &UiEvent) -> bool { - match (a, b) { - (UiEvent::Click(x), UiEvent::Click(y)) | (UiEvent::Change(x, _), UiEvent::Change(y, _)) => x == y, - (UiEvent::Close, UiEvent::Close) => true, - _ => false, +/// Does `event`, for the control at `place`, 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, place: &[usize]) -> bool { + let same_kind = matches!( + (&q.event, event), + (UiEvent::Click(_), UiEvent::Click(_)) | (UiEvent::Change(..), UiEvent::Change(..)) | (UiEvent::Close, UiEvent::Close) + ); + same_kind && q.place == place +} + +/// 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, } } @@ -151,12 +164,13 @@ impl Palettes { if !p.visible { return Err(format!("the script palette {id} is hidden")); } - let event = scriptui::check_event(&p.dialog, event)?; + 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, }; - if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(&q.event, &event)) { + let place = control_of(&mut event).map_or_else(Vec::new, |c| p.dialog.place_of(*c)); + if let Some(slot) = self.waiting.iter_mut().find(|q| q.palette == id && same_place(q, &event, &place)) { slot.event = event; slot.list = list; return Ok(Waiting::Merged); @@ -164,16 +178,21 @@ impl Palettes { 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, list, grants: None }); + self.waiting.push_back(Queued { palette: id, event, place, list, grants: None }); Ok(Waiting::Added) } - /// The oldest waiting event whose palette is still shown, and that palette. + /// The oldest waiting event whose palette is still shown, given to the control at its place in + /// the palette as the runs since left it, and that palette. An event whose control the palette + /// no longer has is dropped. fn next(&mut self) -> Option<(ScriptPalette, Queued)> { - while let Some(q) = self.waiting.pop_front() { - if let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) { - return Some((p.clone(), q)); + while let Some(mut q) = self.waiting.pop_front() { + let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; + if let Some(c) = control_of(&mut q.event) { + let Some(at) = p.dialog.control_at(&q.place) else { continue }; + *c = at; } + return Some((p.clone(), q)); } None } diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 8ca7154e47..fd3bda32a4 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -201,6 +201,33 @@ impl ScriptUiDialog { }; by(true).or_else(|| by(false)) } + + /// Where control `i` sits: its position among its container's controls, after its container's + /// own position, and so on up to the dialog. `add` puts a new control after the others in its + /// container, so adding controls leaves the place of every other one as it was, while its index + /// in [`Self::nodes`] can move. Empty for the dialog and for an index it does not have. + pub fn place_of(&self, mut i: usize) -> Vec { + let mut place = Vec::new(); + while i > 0 { + let Some(n) = self.nodes.get(i) else { return Vec::new() }; + place.push(self.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); + if n.parent >= i { + return Vec::new(); + } + i = n.parent; + } + place.reverse(); + place + } + + /// The index of the control at `place` ([`Self::place_of`]), if the dialog has one there. + pub fn control_at(&self, place: &[usize]) -> Option { + let mut at = 0; + for &k in place { + at = self.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; + } + (at > 0).then_some(at) + } } /// A value a control takes in a change. diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 006f022627..9c4b7be294 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,27 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine places\nvar p = new Window('palette'); var g = p.add('group'); g.add('button', undefined, 'First'); \ + var last = p.add('button', undefined, 'Last'); last.onClick = function () { vc.log('last'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(3)); + let added = "#targetengine places\nconfirm('Go?'); g.add('button', undefined, 'Added').onClick = function () { vc.log('added'); };"; + assert_eq!(run(&mut s, added).unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(3)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert_eq!(s.script_palettes()[0].dialog.find("Last"), Some(4), "the added button comes before Last in the list of controls"); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2662e30d87..2c8f35365e 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -143,7 +143,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if let Value::Object(mut fields) = next { // The control the event was given to, found again in the dialog as the handlers that ran // since left it. - let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); + let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,36 +152,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } -/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). +/// The field of a queued event that holds where its control sits in the dialog +/// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; -/// Where control `i` sits in the dialog `w`: its position among its container's controls, after -/// its container's own position, and so on up to the dialog. `add` puts a new control after the -/// others in its container, so a handler that adds controls leaves the place of every other one -/// as it was, while its index in the dialog's list of elements can move. -fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { - let mut place = Vec::new(); - while i > 0 { - let Some(n) = w.nodes.get(i) else { return Vec::new() }; - place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); - if n.parent >= i { - return Vec::new(); - } - i = n.parent; - } - place.reverse(); - place -} - -/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. -fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { - let mut at = 0; - for &k in place { - at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; - } - (at > 0).then_some(at) -} - /// The field that holds the events the person gave in one frame that the script has not had yet; /// the script takes one event each time it waits. const QUEUE_KEY: &str = "queued"; @@ -245,14 +219,14 @@ fn draft_key(i: usize) -> String { format!("text{i}") } -/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) -/// in the dialog the text was typed in. +/// The field that holds, for each text typed in an edit field, where the field sat +/// ([`ScriptUiDialog::place_of`]) in the dialog the text was typed in. const DRAFT_PLACES_KEY: &str = "draftPlaces"; /// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. -fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { let places: serde_json::Map = - (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(w.place_of(i)))).collect(); if places.is_empty() { d.fields.remove(DRAFT_PLACES_KEY); } else { @@ -263,12 +237,12 @@ fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { /// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the /// dialog `w`, which moves when a handler adds controls before the field. A text whose field the /// dialog no longer has is dropped. -fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { +pub(crate) fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; let mut moved = Vec::new(); for (key, place) in places { let Some(text) = d.fields.remove(&key) else { continue }; - let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + let at = serde_json::from_value::>(place).ok().and_then(|p| w.control_at(&p)); if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { moved.push((draft_key(i), text)); } @@ -466,7 +440,7 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { }; let mut fields = json!({"event": name, "control": control, "value": value}); if let Some(i) = control { - fields[PLACE_KEY] = json!(place_of(w, i)); + fields[PLACE_KEY] = json!(w.place_of(i)); } fields } diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 125adf0365..ec2e8773dd 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -26,7 +26,7 @@ fn drafts_id(id: u64) -> egui::Id { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let shown: Vec = app.session.script_palettes().iter().filter(|p| p.visible).cloned().collect(); for p in shown { - let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + let mut drafts = drafts(ctx, &p); let mut events = Vec::new(); let mut open = true; let title = p.dialog.title(); @@ -49,11 +49,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); - ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); + keep_drafts(ctx, &p, drafts); give(app, ctx, p.id, events); } } +/// The text typed in palette `p`'s fields, each under the index its field has in `p` now, which +/// moves when a run adds controls before the field. +pub(crate) fn drafts(ctx: &egui::Context, p: &ScriptPalette) -> Dialog { + let mut drafts = ctx.data(|m| m.get_temp::(drafts_id(p.id))).unwrap_or_else(|| Dialog::new(script_window::KIND, json!({}))); + script_window::move_drafts(&p.dialog, &mut drafts); + drafts +} + +/// Keeps the text typed in palette `p`'s fields for the next frame, with where each field sits. +pub(crate) fn keep_drafts(ctx: &egui::Context, p: &ScriptPalette, mut drafts: Dialog) { + script_window::note_draft_places(&p.dialog, &mut drafts); + ctx.data_mut(|m| m.insert_temp(drafts_id(p.id), drafts)); +} + /// Puts the text still typed in palette `p`'s fields (`drafts`) before a click or a close in /// `events`. A text the script would refuse stays in its field with its error in the status bar, /// and a click or a close waits for the person to fix it. diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 113c501162..56cd162316 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,29 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[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();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let before = app.session.script_palettes()[0].clone(); + assert_eq!(before.dialog.nodes[3].kind, vectorcraft_engine::script::UiKind::EditText); + let ctx = egui::Context::default(); + let mut drafts = script_palettes::drafts(&ctx, &before); + drafts.fields.insert("text3".into(), json!("typed")); + script_palettes::keep_drafts(&ctx, &before, drafts); + let added = "#targetengine places\ng.add('button', undefined, 'Added');"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": added, "name": "a.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let after = app.session.script_palettes()[0].clone(); + assert_eq!(after.dialog.nodes[4].kind, vectorcraft_engine::script::UiKind::EditText, "the added button comes before the field"); + let drafts = script_palettes::drafts(&ctx, &after); + assert_eq!(drafts.fields.get("text4"), Some(&json!("typed")), "{:?}", drafts.fields); + assert!(!drafts.fields.contains_key("text3")); +} + #[test] fn a_typed_text_the_script_refuses_keeps_the_palette_click_out_of_line() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 1fd0e6d865..eee919e83c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2988,9 +2988,10 @@ the same controls, handlers and limits: 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. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, - with the newer value. A list's change ends its run with an error when a script added or removed the list's - items after the person chose, even if the list again holds the same texts. 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 a click or close waits + with the newer value. 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 is dropped. A list's change ends its run + with an error when a script added or removed the list's items after the person chose, even if the list again + holds the same texts. 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 a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and leaves the palette open. 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. From f19e114c40227c04e6b8e8a959d852f38ef45d08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:32:54 -0800 Subject: [PATCH 006/334] Scripts: a waiting palette event a handler made its control refuse is dropped A click or change that waits for a palette's run is checked against the palette's controls again before its run starts. When an earlier handler disabled or hid the control, the event is dropped. A list's change whose list a run changed since still ends its run with the error that says so, unless the list can no longer take a change. --- crates/engine/src/script/palettes.rs | 20 ++++++++- crates/engine/src/tests/script_palettes.rs | 48 ++++++++++++++++++++++ docs/mcp.md | 3 +- 3 files changed, 69 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 5da1b6e888..6fdd49b45b 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -184,7 +184,8 @@ impl Palettes { /// The oldest waiting event whose palette is still shown, given to the control at its place in /// the palette as the runs since left it, and that palette. An event whose control the palette - /// no longer has is dropped. + /// 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(mut q) = self.waiting.pop_front() { let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; @@ -192,6 +193,23 @@ impl Palettes { let Some(at) = p.dialog.control_at(&q.place) else { continue }; *c = at; } + // 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 { + if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { + continue; + } + } else { + let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; + q.event = event; + } return Some((p.clone(), q)); } None diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 9c4b7be294..7078442ac2 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -153,6 +153,32 @@ fn a_list_change_that_waited_while_the_list_changed_ends_its_run() { assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["b"])); } +#[test] +fn a_list_change_for_an_item_a_run_removed_since_ends_its_run() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine shrink\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.removeAll(); l.add('item', 'a');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(1)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the change starts its run").is_ok()); + let e = pump(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("a palette's list changed before the person's choice was taken"), "{e}"); + assert_eq!(run(&mut s, "#targetengine shrink\nconfirm('Go?'); l.add('item', 'c'); l.enabled = false;").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Change(1, crate::script::UiValue::Index(Some(0)))), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().is_none(), "a change of a list a run changed and disabled since is dropped"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button() { let mut s = one_doc(); @@ -174,6 +200,28 @@ fn a_click_that_waited_while_a_run_added_a_control_before_it_reaches_its_button( assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["last"])); } +#[test] +fn a_waiting_click_on_a_button_a_handler_disabled_is_dropped() { + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine switches\nvar p = new Window('palette'); var off = p.add('button', undefined, 'Off'); \ + var go = p.add('button', undefined, 'Go'); off.onClick = function () { go.enabled = false; vc.log('off'); }; \ + go.onClick = function () { vc.log('go'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(run(&mut s, "confirm('Go?');").unwrap()["running"], true); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_answer(DialogAnswer::Confirm(true))); + pump(&mut s).unwrap().unwrap(); + assert!(s.script_palette_start().expect("the first click starts its run").is_ok()); + assert_eq!(pump(&mut s).unwrap().unwrap()["log"], json!(["off"])); + assert!(s.script_palette_start().is_none(), "the click on the button the handler disabled does not run"); + assert_eq!(s.script_palette_events_waiting(), 0); +} + #[test] fn a_palette_click_during_another_run_runs_after_it() { let mut s = one_doc(); diff --git a/docs/mcp.md b/docs/mcp.md index eee919e83c..2bc012fe73 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2989,7 +2989,8 @@ the same controls, handlers and limits: goes on, the event waits and runs after it; events run one at a time, oldest first. While an event waits, a newer click on the same control, change of the same control or close of the same palette takes its place, with the newer value. 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 is dropped. A list's change ends its run + run adds controls before it. A waiting event whose control is gone, or that its control can no longer take + because a handler disabled or hid it, is dropped. A list's change ends its run with an error when a script added or removed the list's items after the person chose, even if the list again holds the same texts. 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 a click or close waits until it is fixed. An error in a handler ends that run like any failed run, puts the documents back, and From 9cbbb23e01e240dbec9b7801f671a529f3b95150 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 15:58:52 -0800 Subject: [PATCH 007/334] Scripts: a palette event waiting for an open undo group asks for no frames While an undo group is open, a palette event's run cannot start. The app asked for a new frame every frame while the event waited, so it never went idle. It now asks for the next frame at once only when the run can start, and otherwise looks again four times a second. --- crates/engine/src/script/palettes.rs | 10 +++++++ crates/ui-egui/src/app.rs | 7 +++-- crates/ui-egui/src/tests/script_palettes.rs | 31 +++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 6fdd49b45b..1336a6a7f3 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -329,6 +329,16 @@ impl Session { self.script_palettes.waiting.len() } + /// 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. A drag in + /// progress 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.explicit_undo_group.is_none() + && self.docs.iter().all(|d| d.undo_group.is_none()) + } + /// 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. diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index bd2bba2159..b52abc1a7a 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -369,9 +369,12 @@ impl VectorcraftApp { crate::scripts_menu::poll(self, ctx); crate::dialogs::proof_setup::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. - if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + // 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 to end looks again four times a second. + if self.session.script_palette_can_start() { ctx.request_repaint(); + } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { + ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 56cd162316..877548d602 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -86,6 +86,37 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { assert_eq!(app.session.script_palette_events_waiting(), 1, "the click still waits"); } +#[test] +fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() { + let mut app = app(); + let source = "#targetengine tools\nvar p = new Window('palette', 'Tools'); var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { vc.log('clicked'); }; p.show();"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + app.run("edit.undoGroup.begin", json!({})).unwrap(); + let ctx = egui::Context::default(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + assert_eq!(app.session.script_palette_events_waiting(), 1); + let mut asks = true; + for _ in 0..5 { + app.begin_host_iteration(); + asks = frame(&ctx, |ui| app.tick(ui.ctx())); + if !asks { + break; + } + } + assert!(!asks, "the waiting click asks for no frames 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(); + app.begin_host_iteration(); + frame(&ctx, |ui| app.tick(ui.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"])); + assert_eq!(app.session.script_palette_events_waiting(), 0); +} + #[test] fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { let mut app = app(); From ab15fbb0d1bd1df64e3b819f4025e711f4b52983 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 17:32:54 -0800 Subject: [PATCH 008/334] Scripts: palette events keep their errors, and palettes keep visible in step - script.palette.event takes a whole float such as 1.0 as a list's item index, as a window answer does. - With nobody to ask, an event given while an undo group is open is refused with the undo-group error and is not kept. An event whose run cannot begin, for example because a recovery copy cannot be saved, ends the call with its error, and the events after it keep waiting. - A handler's error keeps its file, line and column when a palette getter also throws in the refresh after the run. - A palette's controls reach the host once, after the handler's run ends, so a getter is read once for a run that completes. - The refresh roots its copy of the palette list while getters run. - hide() sets a palette's visible to false, and show() sets it to true once the host shows it. - A close() inside a modal dialog's onClose does nothing, as for a palette; a later close runs onClose again. - A palette list change reads the list's revision after its item texts, whose getters may replace the items. - Bounds given as x, y, width and height keep their right and bottom edges finite. - A palette event that waits for an open undo group asks for no frames; the frame that ends the group asks for the next one. - A list choice queued in a ScriptUI dialog carries the list's items and revision, and is not given when a handler changed the list since. The status message has a row in every complete catalog. - docs/mcp.md: with nobody to ask, the undo-group refusal and the event whose run cannot begin; a handler reads the files allowed with Always. --- crates/engine/src/cmd/scripts.rs | 7 +- crates/engine/src/script/mod.rs | 7 +- crates/engine/src/script/palettes.rs | 24 ++++--- crates/engine/src/tests/script_palettes.rs | 75 +++++++++++++++++++++ crates/js/src/realm.rs | 12 ++++ crates/js/src/scriptui.rs | 49 +++++++++----- crates/js/src/scriptui_tests.rs | 72 +++++++++++++++++++- crates/ui-egui/src/app.rs | 9 ++- crates/ui-egui/src/dialogs/script_window.rs | 29 ++++++++ crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/tests/script_palettes.rs | 16 +++-- crates/ui-egui/src/tests/script_window.rs | 26 +++++++ docs/mcp.md | 7 +- 37 files changed, 316 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 831b56c586..349b46b28f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), @@ -281,6 +281,11 @@ fn palette_event(s: &mut Session, p: &Value) -> Result { let Some(event) = p.get("event").and_then(Value::as_str) else { return Err(bad(C, "`event` must be click, change or close")) }; let Some(palette) = s.script_palettes().iter().find(|q| q.id == id) else { return Err(bad(C, format!("there is no script palette {id}"))) }; let event = script::palettes::parse_event(&palette.dialog, event, p.get("control"), p.get("value")).map_err(|e| bad(C, e))?; + // With nobody to ask, the event runs now or not at all: it is not kept for after an open undo + // group, which a run cannot start in. + if !s.script_frames && s.undo_group_open() { + return Err(EngineError::Other(script::OPEN_EDIT.to_string())); + } let waiting = s.script_palette_event(id, event).map_err(|e| bad(C, e))?; if s.script_frames { return Ok(json!({"waiting": true, "merged": waiting == script::Waiting::Merged, "waitingEvents": s.script_palette_events_waiting()})); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index de8f299cec..ef204e4582 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2345,7 +2345,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"; @@ -2515,9 +2515,10 @@ fn run_slice(s: &mut Session, job: &mut Job) -> std::result::Result realm.refresh_script_ui().map(|()| 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. + // 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 => { - let _ = realm.refresh_script_ui(); + realm.refresh_script_ui_after_error(); Err(e) } r => r, diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 1336a6a7f3..e7de94a1bf 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -43,7 +43,8 @@ pub struct ScriptPalette { 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. + /// 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, } @@ -253,8 +254,8 @@ pub(crate) fn parse_event( ("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 v.as_u64() { - Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + ("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))), @@ -333,10 +334,12 @@ impl Session { /// waits, no run is going, and no undo group is open, which a run cannot start in. A drag in /// progress 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.explicit_undo_group.is_none() - && self.docs.iter().all(|d| d.undo_group.is_none()) + !self.script_palettes.waiting.is_empty() && !self.script_running() && !self.undo_group_open() + } + + /// 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 @@ -383,11 +386,14 @@ impl Session { } /// `script.palette.event` with no run going and nobody to ask: runs the waiting events in turn, - /// the one just given last. → that one's report. + /// the one just given last. → that one's report. An event whose run could not begin, for + /// example because the recovery copies could not be saved, ends this with its error, and the + /// events after it keep waiting. pub(crate) fn script_palette_run_waiting(&mut self) -> Result { let mut last = Err(EngineError::Other("no script palette event waits".into())); while let Some(started) = self.script_palette_start() { - last = started.and_then(|_| self.script_run_to_end()); + started?; + last = self.script_run_to_end(); } last } diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index 7078442ac2..c432700fe6 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -262,6 +262,81 @@ fn double_clicks_while_queued_run_once() { assert_eq!(logs, [json!(["click 1"]), json!(["change ab"])]); } +#[test] +fn a_list_change_takes_a_whole_float_as_its_item_index() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine floats\nvar p = new Window('palette'); var l = p.add('listbox', undefined, ['a', 'b']); \ + l.onChange = function () { vc.log(String(l.selection)); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let picked = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": 1.0})).unwrap(); + assert_eq!(picked["log"], json!(["b"])); + for value in [json!(0.5), json!(-1)] { + let given = s.execute("script.palette.event", &json!({"palette": id, "event": "change", "control": 1, "value": value})); + assert!(given.is_err(), "{value}"); + } +} + +#[test] +fn with_nobody_to_ask_an_event_while_an_undo_group_is_open_is_refused_and_not_kept() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + s.execute("edit.undoGroup.begin", &json!({})).unwrap(); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("undo group is open"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the refused click does not wait"); + s.execute("edit.undoGroup.end", &json!({})).unwrap(); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap(); + assert_eq!(clicked["log"], json!(["click 1"]), "only the click given after the group ran"); +} + +#[test] +fn with_nobody_to_ask_an_event_whose_run_cannot_begin_ends_with_its_error_and_the_next_waits() { + let mut s = one_doc(); + run(&mut s, TOOLS).unwrap(); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Change(2, crate::script::UiValue::Text("a".into()))), Ok(Waiting::Added)); + // The document has changes, and the session has nowhere to keep a recovery copy of it. + s.script_copy_first = true; + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("recovery copy"), "{e}"); + assert_eq!(s.script_palette_events_waiting(), 1, "the click after the change whose run could not begin still waits"); + s.script_copy_first = false; + assert_eq!(s.script_palette_run_waiting().unwrap()["log"], json!(["click 1"])); +} + +#[test] +fn a_handler_s_error_keeps_its_file_when_a_palette_getter_throws_after_it() { + let base = std::env::temp_dir().join(format!("vc-script-palette-place-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + std::fs::create_dir_all(&base).unwrap(); + let base = std::fs::canonicalize(&base).unwrap(); + let first = base.join("first.jsx"); + std::fs::write( + &first, + "#targetengine places\nvar armed = false; var p = new Window('palette'); var b = p.add('button', undefined, 'Go');\n\ + Object.defineProperty(p, 'text', {get: function () { if (armed) { throw new Error('getter'); } return 'P'; }});\np.show();", + ) + .unwrap(); + let second = base.join("second.jsx"); + std::fs::write(&second, "#targetengine places\n\n\nb.onClick = function () { armed = true; throw new Error('handler'); };").unwrap(); + let mut s = one_doc(); + for file in [&first, &second] { + s.execute("script.run", &json!({"path": file.to_string_lossy()})).unwrap(); + } + let id = only_palette(&s); + let e = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": 1})).unwrap_err().to_string(); + assert!(e.contains("handler"), "{e}"); + let report = s.script_report().unwrap(); + assert!(report["file"].as_str().is_some_and(|f| f.ends_with("second.jsx")), "{report}"); + assert_eq!(report["line"], 4, "{report}"); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn a_palette_from_a_script_without_a_named_engine_is_refused() { let mut s = one_doc(); diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 117ae759b6..3a65a60f0b 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -512,6 +512,18 @@ impl Realm { } } + /// [`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. + 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 _ = self.refresh_script_ui(); + self.interp.error_tag = tag; + self.interp.error_mark = mark; + self.interp.last_thrown = thrown; + } + /// 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`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 52f42ee49c..dac3e9d590 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -666,14 +666,15 @@ fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { let (o, palette) = window_of(i, &this, "hide")?; if !palette { @@ -682,6 +683,7 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } @@ -698,10 +700,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); } - set_slot(i, win, IN_CLOSE, Value::Bool(true))?; - let allowed = may_close(i, win); - set_slot(i, win, IN_CLOSE, Value::Undefined)?; - if !allowed? { + if !may_close(i, win)? { return Ok(()); } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { @@ -724,10 +723,16 @@ fn update_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { /// Gives the host the controls of every palette it shows, after a handler may have changed them. fn update_palettes(i: &mut Interp) -> JsResult<()> { - for win in classes(i)?.palettes { - update_palette(i, win)?; - } - Ok(()) + // A getter may close a later palette, which removes it from the rooted list, so the copy is + // rooted until the loop ends. + let palettes = classes(i)?.palettes; + let roots: Vec = palettes.iter().map(|&win| Value::Object(win)).collect(); + i.rooted(&roots, |i| { + for win in palettes { + update_palette(i, win)?; + } + Ok(()) + }) } /// Gives the host the controls of every palette the realm keeps, as a run left them @@ -755,15 +760,16 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; Ok(Value::Undefined) } /// `Window.__vcPaletteEvent()`, which the run of a palette's handler calls: takes the event from the -/// host's `paletteEvent`, gives it to the palette the way a dialog takes the person's event, and -/// gives the host every palette's controls afterward. An event for a palette that has closed does -/// nothing. +/// host's `paletteEvent` and gives it to the palette the way a dialog takes the person's event. The +/// host gets every palette's controls once the run ends ([`crate::Realm::refresh_script_ui`]). An +/// event for a palette that has closed does nothing. fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; @@ -795,7 +801,6 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. +/// Runs `onClose`, during which a `close()` of the same window does nothing. → false when it +/// returned `false`. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) + set_slot(i, win, IN_CLOSE, Value::Bool(true))?; + let ran = handler(i, win, "onClose"); + set_slot(i, win, IN_CLOSE, Value::Undefined)?; + Ok(!matches!(ran?, Some(Value::Bool(false)))) } /// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. @@ -1005,12 +1014,14 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } // A palette's list may have changed while the event waited: the host gives // the items the person saw and the list's revision then. + // The revision is read after the texts, whose getters may change the list. None => { + let same = same_items(i, c, &slot(i, ev, "items")?)?; let revised = match slot(i, ev, "revision")? { Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; - if revised || !same_items(i, c, &slot(i, ev, "items")?)? || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { + if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } } @@ -1116,7 +1127,9 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { Some(Data::Number(n)) => *n, _ => 0.0, }; - return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + // Two finite numbers can add up to infinity; the sum is kept finite. + let end = |a: f64, b: f64| (a + b).clamp(-f64::MAX, f64::MAX); + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(end(n(0), n(2))), Data::Number(end(n(1), n(3)))])); } numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 76a70d331d..f9be03af3b 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -444,7 +444,10 @@ fn a_palette_s_show_returns_at_once_and_its_events_run_its_handlers() { 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())); - assert_eq!(calls.borrow().iter().filter(|(n, id)| n == "paletteUpdate" && *id == 1.0).count(), 3, "each event gives the host the new controls"); + 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"); } @@ -489,6 +492,73 @@ fn a_palette_list_change_after_its_items_changed_throws() { 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 replaces the items with ones of the same + // texts. + 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) { 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_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()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b52abc1a7a..7cc5524c25 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -370,11 +370,10 @@ impl VectorcraftApp { crate::dialogs::proof_setup::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 to end looks again four times a second. + // 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 self.session.script_palette_can_start() { ctx.request_repaint(); - } else if self.session.script_palette_events_waiting() > 0 && !self.session.script_running() { - ctx.request_repaint_after(std::time::Duration::from_millis(250)); } if self.session.script_running() && !self.session.script_waiting() @@ -672,6 +671,10 @@ impl VectorcraftApp { } scrub::end_frame(self, &ctx); native_menu::sync(self, &ctx); + // A palette event that waited for an undo group this pass ended starts its run next frame. + if self.session.script_palette_can_start() { + ctx.request_repaint(); + } // Observe once, after all of this pass's input, dialogs, floating panels, palette and // commands: the latest completed pass is authoritative for owner, text and cause. crate::ime::end_of_pass(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2c8f35365e..343f6c27d3 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -144,6 +144,15 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc // The control the event was given to, found again in the dialog as the handlers that ran // since left it. let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| w.control_at(&p)); + // A list's choice whose list a handler changed since it was made is not given. + if !same_list(&w, at, fields.remove(LIST_KEY).as_ref()) { + app.status(LIST_CHANGED); + // The events after it are given from the next frame on. + if d.fields.contains_key(QUEUE_KEY) { + ui.ctx().request_repaint(); + } + return DialogAction::None; + } if let Some(i) = at { fields.insert("control".into(), json!(i)); } @@ -152,6 +161,13 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc DialogAction::Confirm } +/// The field of a queued list change that holds the list's items and revision as the person saw +/// them ([`UiNode::revision`]). +const LIST_KEY: &str = "list"; + +/// The status when a queued list choice is not given because its list changed. +const LIST_CHANGED: &str = "The list's items changed before the choice was taken"; + /// The field of a queued event that holds where its control sits in the dialog /// ([`ScriptUiDialog::place_of`]). const PLACE_KEY: &str = "place"; @@ -442,9 +458,22 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { if let Some(i) = control { fields[PLACE_KEY] = json!(w.place_of(i)); } + if let UiEvent::Change(i, UiValue::Index(_)) = event + && let Some(n) = w.nodes.get(*i) + { + fields[LIST_KEY] = json!({"items": n.items, "revision": n.revision}); + } fields } +/// Whether the list control `at` of `w` still holds the items a queued list change was given for +/// (its [`LIST_KEY`] field): the same texts and the same revision. True for any other event. +fn same_list(w: &ScriptUiDialog, at: Option, seen: Option<&Value>) -> bool { + let Some(seen) = seen else { return true }; + let n = at.and_then(|i| w.nodes.get(i)); + n.is_some_and(|n| seen["revision"].as_f64() == Some(n.revision) && seen["items"] == json!(n.items)) +} + /// The event in the dialog's fields, for the dialog `w`. fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { let control = match d.fields.get("control") { diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 51a518f798..055cc437f6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6583,6 +6583,7 @@ liquify-list-end {0}, {1} {0} i {1} @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` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 9457178baf..17f9bd3929 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8987,6 +8987,7 @@ breakText Glyphs Glyfy @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 diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 1ef0d2169d..4f64a31c76 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -226,6 +226,7 @@ liquify-list-end {0}, {1} {0} og {1} @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` diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 935a135c4b..d606cb3196 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8427,6 +8427,7 @@ breakText Glyphs Glyphen @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 diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index aa30a34709..4ae2b19c0a 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2780,6 +2780,7 @@ liquify-list-end {0}, {1} {0} και {1} @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` diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 5cc8d86fdf..6c79382ae8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5055,6 +5055,7 @@ liquify-list-end {0}, {1} {0}, {1} @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` diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 1205c1dc9d..3a223923e4 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5296,6 +5296,7 @@ liquify-list-end {0}, {1} {0} ja {1} @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` diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index dbdca9ca76..0560264b7c 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8854,6 +8854,7 @@ breakText Glyphs Glyphes @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 diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 8c5e1f5602..d600eda164 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7729,6 +7729,7 @@ liquify-list-end {0}, {1} {0} और {1} @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` वाला ऑब्जेक्ट होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 6f7ce5a4ca..10ec8d74fc 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8858,6 +8858,7 @@ breakText Glyphs Glifák @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 diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 25e340bec0..50c3eeec25 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -134,6 +134,7 @@ @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` diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ea73cf2b91..788dad1c7a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8468,6 +8468,7 @@ breakText Glyphs Glifi @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} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 0b73565e9a..1ef4e34f52 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7294,6 +7294,7 @@ axis Y Axis Y 軸 @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` にはドキュメントのアートボードのインデックスを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 541d871302..709bb0deea 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -177,6 +177,7 @@ @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` უნდა იყოს დოკუმენტის სამუშაო დაფის ინდექსი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 07bde95166..e306c15d66 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8626,6 +8626,7 @@ breakText Glyphs 글리프 @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`은(는) 문서에 있는 아트보드의 인덱스여야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 9287dd44e3..93a35a622b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6494,6 +6494,7 @@ imageTrace Outline Contour @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 diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index fd7342da72..a89b52d6cd 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8671,6 +8671,7 @@ breakText Glyphs Glify @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} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4aa2697468..24838d4c6b 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9040,6 +9040,7 @@ swatch Yellow Green Verde-amarelado @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} diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ac74d5747a..8bdecf2658 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5077,6 +5077,7 @@ liquify-list-end {0}, {1} {0} и {1} @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` diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index dc74ea16ce..ea059da395 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4952,6 +4952,7 @@ liquify-list-end {0}, {1} {0} och {1} @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` diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 109ef0345a..07a1987942 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7670,6 +7670,7 @@ axis Y Axis Y ekseni @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 diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 20e6a222ab..f7b1ffc2a2 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8627,6 +8627,7 @@ breakText Glyphs Гліфи @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} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 173c74895c..4fa7e8ace1 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5576,6 +5576,7 @@ liquify-list-end {0}, {1} {0} và {1} @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` diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 129b2fff68..863ae243df 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8677,6 +8677,7 @@ breakText Glyphs 字形 @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} 之间的整数 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b11084d879..2d69c7b869 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8622,6 +8622,7 @@ breakText Glyphs 字符 @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` 必須是文件中某個工作區域的索引 diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 877548d602..b02fc382b2 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -28,10 +28,16 @@ fn run_to_end(app: &mut VectorcraftApp) { /// One headless frame in which `f` runs. → whether the frame asked for the next one at once. fn frame(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> bool { + frame_delay(ctx, f).is_zero() +} + +/// One headless frame in which `f` runs. → how long until the frame asked for the next one; +/// `Duration::MAX` when it asked for none. +fn frame_delay(ctx: &egui::Context, f: impl FnMut(&mut egui::Ui)) -> std::time::Duration { let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, f); out.textures_delta.clear(); - out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()) + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) } #[test] @@ -98,15 +104,15 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let ctx = egui::Context::default(); frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); - let mut asks = true; + let mut delay = std::time::Duration::ZERO; for _ in 0..5 { app.begin_host_iteration(); - asks = frame(&ctx, |ui| app.tick(ui.ctx())); - if !asks { + delay = frame_delay(&ctx, |ui| app.tick(ui.ctx())); + if delay == std::time::Duration::MAX { break; } } - assert!(!asks, "the waiting click asks for no frames while the undo group is open"); + 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(); app.begin_host_iteration(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 21fbd0c785..d3e6069f16 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,32 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[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. + let swap = json!({"event": "click", "control": 2, "value": null}); + let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); + frame(&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"]); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "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 continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 2bc012fe73..fef4f78655 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2983,7 +2983,8 @@ the same controls, handlers and limits: 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. - A handler's run reads and writes the files the person allowed the script that first showed the palette. + 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. - 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. While an event waits, a @@ -3006,7 +3007,9 @@ waitingLimit: 64}`. `script.palette.event {palette, event, control?, value?}` gi `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 and returns the report of this one, -or its error. A hidden palette, a disabled or hidden control, and a control that cannot take the event are errors. +or its error; an event whose run cannot begin ends it with that error, and the events after it keep waiting. 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 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();"}' From f05ec9a0906db1895c6f54609a251c8150bb9b23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 21:36:00 -0800 Subject: [PATCH 009/334] Scripts: a palette event finds its control by its place, and a run at its dialog idles - script.palette.event's params text lists `control` and `value` with their notes in parentheses, so the description reads as a params object again. - A palette handler's run gets the place of the clicked or changed control from the host and gives the event to the control at that place in the palette as it is then. A getter read while the palette is described can add a control before it; the event no longer goes to the control that took its index. An event whose place holds no control is an error. - While a run waits at its ScriptUI dialog, the app asks for no frames; the pass that gives the dialog's event asks for the next one, and so does a frame that handles a control request while a run goes on, such as `ui.dialog.confirm` answering the dialog. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/palettes.rs | 2 +- crates/engine/src/script/scriptui.rs | 10 ++- crates/js/src/scriptui.rs | 35 +++++++++- crates/js/src/scriptui_tests.rs | 19 +++++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/control.rs | 4 ++ crates/ui-egui/src/dialogs/script_window.rs | 3 + crates/ui-egui/src/tests/script_window.rs | 77 +++++++++++++++++++++ 9 files changed, 146 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 349b46b28f..28a05598ea 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -77,7 +77,7 @@ pub fn specs() -> Vec { "Script Palette Event", [], None, - "{palette: an id script.palettes lists, event: click|change|close, control?: a control's index, or its name or text (click and change), value?: an edit field's text, a slider's number, or a list's item index or null (change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", + "{palette: an id script.palettes lists, event: click|change|close, control?: a control (its index, name or text; click and change), value?: the new value (an edit field's text, a slider's number, or a list's item index or null; change)} give a shown palette a click, a change or a close, as the person does: it runs as a run of its own in the palette's engine, with its report like script.run's, once no run is going, oldest first; while it waits, another click on the same control, change of it or close of the same palette takes its place with the newer value, and a list's change ends its run with an error when the list holds other items by then; dialogs throw in the handler in the app, and with nobody to ask the run ends at one; a hidden palette, a control that is disabled, hidden or cannot take the event, and a 65th waiting event are refused, and with nobody to ask so is an event while an undo group is open → in the app {waiting: true, merged: whether it took the place of a waiting event, waitingEvents}, and the report later in ui.inspect's scriptReport; with nobody to ask, the run's report (or its error) once it ends", always, palette_event ), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index e7de94a1bf..673fcf5714 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -65,7 +65,7 @@ pub(crate) struct Queued { /// Where the control of a click or a change sits in the palette ([`ScriptUiDialog::place_of`]), /// by which the event finds its control again when a run adds controls before it; empty for a /// close. - place: Vec, + pub(crate) place: Vec, /// 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. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index fd3bda32a4..bb96c2771d 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -773,13 +773,17 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { Ok(Data::Undefined) } -/// The event a palette handler's run is for, once: `{palette, event, id, value, items}`, as `show()` -/// takes a dialog's event with the palette's id added, and for a list's change the items the -/// palette showed; `null` for any other run, and after the first call. +/// The event a palette handler's run is for, once: `{palette, event, id, value, place, items}`, as +/// `show()` takes a dialog's event with the palette's id added, the place of a click's or a +/// change's control ([`ScriptUiDialog::place_of`]), 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 { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; let Data::Object(mut fields) = queued.event.data() else { return Ok(Data::Null) }; fields.push(("palette".into(), Data::Number(queued.palette as f64))); + if !queued.place.is_empty() { + fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); + } 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))); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index dac3e9d590..6e997aa2af 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -795,10 +795,23 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult= 1.0 && n.fract() == 0.0 && (n as usize) < count) { + let held = list_values(i, nodes)?; + // The host gives the control's place, which is found again in the palette as it is now: + // a getter read in the description may have added a control before it. + let at = match slot(i, ev, "place")? { + Value::Object(place) => { + let control = control_at_place(i, win, place)?; + control.and_then(|c| held.iter().position(|v| v.as_object() == Some(c))) + } + _ => match slot(i, ev, "id")? { + Value::Number(n) if n >= 1.0 && n.fract() == 0.0 => Some(n as usize), + _ => None, + }, + }; + let Some(at) = at.filter(|&n| n >= 1 && n < held.len()) else { return Err(error(i, "a palette event names a control the palette no longer holds")); - } + }; + set_slot(i, ev, "id", Value::Number(at as f64))?; take_event(i, win, nodes, ev, &event, None)?; } Ok(Value::Undefined) @@ -807,6 +820,22 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult> { + let mut at = win; + for k in list_values(i, place)? { + let Value::Number(k) = k else { return Ok(None) }; + if k < 0.0 || k.fract() != 0.0 { + return Ok(None); + } + let Some(kid) = kids_of(i, at)?.get(k as usize).and_then(Value::as_object) else { return Ok(None) }; + at = kid; + } + Ok((at != win).then_some(at)) +} + fn host_fn(i: &mut Interp, name: &str) -> JsResult { let host = classes(i)?.host; i.get_value(&Value::Object(host), &key(name)) diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index f9be03af3b..c6ed56abdb 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -530,6 +530,25 @@ fn a_palette_list_change_throws_when_an_item_s_text_getter_replaces_the_items() assert_eq!(r.run("[reads, got.join()].join()").unwrap(), JsValue::String("2,".into())); } +#[test] +fn a_palette_event_finds_its_control_by_its_place() { + let placed = |id: usize, place: &[f64]| { + let Data::Object(mut fields) = palette_event(1.0, click(id)) else { return Data::Null }; + fields.push(("place".into(), Data::Array(place.iter().map(|&k| Data::Number(k)).collect()))); + Data::Object(fields) + }; + // The host's index 1 is the group, where a control a getter added would have moved the button; + // the place is the button's, the second control of the palette. + let (mut r, _) = palette_realm(vec![placed(1, &[1.0]), placed(2, &[2.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 at its place"); + 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 at the place"); + assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); +} + #[test] fn a_palette_s_visible_follows_hide_and_show() { let (mut r, _) = palette_realm(Vec::new()); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7cc5524c25..b24b69f419 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -378,10 +378,12 @@ impl VectorcraftApp { if self.session.script_running() && !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 `picks::poll` looks 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(), diff --git a/crates/ui-egui/src/app/control.rs b/crates/ui-egui/src/app/control.rs index 5ef64dfa3f..43e1cff7ed 100644 --- a/crates/ui-egui/src/app/control.rs +++ b/crates/ui-egui/src/app/control.rs @@ -120,6 +120,10 @@ impl VectorcraftApp { if handled == control::MAX_CONTROL_REQUESTS_PER_FRAME { // Leave later requests on the channel and schedule another frame to serve them. 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.control_rx = Some(rx); } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 343f6c27d3..78e130bab2 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -158,6 +158,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc } d.fields.extend(fields); } + // The event lets the run go on, which the app idles for while it waits: the next frame takes + // the run's next slice. + ui.ctx().request_repaint(); DialogAction::Confirm } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index d3e6069f16..45bb4db50e 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -461,6 +461,83 @@ fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() assert_eq!(log(&app), json!([[1, "typed"]])); } +#[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 = egui::Context::default(); + 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 { + app.begin_host_iteration(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.tick(ui.ctx())); + out.textures_delta.clear(); + 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 = egui::Context::default(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let drain = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| app.drain_control(ui.ctx())); + out.textures_delta.clear(); + 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) = crate::control::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 = CTX.with(Clone::clone); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pass = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay) + }; + // The focused field's cursor blink asks for a later frame once the dialog has settled. + let mut settled = false; + for _ in 0..40 { + if !pass(&mut app).is_zero() { + settled = true; + break; + } + } + assert!(settled, "the dialog stops asking for the very next frame while nothing happens in it"); + // A click on Bold that waited in line behind a typed text. + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([{"event": "click", "control": 2, "value": null}])); + 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(); From 8cc34c71a07a4ff759dd3206b410ea59e51e7b66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 09:17:14 -0800 Subject: [PATCH 010/334] Scripts: a palette event is dropped once a getter or a handler closed the palette A palette event checks again, after the palette's description is read and after each handler is read or run, that the host still shows the palette under the id the event names. A getter or an earlier handler that closed the palette now stops the event, so no click or change reaches a closed palette, and a list change whose palette closed is dropped rather than refused. --- crates/js/src/scriptui.rs | 56 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 62 +++++++++++++++++++++++ crates/ui-egui/src/tests/script_window.rs | 21 +++++++- 3 files changed, 133 insertions(+), 6 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 6e997aa2af..e912e8a387 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -794,6 +794,10 @@ fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult JsResult) -> JsResult { + if keep.is_some() { + return Ok(true); + } + let id = slot(i, ev, "palette")?; + Ok(matches!((slot(i, win, PALETTE_ID)?, id), (Value::Number(a), Value::Number(b)) if a == b)) +} + +/// Calls control `c`'s handler `name` for the event `ev` when it has one and `win` still takes the +/// event once the handler has been read: a getter for `name` may have closed the palette. +/// → `None` when `win` no longer takes the event, otherwise `handler`'s answer. +fn event_handler(i: &mut Interp, win: ObjId, c: ObjId, ev: ObjId, keep: Option<&[Value]>, name: &str) -> JsResult>> { + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + let f = i.get_value(&Value::Object(c), &key(name))?; + if !still_takes(i, win, ev, keep)? { + return Ok(None); + } + if !i.is_callable(&f) { + return Ok(Some(None)); + } + i.call(&f, &Value::Object(c), &[]).map(|v| Some(Some(v))) +} + /// The control at `place` in `win` as it is now: the index of each control among its container's /// controls, from the window down, as the host counts places. `None` when the palette has no /// control there. @@ -975,7 +1007,8 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { /// A click or a change the host gave in `ev` for control `id` of `nodes` (a description's list of /// elements): the control takes it and its handler runs. A dialog's button without `onClick` asks /// to close it with 1 when it is the default element and 2 when it is the cancel element, which -/// `keep` (`show()`'s kept values) names; a palette has no `keep`. +/// `keep` (`show()`'s kept values) names; a palette has no `keep`. No handler of a palette runs +/// once a getter, a setter or an earlier handler of the event closed the palette. fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, keep: Option<&[Value]>) -> JsResult<()> { let id = match slot(i, ev, "id")? { Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, @@ -1003,7 +1036,10 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, } i.put(c, key("value"), Value::Bool(true), true)?; } - if handler(i, c, "onClick")?.is_none() + let Some(ran) = event_handler(i, win, c, ev, keep, "onClick")? else { + return Ok(()); + }; + if ran.is_none() && kind == "button" && let Some(keep) = keep { @@ -1019,11 +1055,15 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, match kind.as_str() { "edittext" => { i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } "slider" => { i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; + if event_handler(i, win, c, ev, keep, "onChanging")?.is_none() { + return Ok(()); + } } _ => { let n = match value { @@ -1050,6 +1090,11 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, Value::Number(r) => r != number_slot(i, c, REVISION)?, _ => false, }; + // An item's text getter may have closed the palette, and its `onClose` + // may have changed the list: the event is then dropped, not refused. + if !still_takes(i, win, ev, keep)? { + return Ok(()); + } if revised || !same || (n >= 0.0 && n as usize >= items_of(i, c)?.len()) { return Err(error(i, "a palette's list changed before the person's choice was taken")); } @@ -1058,7 +1103,8 @@ fn take_event(i: &mut Interp, win: ObjId, nodes: ObjId, ev: ObjId, event: &str, set_slot(i, c, SELECTION, Value::Number(n))?; } } - handler(i, c, "onChange")?; + // `onChanging` may have closed the palette. + event_handler(i, win, c, ev, keep, "onChange")?; } _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index c6ed56abdb..063d02a2af 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -549,6 +549,68 @@ fn a_palette_event_finds_its_control_by_its_place() { assert_eq!(r.run("clicks").unwrap(), JsValue::Number(1.0)); } +#[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_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_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_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()); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 45bb4db50e..ed94fdde69 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -551,7 +551,7 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { // A click on Swap, then a choice in the list as it was before Swap's handler ran, both given // in one frame. let swap = json!({"event": "click", "control": 2, "value": null}); - let choice = json!({"event": "change", "control": 1, "value": 1, "list": {"items": ["a", "b"], "revision": 2.0}}); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([swap, choice])); frame(&mut app, Vec::new()); assert!(until_window(&mut app), "the script takes the click and waits again"); @@ -564,6 +564,25 @@ fn a_queued_list_choice_is_not_given_after_a_handler_changed_the_list() { 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)); + let choice = json!({"event": "change", "control": 1, "value": 1, "place": [0], "list": {"items": ["a", "b"], "revision": 2.0}}); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([choice])); + frame(&mut app, Vec::new()); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "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(); From 73394611d102f04fda4fd3061f7769d831885890 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:20:02 -0800 Subject: [PATCH 011/334] Scripts: ScriptUI windows, groups and panels have update() Window.update() was missing, so a palette handler that moved a progress bar and called update() ended with an error. The window-object reference describes update() as redrawing the window and taking the person's waiting events, so that a Cancel button can stop a long loop (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). - update() on a shown palette, or on a group or panel in it, runs the handlers of the clicks, changes and closes that wait for the palettes of the run's engine, oldest first, so a loop that calls update() sees a Cancel button's onClick. Those events do not get runs of their own. - In the app, an update() in the script's own code then pauses the run so the app draws the palette, at most once every 16 ms of the run's time (VectorCraft's own interval). Only an update() that pauses gives the host the palette's controls, so a loop of many update() calls does not use up the run's host-call or bridge limits. An update() in a handler, a callback of a built-in function, a getter or a conversion, and any update() on the web, does not pause the run. - update() on the showing dialog, or a group or panel in it, runs without an error; the dialog shows a handler's changes when the handler returns. On a window that is not showing it throws an Error, and on a control that is not a container a TypeError. Whether a palette is showing comes from show() and hide(), not from its visible property. - docs/mcp.md and the progress-doc line describe update(). --- crates/engine/src/script/mod.rs | 24 ++++ crates/engine/src/script/palettes.rs | 73 +++++++---- crates/engine/src/script/scriptui.rs | 30 ++++- crates/engine/src/tests/script_palettes.rs | 105 +++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/scriptui.rs | 86 +++++++++++++ crates/js/src/scriptui_tests.rs | 117 ++++++++++++++++++ docs/mcp.md | 22 +++- docs/target-app-parity.md | 2 +- 9 files changed, 429 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ef204e4582..2ea2f2aa71 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -108,6 +108,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. @@ -799,6 +802,8 @@ struct Host { started: Option, /// The time since [`Host::started`] at which a `$.sleep` ends. wake_at: Cell>, + /// The time since [`Host::started`] at which a ScriptUI `update()` last ended the slice. + drawn_at: Cell>, /// Set while a host function runs where the run can stop at the call ([`Realm::wait_flag`]). can_wait: Rc>, /// What the last `#strict` line of the file `$.evalFile` last gave set (`None` without one). @@ -997,6 +1002,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 { let wake = self.wake_at.get()?; @@ -2081,6 +2104,7 @@ 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), diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 673fcf5714..68c84e3f0d 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -8,7 +8,9 @@ //! 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. While an event waits, another click //! on the same control, another change of it or another close of the same palette takes its place -//! in line, with the newer value, instead of waiting as well. +//! in line, with the newer value, instead of waiting as well. 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. @@ -188,33 +190,56 @@ impl Palettes { /// 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(mut q) = self.waiting.pop_front() { - let Some(p) = self.list.iter().find(|p| p.id == q.palette && p.visible) else { continue }; - if let Some(c) = control_of(&mut q.event) { - let Some(at) = p.dialog.control_at(&q.place) else { continue }; - *c = at; + while let Some(q) = self.waiting.pop_front() { + if let Some(taken) = self.checked(q) { + return Some(taken); } - // 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 { - if scriptui::check_event(&p.dialog, UiEvent::Change(c, UiValue::Index(None))).is_err() { - continue; - } - } else { - let Ok(event) = scriptui::check_event(&p.dialog, q.event) else { continue }; - q.event = event; - } - return Some((p.clone(), q)); } None } + + /// As [`Palettes::next`], for the palettes of the engine `engine` only: the events of other + /// engines' palettes keep their places in line. + fn next_of(&mut self, engine: &str) -> Option<(ScriptPalette, Queued)> { + loop { + let list = &self.list; + let at = self.waiting.iter().position(|q| list.iter().any(|p| p.id == q.palette && p.engine == engine))?; + let q = self.waiting.remove(at)?; + if let Some(taken) = self.checked(q) { + return Some(taken); + } + } + } + + /// The taken event `q` given to the control at its place 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.control_at(&q.place)?; + } + // 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`]). + pub(crate) fn take_for(&mut self, engine: &str) -> Option { + self.next_of(engine).map(|(_, q)| q) + } } /// `name` in a `#targetengine` line, quoted with a quote it does not hold. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index bb96c2771d..e460408a51 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -38,6 +38,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; @@ -712,6 +713,8 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("paletteHide".into(), function(link, palette_hide)), ("paletteClose".into(), function(link, palette_close)), ("paletteEvent".into(), function(link, palette_event)), + ("paletteTake".into(), function(link, palette_take)), + ("paletteDraw".into(), function(link, palette_draw)), ]) } @@ -747,7 +750,7 @@ fn palette_show(host: &Host, args: &[Data]) -> Result { shown.map(|id| Data::Number(id as f64)).map_err(HostError::Range) } -/// The palette `id`'s controls as a handler or `add()` left them. +/// The palette `id`'s controls as a handler, `add()` or `update()` left them. fn palette_update(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); let dialog = described(host, args)?; @@ -757,6 +760,22 @@ fn palette_update(host: &Host, args: &[Data]) -> Result { 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 { + 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. +fn palette_take(host: &Host, _: &[Data]) -> Result { + let engine = palette_engine(host)?.to_string(); + let taken = host.session.borrow_mut().script_palettes.take_for(&engine); + Ok(taken.map_or(Data::Null, event_data)) +} + fn palette_hide(host: &Host, args: &[Data]) -> Result { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { @@ -779,7 +798,12 @@ fn palette_close(host: &Host, args: &[Data]) -> Result { /// 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 { let Some(queued) = host.palette_event.borrow_mut().take() else { return Ok(Data::Null) }; - let Data::Object(mut fields) = queued.event.data() 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 !queued.place.is_empty() { fields.push(("place".into(), Data::Array(queued.place.iter().map(|&k| Data::Number(k as f64)).collect()))); @@ -788,7 +812,7 @@ fn palette_event(host: &Host, _: &[Data]) -> Result { fields.push(("items".into(), Data::Array(items.into_iter().map(Data::String).collect()))); fields.push(("revision".into(), Data::Number(revision))); } - Ok(Data::Object(fields)) + Data::Object(fields) } fn described(host: &Host, args: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index c432700fe6..eff97479d1 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -2,11 +2,13 @@ //! and run one at a time after it, the events that take a waiting one's place, `close()` and the //! close box, the engine's end, and the limits. +use std::time::Duration; + use serde_json::{Value, json}; use crate::script::palettes::{MAX_PALETTES, MAX_WAITING}; use crate::script::scriptui::PALETTE_NEEDS_ENGINE; -use crate::script::{DialogAnswer, UiEvent, Waiting}; +use crate::script::{DialogAnswer, TEST_ELAPSED, UiEvent, Waiting}; use crate::*; /// One open document with one rectangle. @@ -72,6 +74,107 @@ fn show_returns_at_once_and_the_palette_stays_after_the_run() { assert_eq!(changed["log"], json!(["change abc"])); } +#[test] +fn update_in_a_palette_s_handler_runs_and_the_palette_shows_the_last_value() { + let mut s = one_doc(); + run( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 10); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 10; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ) + .unwrap(); + let id = only_palette(&s); + let clicked = s.execute("script.palette.event", &json!({"palette": id, "event": "click", "control": "Go"})).unwrap(); + assert_eq!(clicked["log"], json!(["done"]), "update() in the handler does not throw"); + let listed = s.execute("script.palettes", &json!({})).unwrap(); + assert_eq!(listed["palettes"][0]["controls"][0]["value"].as_f64(), Some(10.0), "{listed}"); +} + +#[test] +fn update_outside_a_handler_pauses_the_run_so_the_app_draws_the_palette_at_most_once_per_interval() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); p.show(); \ + for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); }"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + let value = |s: &Session| s.script_palettes().first().map_or(0.0, |p| p.dialog.nodes[1].value); + for _ in 0..100 { + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + if value(&s) > 0.0 { + break; + } + } + let first = value(&s); + assert!(first > 0.0); + TEST_ELAPSED.set(Some(Duration::from_millis(16))); + assert!(s.script_pump().is_none(), "an update() a frame later pauses the run too"); + let second = value(&s); + assert!(second > first, "the palette shows the second update()"); + assert!(s.script_pump().expect("an update() within the same frame does not pause the run").is_ok()); + assert!(value(&s) > second); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_loop() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 100000); \ + var cancel = p.add('button', undefined, 'Cancel'); var stopped = false; cancel.onClick = function () { stopped = true; }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; bar.value = k; p.update(); } vc.log(stopped ? 'canceled' : 'ran out');"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["canceled"]), "{report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click was handled in the run, not left for a run of its own"); + TEST_ELAPSED.set(None); +} + +#[test] +fn update_in_a_handler_does_not_pause_the_run() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + run_in_app( + &mut s, + "#targetengine progress\nvar p = new Window('palette'); var bar = p.add('progressbar', undefined, 0, 3); \ + var go = p.add('button', undefined, 'Go'); \ + go.onClick = function () { for (var k = 1; k <= 3; k++) { bar.value = k; p.update(); } vc.log('done'); }; p.show();", + ); + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + assert!(s.script_palette_start().expect("the click starts its run").is_ok()); + let report = s.script_pump().expect("the handler's run ends without a pause after the handler").unwrap(); + assert_eq!(report["log"], json!(["done"])); + TEST_ELAPSED.set(None); +} + +#[test] +fn many_update_calls_within_one_interval_give_the_controls_once() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + let report = run_in_app( + &mut s, + "#targetengine progress\nvar names = []; for (var n = 0; n < 500; n++) { names.push('a long list item name ' + n); } \ + var p = new Window('palette'); var list = p.add('listbox', undefined, names); var bar = p.add('progressbar', undefined, 0, 1000); \ + p.show(); for (var k = 1; k <= 1000; k++) { bar.value = k; p.update(); }", + ); + let calls = report["hostCalls"].as_u64().unwrap(); + assert!(calls < 1000, "an update() the app does not draw costs no host call: {calls}"); + let bar = s.script_palettes()[0].dialog.nodes[2].value; + assert_eq!(bar, 1000.0, "the palette shows the last value once the run ends"); + TEST_ELAPSED.set(None); +} + #[test] fn a_later_run_in_the_engine_changes_what_the_palette_shows() { let mut s = one_doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 08badaae56..ba03106e4b 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -45,7 +45,7 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), ("Window.", "__vcPaletteEvent length prototype"), - ("Window.prototype.", "add center close constructor findElement hide show"), + ("Window.prototype.", "add center close constructor findElement hide show update"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index e912e8a387..2d2ccf2e9a 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -33,6 +33,14 @@ //! host's `paletteEvent` (`{palette, event, id, value}`, or `null`), gives it to that palette as a //! dialog takes one, and then gives `paletteUpdate` each palette's description; `add()` on a shown //! palette does the same for that palette, so the host's list of its controls stays in step. +//! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits +//! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or +//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! handler, a callback of a built-in function, a getter or a conversion), it asks the host's +//! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the +//! palette's description. On the showing dialog, or a group or panel in it, `update()` does +//! nothing more, and on a window that is not showing it throws an `Error`. A dialog takes the +//! person's events once the running handler returns. //! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the @@ -77,6 +85,7 @@ const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; const PALETTE_ID: &str = "__vcPaletteId"; +const SHOWN: &str = "__vcShown"; const IN_CLOSE: &str = "__vcInClose"; /// How many times a list's items were added or removed: a palette's waiting change of the list is /// for the items it had then. @@ -683,11 +692,76 @@ fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if let Value::Number(id) = slot(i, o, PALETTE_ID)? { let f = host_fn(i, "paletteHide")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; + set_slot(i, o, SHOWN, Value::Bool(false))?; i.put(o, key("visible"), Value::Bool(false), true)?; } Ok(Value::Undefined) } +/// `update()` on a window: [`update_window`]. +fn update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, palette) = window_of(i, &this, "update")?; + update_window(i, o, palette, own)?; + Ok(Value::Undefined) +} + +/// Whether the native running now was called from the script's own code in a run that can pause, +/// as the host's functions find whether a run can wait. +fn own_code(i: &Interp) -> bool { + i.in_slice && i.reentry == 0 +} + +/// `update()` on a `group` or a `panel`: [`update_window`] for the window that holds it. +fn control_update(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let own = own_code(i); + let (o, kind) = element(i, &this, "update")?; + if !is_container(&kind) { + return Err(i.type_error("update: this is not a ScriptUI window or container")); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a container without its window".into())) }; + let palette = matches!(slot(i, win, KIND)?, Value::String(s) if s.to_rust_string() == "palette"); + update_window(i, win, palette, own)?; + Ok(Value::Undefined) +} + +/// `update()` on the window `win`. On a shown palette: hands each event that waits for a palette of +/// the run's engine to its palette ([`take_waiting`]), and then, from the script's own code (`own`), +/// gives the host the palette's controls when the host draws it now (`paletteDraw`). The showing +/// dialog's controls go to the host when its handler returns, since a handler runs to its end in +/// one slice. Whether a palette shows is the host's, not its `visible` property. A window that is +/// not showing throws. +fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResult<()> { + let showing = if palette { slot(i, win, SHOWN)?.truthy() } else { classes(i)?.showing == Some(win) }; + if !showing { + return Err(error(i, "update: the window is not showing")); + } + if !palette { + return Ok(()); + } + take_waiting(i)?; + if !own || !slot(i, win, SHOWN)?.truthy() { + return Ok(()); + } + let f = host_fn(i, "paletteDraw")?; + if i.call(&f, &Value::Undefined, &[])?.truthy() { + update_palette(i, win)?; + } + Ok(()) +} + +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +fn take_waiting(i: &mut Interp) -> JsResult<()> { + let f = host_fn(i, "paletteTake")?; + loop { + let answer = i.call(&f, &Value::Undefined, &[])?; + if answer.as_object().is_none() { + return Ok(()); + } + deliver(i, answer)?; + } +} + fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { if let Some(c) = i.script_ui.as_mut() { f(&mut c.palettes); @@ -705,6 +779,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { } if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; + set_slot(i, win, SHOWN, Value::Bool(false))?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; @@ -760,6 +835,7 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { if !classes(i)?.palettes.contains(&win) { set_palettes(i, |p| p.push(win)); } + set_slot(i, win, SHOWN, Value::Bool(true))?; i.put(win, key("visible"), Value::Bool(true), true)?; handler(i, win, "onShow")?; update_palette(i, win)?; @@ -773,6 +849,14 @@ fn palette_shown(i: &mut Interp, keep: &[Value], id: Value) -> JsResult { fn palette_event(i: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { let f = host_fn(i, "paletteEvent")?; let answer = i.call(&f, &Value::Undefined, &[])?; + deliver(i, answer)?; + Ok(Value::Undefined) +} + +/// Gives the host's event `answer` (`{palette, event, id, value, place}`, or anything else for +/// none) to its palette the way a dialog takes the person's event. An event for a palette that has +/// closed does nothing. +fn deliver(i: &mut Interp, answer: Value) -> JsResult { let Some(ev) = answer.as_object() else { return Ok(Value::Undefined) }; let mark = i.temp_roots.len(); i.temp_roots.push(answer.clone()); @@ -1422,6 +1506,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; + method(i, window_proto, "update", update, 0)?; pausable_method(i, window_proto, "show", show, 0)?; method(i, control_proto, "add", add, 4)?; method(i, control_proto, "findElement", find_element, 1)?; @@ -1429,6 +1514,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, control_proto, "notify", notify, 1)?; method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; + method(i, control_proto, "update", control_update, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 063d02a2af..355faee1cf 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -380,6 +380,12 @@ type Calls = Rc>>; /// 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) -> (Realm, Calls) { + palette_realm_with(events, Vec::new(), Vec::new()) +} + +/// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, +/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); let calls: Calls = Rc::default(); @@ -403,6 +409,18 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); + let taken = RefCell::new(VecDeque::from(taken)); + let c = calls.clone(); + let take: HostFunction = Rc::new(move |_| { + c.borrow_mut().push(("paletteTake".into(), 0.0)); + Ok(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + }); + 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())), @@ -414,6 +432,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { ("paletteHide".into(), HostItem::Function(record("paletteHide", 0))), ("paletteClose".into(), HostItem::Function(record("paletteClose", 0))), ("paletteEvent".into(), HostItem::Function(event)), + ("paletteTake".into(), HostItem::Function(take)), + ("paletteDraw".into(), HostItem::Function(draw)), ]; r.define_script_ui(items).unwrap(); (r, calls) @@ -467,6 +487,103 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { 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!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); +} + +#[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| { diff --git a/docs/mcp.md b/docs/mcp.md index fef4f78655..941a86437c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2918,8 +2918,15 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s - A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, `window`, `show()` and `hide()`. 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) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, - `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + (15 to start, 0 for a group), `findElement(name)` and `update()`. 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. `show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An @@ -2983,6 +2990,17 @@ the same controls, handlers and limits: 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/). + Those events do not wait for runs of their own. 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. - Each click, change or close the person gives a palette runs its handler as a run of its own in the palette's diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c8f4bb0095..9919c099c6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1067,7 +1067,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - 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, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button; a run over MCP or the command line takes the clicks and changes from a `window` answer. Other control types and resource strings 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")` in a script with `#targetengine` shows a palette that stays open beside the documents 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; a newer event for the same control takes a waiting one's place. A palette closes with `close()`, its close box, or the end of its engine or the session; 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`. + - Scripts: ScriptUI's `new Window("palette")` in a script with `#targetengine` shows a palette that stays open beside the documents 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; a newer event for the same control takes a waiting one's place. `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, so a Cancel button can stop a loop, and in the script's own code in the app pauses the run so the app draws the palette, at most once every 16 ms; on a showing dialog it runs without an error. A palette closes with `close()`, its close box, or the end of its engine or the session; 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`). From fe0c8da91908b62ed01a1c1517a638f5b08e3d91 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:51:32 -0800 Subject: [PATCH 012/334] Scripts: layers and groups give their own path items Layer.pathItems and GroupItem.pathItems now return a PathItems collection for the paths directly in the layer or group, topmost first, as the Layer and GroupItem pages describe them (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). Before, both threw an error that said they were not available yet. - The collection has the members of Document.pathItems. Its parent is the layer or group, and length, [i], index and getByName read only that container's paths, so a path inside a group, a compound path or a sublayer is not listed. - add() and the shape creators put the new path on top of the layer's or group's contents and leave the current layer as it was. The path is made with the container's layer current (layer.setCurrent) and, for a group, moved into it with node.move, in the run's one undo step. - VectorCraft's own rule: a layer or group that is hidden or locked, or that is in a hidden or locked layer or group, throws "Cannot add a path to a hidden or locked layer or group" and no path is made. - The last four path lists stay cached while their documents are unchanged, so a loop over a large layer or group builds its list once. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 6 +- crates/engine/src/script/dom/layers.rs | 24 +- crates/engine/src/script/dom/paths.rs | 206 +++++++++++++----- crates/engine/src/tests/script_dom.rs | 117 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 4 +- docs/mcp.md | 20 +- docs/target-app-parity.md | 2 +- 7 files changed, 302 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c600cc84c4..e8d0cc404a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -102,8 +102,10 @@ pub(super) struct State { coords: Cell, items: RefCell>, locked: RefCell>, - /// The last list of a document's paths ([`paths`]), kept while that document is unchanged. - paths: RefCell>, + /// The last [`paths::PATH_LISTS`] lists of paths a document's, a layer's or a group's + /// `pathItems` gave ([`paths`]), least recently used first, each kept while its document is + /// unchanged. + paths: RefCell>, /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 3fafaf684b..23e4d58170 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -12,8 +12,8 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `layers` lists layers top first, as the Layers panel shows them. A layer's or group's -//! `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the -//! objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` +//! `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a compound path's +//! `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` //! hold every group or compound path at any depth, in the order of the document's `pageItems`. //! - `layers.add()` on the document makes a layer above every top-level layer; on a layer it makes //! a sublayer on top of that layer's contents. The new layer becomes the current one. @@ -114,7 +114,7 @@ fn this_layer(h: &Host, a: &[Data]) -> Result<(Doc, NodeId)> { layer_of(h, arg(a, 0)) } -fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { +pub(super) fn layer_ref(h: &Host, uid: u64, id: NodeId) -> Data { let [high, low] = id_parts(id); host_ref("Layer", &[float(h.run), float(uid), high, low]) } @@ -845,6 +845,17 @@ fn held_compounds(h: &Host, a: &[Data]) -> Answer { held(h, a, Kind::Compound) } +/// A layer's or group's `pathItems`: the paths directly in it ([`super::paths`]). +fn held_paths(h: &Host, a: &[Data]) -> Answer { + let this = arg(a, 0); + if handle_of(this, "Layer").is_some() { + let (doc, id) = layer_of(h, this)?; + return Ok(super::paths::held_path_items(h, doc.uid, id)); + } + let item = this_item_of(h, a, "GroupItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -897,8 +908,9 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ]); - m.extend(["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); + m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), @@ -1320,6 +1332,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("pageItems", get(l, held_page_items)), ("groupItems", get(l, held_groups)), ("compoundPathItems", get(l, held_compounds)), + ("pathItems", get(l, held_paths)), ("zOrderPosition", get(l, layer_z_position)), ("hasSelectedArtwork", property(l, layer_has_selected, layer_set_has_selected)), ("isIsolated", get(l, layer_is_isolated)), @@ -1328,8 +1341,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("zOrder", method(l, layer_z_order)), ]); layer.extend( - ["pathItems", "textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"] - .map(|m| later(l, "Layer", m)), + ["textFrames", "symbolItems", "placedItems", "rasterItems", "blendingMode", "artworkKnockout", "sliced"].map(|m| later(l, "Layer", m)), ); vec![ class("Layer", None, layer, None), diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 32401db1d0..87287c5c27 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -13,7 +13,9 @@ //! //! VectorCraft's own rules, which the help pages do not state: //! - `Document.pathItems` lists the document's paths in the order of `pageItems`, paths inside -//! groups and compound paths included. +//! groups and compound paths included. A layer's or group's `pathItems` list the paths directly in +//! it, topmost first, and make their paths on top of its contents; a layer or group that is hidden +//! or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`]. //! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden //! or locked layer or group, throws `Cannot edit` with nothing changed. //! - A path in a compound path or compound shape reads that owner's paint, which the paint @@ -23,8 +25,8 @@ //! fill or stroke only. //! - `closed` is true when every subpath of the path is closed, and assigning it opens or closes //! them all. -//! - `pathItems.add()` and the shape creators make their path on top of the active layer, whatever -//! the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or +//! - `pathItems.add()` and the shape creators make their path on top of the active layer (a layer's +//! or group's: on top of its contents), whatever the drawing mode, painted as new art is; `add()` makes a path with no points. `filled` and `stroked` set to true give a path with no fill or stroke new art's fill or //! stroke (solid, gradient or pattern), or black when new art has none. `PathPoints.add()` adds //! a corner point with no handles at the last point, or at `[0, 0]` on a path with no points. //! Removing the last points leaves the path, with no points. @@ -56,8 +58,8 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of, edit_item, editable, find_doc, - float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, + frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -263,21 +265,48 @@ fn keeping_paint(h: &super::Host, f: impl FnOnce() -> T) -> T { r } -// ---- Document.pathItems ---- +// ---- Document.pathItems, Layer.pathItems and GroupItem.pathItems ---- -/// The ids of a document's paths, in the order of its page items. -fn path_items(h: &super::Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.paths.borrow() - && *uid == st.uid - && std::sync::Arc::ptr_eq(doc, &st.doc) +/// A document's uid, the document as it was, the layer or group a list of paths is of (none for the +/// document's), and the ids it listed then. +pub(super) type PathList = (u64, Arc, Option, Rc>); + +/// How many lists of paths [`super::State`] keeps at once. +pub(super) const PATH_LISTS: usize = 4; + +/// The ids of a document's paths, in the order of its page items, or of the paths directly in the +/// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their +/// documents are unchanged, so a loop over a collection builds its list once. A new list of a +/// container is charged by the objects it looks at. +fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { - return ids.clone(); + let mut lists = h.dom.paths.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, c, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *c == container) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } } - let all = super::page_items(h, st); - let ids: Rc> = - Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. }))).collect()); - *h.dom.paths.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); - ids + let is_path = |n: &crate::doc::Node| matches!(n.kind, NodeKind::Path { .. }); + let ids: Rc> = match container { + Some(c) => { + let children: &[Arc] = st.doc.node(c).and_then(|n| n.children()).map_or(&[], Vec::as_slice); + h.charge_call(children.len() as u64)?; + Rc::new(children.iter().rev().filter(|n| is_path(n)).map(|n| n.id).collect()) + } + None => { + let all = super::page_items(h, st); + Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) + } + }; + let mut lists = h.dom.paths.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= PATH_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), container, ids.clone())); + Ok(ids) } pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { @@ -285,32 +314,57 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer { Ok(host_ref("PathItems", &[float(h.run), float(doc.uid)])) } -fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result { - doc_of(h, arg(a, 0), "PathItems") +/// The `pathItems` of the layer or group `id` in the document `uid`. +pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { + let [high, low] = id_parts(id); + host_ref("PathItems", &[float(h.run), float(uid), high, low]) +} + +/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { + let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; + match handle.as_slice() { + [run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?, None)), + [run, uid, high, low] => { + let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + if !holds { + return Err(HostError::Error(STALE_ITEM.into())); + } + Ok((doc, Some(id))) + } + _ => Err(HostError::Type("this is not a PathItems".into())), + } } fn items_length(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).len()) as u64))) + let (doc, c) = items_scope(h, a)?; + Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st, c).map(|l| l.len()))? as u64))) } fn items_parent(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - Ok(host_ref("Document", &[float(h.run), float(doc.uid)])) + let (doc, c) = items_scope(h, a)?; + Ok(match c { + None => host_ref("Document", &[float(h.run), float(doc.uid)]), + Some(c) => with_doc(h, doc, |_, st| { + if st.doc.node(c).is_some_and(crate::doc::Node::is_layer) { super::layers::layer_ref(h, st.uid, c) } else { super::item_ref(h, st, c) } + }), + }) } fn items_at(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| path_items(h, st).get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) + with_doc(h, doc, |_, st| Ok(path_items(h, st, c)?.get(i).map_or(Data::Undefined, |id| super::item_ref(h, st, *id)))) } fn items_by_name(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| super::item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -328,15 +382,15 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer { } } -/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked -/// path, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// `pathItems.removeAll()`: deletes every path the collection lists in one command. A hidden or +/// locked path, or one in a hidden or locked layer or group, stops it before anything is deleted. fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, c) = items_scope(h, a)?; let (ids, refused) = with_doc(h, doc, |_, st| { - let ids = path_items(h, st); + let ids = path_items(h, st, c)?; let refused: Vec = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect(); - (ids, refused) - }); + Ok::<_, HostError>((ids, refused)) + })?; if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked paths: {list}"))); @@ -356,19 +410,53 @@ fn made_id(r: &Data) -> std::result::Result { id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } -/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept, -/// and reverses the new path's direction when `reversed`. → the new path. -fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer { - let made = on_doc(h, doc.uid, true, |h| { +/// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or +/// locked layer or group. +pub const CONTAINER_LOCKED: &str = "Cannot add a path to a hidden or locked layer or group"; + +/// Runs `make`, which makes a path in `doc` on top of the current layer and gives its id, with the +/// selection and the current layer kept. With a layer or group `container`, the container's layer +/// is the current one while `make` runs (`layer.setCurrent`, not an undo step), and a path made +/// outside the container then moves on top of its contents in the same step; a container that is +/// hidden or locked, or that is in a hidden or locked layer or group, throws [`CONTAINER_LOCKED`] +/// before anything is made. → the new path. +fn make_in( + h: &super::Host, + doc: Doc, + container: Option, + make: impl FnOnce(&super::Host) -> std::result::Result, +) -> Answer { + if let Some(c) = container + && !with_doc(h, doc, |_, st| editable(&st.doc, c)) + { + return Err(HostError::Error(CONTAINER_LOCKED.into())); + } + let made = match container { + None => on_doc(h, doc.uid, true, make)?, + Some(c) => super::atomically(h, |h| { + let id = on_doc(h, doc.uid, true, |h| { + command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; + make(h) + })?; + super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?; + Ok(id) + })?, + }; + let s = h.session.borrow(); + let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; + Ok(super::item_ref(h, st, made)) +} + +/// Runs the command `id` that makes a path in `doc`, on top of the active layer or of `container`'s +/// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. +fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { + make_in(h, doc, container, |h| { let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } /// Argument `i`, or `default` when it is left out. @@ -409,13 +497,13 @@ fn corner(h: &super::Host, doc: Doc, left: f64, top: f64) -> std::result::Result /// `rectangle(top, left, width, height, reversed?)`. fn items_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); let reversed = flag(a, 5, "reversed")?; let p = corner(h, doc, left, top)?; - make(h, doc, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.rectangle", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The anchors of a rectangle `r` with elliptical corners of radii `rx` and `ry`, clockwise on the @@ -455,7 +543,7 @@ fn rounded(r: Rect, rx: f64, ry: f64) -> Vec { /// `roundedRectangle(top, left, width, height, horizontalRadius = 15, verticalRadius = 20, /// reversed = false)`: a closed path with `path.create`. fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = coordinate(arg(a, 1), "top")?; let left = coordinate(arg(a, 2), "left")?; let (w, ht) = (size(a, 3, None, "width")?, size(a, 4, None, "height")?); @@ -463,12 +551,12 @@ fn items_rounded_rectangle(h: &super::Host, a: &[Data]) -> Answer { let reversed = flag(a, 7, "reversed")?; let p = corner(h, doc, left, top)?; let anchors: Vec = rounded(Rect::new(p.x, p.y, p.x + w, p.y + ht), rx, ry).iter().map(anchor_json).collect(); - make(h, doc, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) + make(h, doc, into, "path.create", &json!({"anchors": anchors, "closed": true}), reversed) } /// `ellipse(top = 100, left = 100, width = 50, height = 100, reversed = false, inscribed)`. fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let top = given(arg(a, 1)).map_or(Ok(100.0), |d| coordinate(d, "top"))?; let left = given(arg(a, 2)).map_or(Ok(100.0), |d| coordinate(d, "left"))?; let (w, ht) = (size(a, 3, Some(50.0), "width")?, size(a, 4, Some(100.0), "height")?); @@ -477,7 +565,7 @@ fn items_ellipse(h: &super::Host, a: &[Data]) -> Answer { return Err(HostError::Error("ellipse with inscribed true is not available yet".into())); } let p = corner(h, doc, left, top)?; - make(h, doc, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) + make(h, doc, into, "shape.ellipse", &json!({"x": p.x, "y": p.y, "width": w, "height": ht}), reversed) } /// The center of a polygon or star, in document coordinates. @@ -489,32 +577,33 @@ fn center(h: &super::Host, doc: Doc, a: &[Data]) -> std::result::Result Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r = size(a, 3, Some(50.0), "radius")?; let sides = count(a, 4, 8.0, 3.0, 1000.0, "sides")?; let reversed = flag(a, 5, "reversed")?; - make(h, doc, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) + make(h, doc, into, "shape.polygon", &json!({"cx": c.x, "cy": c.y, "radius": r, "sides": sides}), reversed) } /// `star(centerX = 200, centerY = 300, radius = 50, innerRadius = 20, points = 5, reversed = /// false)`. fn items_star(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; + let (doc, into) = items_scope(h, a)?; let c = center(h, doc, a)?; let r1 = size(a, 3, Some(50.0), "radius")?; let r2 = size(a, 4, Some(20.0), "innerRadius")?; let points = count(a, 5, 5.0, 2.0, 1000.0, "points")?; let reversed = flag(a, 6, "reversed")?; - make(h, doc, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) + make(h, doc, into, "shape.star", &json!({"cx": c.x, "cy": c.y, "radius1": r1, "radius2": r2, "points": points}), reversed) } -/// `pathItems.add()`: a path with no points on top of the active layer, from `path.create` with -/// empty path data, painted as new art. When new art has no fill and no stroke, the black stroke `path.create` gives an open -/// path is set back to none in the same step. +/// `pathItems.add()`: a path with no points on top of the active layer, or of the layer's or +/// group's contents ([`make_in`]), from `path.create` with empty path data, painted as new art. +/// When new art has no fill and no stroke, the black stroke `path.create` gives an open path is set +/// back to none in the same step. fn items_add(h: &super::Host, a: &[Data]) -> Answer { - let doc = items_doc(h, a)?; - let made = on_doc(h, doc.uid, true, |h| { + let (doc, into) = items_scope(h, a)?; + make_in(h, doc, into, |h| { let unpainted = { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() @@ -524,10 +613,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } Ok(id) - })?; - let s = h.session.borrow(); - let st = s.documents().iter().find(|d| d.uid == doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?; - Ok(super::item_ref(h, st, made)) + }) } // ---- PathItem geometry ---- diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index ea3e0ac497..fb7239394a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1597,6 +1597,123 @@ fn a_layers_and_a_groups_lists_give_the_topmost_object_first() { assert_eq!(out, [json!("GroupItem"), json!("CompoundPathItem"), json!(70), json!(50), json!("E"), json!("E"), json!(30)]); } +#[test] +fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost_first() { + let (mut s, _, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 70.0, 20.0); + s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + // The layer holds `a` (30 pt wide) and a group of `b` (50 pt wide) and `c` (70 pt wide); the + // document's list holds all three, the layer's only `a`, and a sublayer's path is its own. + let out = log( + &mut s, + "var d = app.activeDocument, L = d.layers[0], g = L.groupItems[0], P = L.pathItems, G = g.pathItems;\ + vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ + vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ + var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ + vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + ); + let expected = + [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; + assert_eq!(out[..11], expected); + assert_eq!(out[11..], [json!(false), json!(true)]); +} + +#[test] +fn a_loop_over_a_groups_path_items_builds_the_list_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ids: Vec = (0..1000).map(|i| rect(&mut s, f64::from(i % 40) * 10.0, 10.0, 5.0, 5.0).0).collect(); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + // Reading `length` and `[i]` 1,000 times each stays within 512 KiB of data only when the list + // of 1,000 paths is not built again for each read. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 19))); + let r = run(&mut s, "var P = app.activeDocument.groupItems[0].pathItems, n = 0; for (var i = 0; i < P.length; i++) if (P[i]) n++; vc.log(n);"); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + assert_eq!(r.unwrap()["log"], json!([1000])); +} + +#[test] +fn a_layers_path_items_make_their_paths_on_top_of_that_layer() { + let (mut s, ..) = doc(); + let bottom = s.active().unwrap().doc.layers[0].id; + let selected = s.active().unwrap().selection.clone(); + let steps = undo_steps(&s); + // A new layer becomes the current one; each creator of the first layer's `pathItems` still + // puts its path on top of that layer. + let out = log( + &mut s, + "var d = app.activeDocument, top = d.layers.add(), L = d.layers[1], P = L.pathItems;\ + var make = [function () { return P.rectangle(100, 100, 20, 10); }, function () { return P.roundedRectangle(100, 100, 20, 10); },\ + function () { return P.ellipse(); }, function () { return P.polygon(); }, function () { return P.star(); }, function () { return P.add(); }];\ + for (var i = 0; i < make.length; i++) { var p = make[i](); p.name = 'm' + i; vc.log(p.layer.name === L.name); vc.log(L.pageItems[0].name); }\ + vc.log(d.activeLayer.name === top.name); vc.log(top.pageItems.length); vc.log(P.length);", + ); + let mut expected = Vec::new(); + for i in 0..6 { + expected.extend([json!(true), json!(format!("m{i}"))]); + } + expected.extend([json!(true), json!(0), json!(8)]); + assert_eq!(out, expected); + assert_eq!(undo_steps(&s), steps + 1); + let st = s.active().unwrap(); + let kids = st.doc.node(bottom).unwrap().children().unwrap(); + assert_eq!(kids.last().unwrap().name.as_deref(), Some("m5")); + assert!(st.selection == selected); +} + +#[test] +fn a_groups_path_items_add_puts_the_path_in_the_group() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let steps = undo_steps(&s); + let before = format!("{:?}", s.active().unwrap().doc.layers); + let out = log( + &mut s, + "var g = app.activeDocument.groupItems[0], n = g.pathItems.add(); n.name = 'N';\ + vc.log(n.parent.typename); vc.log(g.pageItems[0].name); vc.log(n.pathPoints.length);\ + var r = g.pathItems.rectangle(50, 50, 10, 10); r.name = 'R'; vc.log(g.pathItems[0].name); vc.log(g.pathItems.length);", + ); + assert_eq!(out, [json!("GroupItem"), json!("N"), json!(0), json!("R"), json!(4)]); + assert_eq!(undo_steps(&s), steps + 1); + let d = &s.active().unwrap().doc; + let top: Vec> = d.node(gid).unwrap().children().unwrap().iter().rev().take(2).map(|n| n.name.as_deref()).collect(); + assert_eq!(top, [Some("R"), Some("N")]); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); +} + +#[test] +fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { + const REFUSED: &str = "Cannot add a path to a hidden or locked layer or group"; + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let gid = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.none", &json!({})).unwrap(); + let lid = s.active().unwrap().doc.layers[0].id; + let before = format!("{:?}", s.active().unwrap().doc.layers); + s.execute("layer.setProps", &json!({"id": lid.0, "locked": true})).unwrap(); + let locked = format!("{:?}", s.active().unwrap().doc.layers); + for src in ["app.activeDocument.layers[0].pathItems.rectangle(10, 10, 5, 5);", "app.activeDocument.layers[0].pathItems.add();"] { + assert!(failure(&mut s, src).contains(REFUSED), "{src}"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); + } + s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); + let hidden = format!("{:?}", s.active().unwrap().doc.layers); + assert!(failure(&mut s, "app.activeDocument.groupItems[0].pathItems.ellipse();").contains(REFUSED)); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), hidden); + s.execute("layer.setProps", &json!({"id": gid.0, "visible": true})).unwrap(); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before); + // A group's `pathItems` read after the group is gone throw. + let msg = failure(&mut s, "var g = app.activeDocument.groupItems[0], P = g.pathItems; g.remove(); P.length;"); + assert!(msg.contains("Stale page item"), "{msg}"); +} + #[test] fn compound_path_items_add_makes_an_empty_compound_path_that_takes_paths() { let (mut s, a, b) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 563f23db6f..cc604a7bc4 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -108,7 +108,7 @@ const INSIDE: &[(&str, &str)] = &[ "Layer.prototype.", "artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \ dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \ - locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \ + locked= move name name= opacity opacity= pageItems parent pathItems placedItems placedItems= preview \ preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \ textFrames= typename visible visible= zOrder zOrderPosition", ), @@ -117,7 +117,7 @@ const INSIDE: &[(&str, &str)] = &[ ("GroupItem.", "prototype"), ( "GroupItem.prototype.", - "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \ + "clipped clipped= compoundPathItems constructor groupItems pageItems pathItems placedItems placedItems= \ rasterItems rasterItems= symbolItems symbolItems= textFrames textFrames=", ), ("GroupItems.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 6a58f9712c..899b7f5563 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2707,12 +2707,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs `layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`, `visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`, - `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`, - `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run + `layers`, `pageItems`, `groupItems`, `compoundPathItems`, `pathItems`, `zOrderPosition`, `hasSelectedArtwork`, + `isIsolated`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run `layer.setProps`, and `opacity` runs `object.setProps`. `move` and `zOrder` run `node.move`; a layer goes into another layer, to the top level of the document, or directly above or below another layer. Every page item has `layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has - `clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem` + `clipped`, `pageItems`, `groupItems`, `compoundPathItems` and `pathItems`, and a `CompoundPathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`. @@ -2757,8 +2757,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot run leaves it). The report also lists a document whose active artboard has another index when the run ends because artboards were inserted, removed or reordered before it. An index outside the list throws a `RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws - `Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and - `GroupItems.createFromFile` throw an error that says they are not available yet. + `Stale artboard`. `Layer.blendingMode`, `artworkKnockout` and `sliced` and `GroupItems.createFromFile` throw an + error that says they are not available yet. - `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`; default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and @@ -2777,7 +2777,15 @@ app through the global object `vc`, and writes to the Script Console and runs ot radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`, `shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing - mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item + mode, which stays as it was. A layer's and a group's `pathItems` + (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) + have the same members, and their `parent` is that layer or group. Their `add()` and shape creators put the new path + on top of that layer's or group's contents, with the current layer left as it was: the path is made with the + container's layer as the current one (`layer.setCurrent`) and, for a group, moved into it with `node.move`, in the + run's one undo step. VectorCraft's own rules: a layer's or group's `pathItems` list the paths directly in it, + topmost first, leaving out paths in its groups, compound paths and sublayers; a layer or group that is hidden or + locked, or that is in a hidden or locked layer or group, throws `Cannot add a path to a hidden or locked layer or + group` and no path is made. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`, `guides`, `clipping`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`, `stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to 500), `strokeDashes`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3796a198aa..3339695f64 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,7 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). Views are not there yet. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`. - - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`, `crates/engine/src/tests/script_dom.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 037a01b5210e2add20ed06eb608510faf31f0a22 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:49:29 -0800 Subject: [PATCH 013/334] Scripts: update() checks each waiting palette event against the palette as handlers left it update() takes the events that wait for the run's palettes one at a time. Before each one, the host now gets every palette's controls as the script and the earlier handlers left them, as at the end of a run, so a click on a control that an earlier handler disabled, hid or removed runs no handler and is dropped. The new host function palettePending says whether an event still waits. An update() that a getter or a handler calls while events are being taken takes none itself; the update() already taking them goes on with the next one, instead of calling itself until a limit stops the run. Docs: docs/mcp.md palette bullet. --- crates/engine/src/script/palettes.rs | 6 ++++ crates/engine/src/script/scriptui.rs | 8 +++++ crates/engine/src/tests/script_palettes.rs | 26 ++++++++++++++++ crates/js/src/scriptui.rs | 34 ++++++++++++++++++-- crates/js/src/scriptui_tests.rs | 36 +++++++++++++++++++--- docs/mcp.md | 4 ++- 6 files changed, 107 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/palettes.rs b/crates/engine/src/script/palettes.rs index 68c84e3f0d..b06dae36fa 100644 --- a/crates/engine/src/script/palettes.rs +++ b/crates/engine/src/script/palettes.rs @@ -240,6 +240,12 @@ impl Palettes { pub(crate) fn take_for(&mut self, engine: &str) -> Option { self.next_of(engine).map(|(_, q)| q) } + + /// 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.waiting.iter().any(|q| 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. diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index e460408a51..dc4bbf3bc5 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -714,6 +714,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("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)), ]) } @@ -776,6 +777,13 @@ fn palette_take(host: &Host, _: &[Data]) -> Result { Ok(taken.map_or(Data::Null, event_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`. +fn palette_pending(host: &Host, _: &[Data]) -> Result { + 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 { let engine = palette_engine(host)?.to_string(); if let Some(id) = palette_id(args.first()) { diff --git a/crates/engine/src/tests/script_palettes.rs b/crates/engine/src/tests/script_palettes.rs index eff97479d1..54de688f93 100644 --- a/crates/engine/src/tests/script_palettes.rs +++ b/crates/engine/src/tests/script_palettes.rs @@ -140,6 +140,32 @@ fn update_hands_a_click_given_during_the_run_to_its_handler_so_cancel_stops_the_ TEST_ELAPSED.set(None); } +#[test] +fn update_drops_a_waiting_click_on_a_control_an_earlier_handler_disabled() { + TEST_ELAPSED.set(Some(Duration::ZERO)); + let mut s = one_doc(); + s.script_frames = true; + let source = "#targetengine progress\nvar p = new Window('palette'); var stop = p.add('button', undefined, 'Stop'); \ + var other = p.add('button', undefined, 'Other'); var stopped = false; var log = []; \ + stop.onClick = function () { stopped = true; other.enabled = false; log.push('stop'); }; \ + other.onClick = function () { log.push('other'); }; \ + p.show(); var k = 0; while (!stopped && k < 100000) { k++; p.update(); } vc.log(log.join());"; + assert_eq!(run(&mut s, source).unwrap()["running"], true); + for _ in 0..100 { + if !s.script_palettes().is_empty() { + break; + } + assert!(s.script_pump().is_none(), "the run pauses at the first update()"); + } + let id = only_palette(&s); + assert_eq!(s.script_palette_event(id, UiEvent::Click(1)), Ok(Waiting::Added)); + assert_eq!(s.script_palette_event(id, UiEvent::Click(2)), Ok(Waiting::Added)); + let report = pump(&mut s).expect("the run ended").unwrap(); + assert_eq!(report["log"], json!(["stop"]), "the click on the disabled button runs no handler: {report}"); + assert_eq!(s.script_palette_events_waiting(), 0, "the click on the disabled button is dropped"); + TEST_ELAPSED.set(None); +} + #[test] fn update_in_a_handler_does_not_pause_the_run() { TEST_ELAPSED.set(Some(Duration::ZERO)); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 2d2ccf2e9a..4a13c7c835 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -35,7 +35,8 @@ //! palette does the same for that palette, so the host's list of its controls stays in step. //! `update()` on a shown palette, or on a `group` or a `panel` in one, takes each event that waits //! for a palette of the run's engine from the host's `paletteTake` (as `paletteEvent` gives it, or -//! `null`) and gives it to its palette. Then, called from the script's own code (not from a +//! `null`) and gives it to its palette, while the host's `palettePending` says one waits, giving +//! `paletteUpdate` each palette's description before each one. Then, called from the script's own code (not from a //! handler, a callback of a built-in function, a getter or a conversion), it asks the host's //! `paletteDraw` whether the palette is drawn now, and when it is, gives `paletteUpdate` the //! palette's description. On the showing dialog, or a group or panel in it, `update()` does @@ -104,6 +105,8 @@ pub(crate) struct Classes { selection_set: ObjId, showing: Option, palettes: Vec, + /// Whether an `update()` is taking the waiting events ([`take_waiting`]). + taking: bool, } impl Classes { @@ -750,10 +753,36 @@ fn update_window(i: &mut Interp, win: ObjId, palette: bool, own: bool) -> JsResu Ok(()) } -/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits. +/// Hands each event the host's `paletteTake` gives, oldest first, to its palette, until none waits +/// (`palettePending`). Before each one the host gets every palette's controls as the script and the +/// handlers before it left them, as at the end of a run, and drops an event whose control has since +/// been disabled, hidden or removed. An `update()` that a getter or a handler calls meanwhile takes +/// no events: the `update()` already taking them goes on with the next one. fn take_waiting(i: &mut Interp) -> JsResult<()> { + if i.script_ui.as_ref().is_some_and(|c| c.taking) { + return Ok(()); + } + set_taking(i, true); + let r = take_each(i); + set_taking(i, false); + r +} + +fn set_taking(i: &mut Interp, taking: bool) { + if let Some(c) = i.script_ui.as_mut() { + c.taking = taking; + } +} + +/// [`take_waiting`]'s loop. +fn take_each(i: &mut Interp) -> JsResult<()> { + let pending = host_fn(i, "palettePending")?; let f = host_fn(i, "paletteTake")?; loop { + if !i.call(&pending, &Value::Undefined, &[])?.truthy() { + return Ok(()); + } + update_palettes(i)?; let answer = i.call(&f, &Value::Undefined, &[])?; if answer.as_object().is_none() { return Ok(()); @@ -1496,6 +1525,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul selection_set, showing: None, palettes: Vec::new(), + taking: false, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 355faee1cf..4dcf1a3ed5 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -384,7 +384,8 @@ fn palette_realm(events: Vec) -> (Realm, Calls) { } /// [`palette_realm`], whose `paletteTake` also gives the events in `taken`, in order, then `null`, -/// and whose `paletteDraw` gives the answers in `draws`, in order, then `false`. +/// 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, taken: Vec, draws: Vec) -> (Realm, Calls) { let mut r = Realm::new(); r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); @@ -409,11 +410,17 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> Ok(Data::Number(id)) }); let event: HostFunction = Rc::new(move |_| Ok(events.borrow_mut().pop_front().unwrap_or(Data::Null))); - let taken = RefCell::new(VecDeque::from(taken)); + 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(taken.borrow_mut().pop_front().unwrap_or(Data::Null)) + 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(); @@ -433,6 +440,7 @@ fn palette_realm_with(events: Vec, taken: Vec, draws: Vec) -> ("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(); @@ -533,7 +541,27 @@ fn update_hands_a_waiting_click_to_the_palette_so_a_cancel_button_stops_a_loop() ) .unwrap(); assert_eq!(done, JsValue::String("1:true".into()), "the first update() runs the click's onClick"); - assert!(count(&calls, "paletteTake") >= 2, "update() takes events until none waits"); + 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] diff --git a/docs/mcp.md b/docs/mcp.md index 941a86437c..3623c6e560 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2993,7 +2993,9 @@ the same controls, handlers and limits: `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/). - Those events do not wait for runs of their own. In the app, an `update()` in the script's own code then + Those events do not wait for runs of their own. 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 From 38937a1c0f6a835884c3920b493fa7abadf8cbb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:21:19 -0800 Subject: [PATCH 014/334] Scripts: a palette text the full event line refuses stays in its field When 64 palette events already wait, a text change from an edit field is refused. The text had already been taken out of the field's draft, so the next frame showed the script's old text and what the person typed was lost. The refused text now goes back in its field, and the clicks and closes given after a refused change in the same frame are not put in line, so no handler runs without the change before it. --- crates/ui-egui/src/dialogs/script_window.rs | 5 +++ crates/ui-egui/src/script_palettes.rs | 31 +++++++++++++---- crates/ui-egui/src/tests/script_palettes.rs | 37 +++++++++++++++++++-- 3 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 78e130bab2..69926adf4b 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -233,6 +233,11 @@ pub(crate) fn keep_refused_texts(w: &ScriptUiDialog, d: &mut Dialog, events: &mu refused } +/// Puts `text` back in the edit field `i` of the dialog's drafts `d`, as typed and not given yet. +pub(crate) fn keep_draft(d: &mut Dialog, i: usize, text: &str) { + d.fields.insert(draft_key(i), json!(text)); +} + /// The field that holds an edit field's text while it is typed. fn draft_key(i: usize) -> String { format!("text{i}") diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index ec2e8773dd..8ad4354dac 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -5,10 +5,11 @@ //! is going ([`crate::script_runs::poll`]); 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 stays in its field with the error in the status bar. +//! 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. use serde_json::json; -use vectorcraft_engine::script::{ScriptPalette, UiEvent}; +use vectorcraft_engine::script::{ScriptPalette, UiEvent, UiValue}; use crate::VectorcraftApp; use crate::dialogs::script_window; @@ -49,8 +50,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { events.push(UiEvent::Close); } drafted(app, &p, &mut drafts, &mut events); + give(app, ctx, p.id, &mut drafts, events); keep_drafts(ctx, &p, drafts); - give(app, ctx, p.id, events); } } @@ -83,13 +84,31 @@ pub(crate) fn drafted(app: &mut VectorcraftApp, p: &ScriptPalette, drafts: &mut } } -/// Puts the events the person gave the palette `id` in line, or shows why one was refused. -pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, events: Vec) { +/// Puts the events the person gave the palette `id` 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. +pub(crate) fn give(app: &mut VectorcraftApp, ctx: &egui::Context, id: u64, drafts: &mut Dialog, events: Vec) { + let mut change_refused = false; 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(id, e) { // The next frame starts its run. Ok(_) => ctx.request_repaint(), - Err(e) => app.status(e), + Err(error) => { + if let Some((i, text)) = change { + if let Some(text) = text { + script_window::keep_draft(drafts, i, &text); + } + change_refused = true; + } + app.status(error); + } } } } diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index b02fc382b2..f467004f6d 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -16,6 +16,11 @@ fn app() -> VectorcraftApp { app } +/// No text typed in a palette's fields. +fn drafts() -> Dialog { + Dialog::new(script_window::KIND, json!({})) +} + fn run_to_end(app: &mut VectorcraftApp) { for _ in 0..10_000 { if !app.session.script_running() { @@ -53,7 +58,10 @@ fn a_click_on_a_palette_asks_for_the_frame_that_starts_its_run() { frame(&ctx, |_| {}); } assert!(!frame(&ctx, |_| {}), "an idle frame asks for no other"); - assert!(frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])), "the click asks for the next frame"); + assert!( + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])), + "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); @@ -78,7 +86,7 @@ fn a_click_waiting_behind_a_run_at_its_dialog_asks_for_no_frames() { } assert!(app.session.script_dialog().is_some(), "the run waits at its confirm"); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut asks = true; for _ in 0..5 { @@ -102,7 +110,7 @@ fn a_click_waiting_for_an_open_undo_group_asks_for_no_frames_and_runs_after_it() let id = app.session.script_palettes()[0].id; app.run("edit.undoGroup.begin", json!({})).unwrap(); let ctx = egui::Context::default(); - frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, vec![UiEvent::Click(1)])); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), vec![UiEvent::Click(1)])); assert_eq!(app.session.script_palette_events_waiting(), 1); let mut delay = std::time::Duration::ZERO; for _ in 0..5 { @@ -146,6 +154,29 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { assert!(!drafts.fields.contains_key("text3")); } +#[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();" + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "p.js"})).unwrap().unwrap(); + run_to_end(&mut app); + let id = app.session.script_palettes()[0].id; + let ctx = egui::Context::default(); + let fill: Vec = (3..3 + MAX_WAITING).map(UiEvent::Click).collect(); + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut drafts(), fill.clone())); + assert_eq!(app.session.script_palette_events_waiting(), MAX_WAITING, "the line is full"); + let mut typed = drafts(); + let events = vec![UiEvent::Change(1, UiValue::Text("typed".into())), UiEvent::Click(2)]; + frame(&ctx, |ui| script_palettes::give(&mut app, ui.ctx(), id, &mut typed, events.clone())); + assert_eq!(typed.fields.get("text1"), Some(&json!("typed")), "the refused text goes back in its field: {:?}", typed.fields); + 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(); From 58292d605af4e21822b7f4d0bcf7aa94a2a2838e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 02:23:19 -0800 Subject: [PATCH 015/334] Scripts: app.showColorPicker asks for a color app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor and returns the color picked for OK. Cancel, and OK with the color unchanged, return a new object of the color the script gave. Anything else throws a TypeError. - In the app the run waits at the picker, which previews nothing on the selection. Stop and quitting end the run as at the other script dialogs and close the picker. - A run with nobody to ask takes {kind: "colorPicker", value: color | null} from answers. The report lists the picker with the color it opened on and the answer. - script.run's params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe it. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 112 +++++++++++++++++---- crates/engine/src/script/dom.rs | 10 ++ crates/engine/src/script/dom/colors.rs | 14 ++- crates/engine/src/tests/script_dialogs.rs | 72 +++++++++++++ crates/ui-egui/src/dialogs/color_picker.rs | 99 +++++++++++++----- crates/ui-egui/src/dialogs/script_run.rs | 26 ++++- crates/ui-egui/src/script_runs.rs | 17 +++- crates/ui-egui/src/tests/script_dialogs.rs | 107 +++++++++++++++++++- docs/mcp.md | 18 +++- docs/target-app-parity.md | 1 + 11 files changed, 425 insertions(+), 53 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 2640433606..56bf96195f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|colorPicker, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | a color as paint.setFill takes it, or null (colorPicker)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; app.showColorPicker(color) opens the Color Picker on an RGBColor, CMYKColor, GrayColor or LabColor (anything else throws a TypeError) and returns the color picked for OK (in the app an RGB pick is CMYK in a CMYK document), or a new object of the color given for Cancel and for OK with the color unchanged; it waits and takes answers as the dialogs above do, and has no Stop button; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"} or {kind: \"colorPicker\", color, answer: a color | null | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..afda864f6a 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -5,12 +5,14 @@ //! it is left out or `undefined` ([`DEFAULT_TITLE`]), and `errorIcon` and `noAsDflt` as the //! boolean `Boolean(value)` gives. `alert` returns `undefined`, `confirm` `true` for Yes and //! `false` for No, and `prompt` the text in its field for OK and `null` for Cancel. +//! `app.showColorPicker(color)` ([`show_color_picker`]) opens the Color Picker on a color and +//! returns the color picked for OK, or a new object of the color it was given for Cancel. //! //! In the app the run waits at the call for the person's answer, and spends no fuel while it -//! waits; every dialog also has Stop, which ends the run and puts everything back. A run with -//! nobody to ask takes its answers, in order, from `script.run`'s `answers`; a call with no -//! answer left, or with the next answer for another kind of dialog, ends the run. The report's -//! `dialogs` lists each dialog and its answer. +//! waits; every dialog but the Color Picker also has Stop, which ends the run and puts +//! everything back. A run with nobody to ask takes its answers, in order, from `script.run`'s +//! `answers`; a call with no answer left, or with the next answer for another kind of dialog, +//! ends the run. The report's `dialogs` lists each dialog and its answer. //! //! The values here are VectorCraft's own limits: [`MAX_MESSAGE_BYTES`], [`MAX_TITLE_BYTES`], //! [`MAX_PROMPT_BYTES`], [`MAX_ANSWERS`], [`MAX_ANSWERS_BYTES`], [`MAX_RECORDS`] and @@ -21,6 +23,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; +use vectorcraft_color::Color; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; use super::{Host, console}; @@ -48,21 +51,33 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// `app.showColorPicker`. + ColorPicker, } impl DialogKind { - /// The function's name, which is also the `kind` of an answer and of a report's dialog. + /// The `kind` of an answer and of a report's dialog, which is also the function's name for + /// `alert`, `confirm` and `prompt`. pub fn id(self) -> &'static str { match self { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::ColorPicker => "colorPicker", + } + } + + /// The function's name, as its errors give it. + fn function(self) -> &'static str { + match self { + Self::ColorPicker => "showColorPicker", + k => k.id(), } } } /// A dialog a script opened, which waits for its answer. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub struct ScriptDialog { pub kind: DialogKind, pub message: String, @@ -74,10 +89,12 @@ pub struct ScriptDialog { pub no_as_default: bool, /// `prompt`: the text its field starts with. pub preset: String, + /// `showColorPicker`: the color the picker starts with. `None` for the other dialogs. + pub color: Option, } /// The answer to a [`ScriptDialog`]. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq)] pub enum DialogAnswer { /// OK, for `alert`. Ok, @@ -85,6 +102,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// OK with the color picked, or Cancel (`None`), for `showColorPicker`. + ColorPicker(Option), } impl DialogAnswer { @@ -93,29 +112,51 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::ColorPicker(_) => DialogKind::ColorPicker, } } - /// What the function returns. - fn data(&self) -> Data { + /// What the function returns for dialog `d`: for Cancel in the Color Picker, the color it + /// started with. + fn data(&self, d: &ScriptDialog) -> Data { match self { Self::Ok => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, + Self::ColorPicker(picked) => picked.or(d.color).as_ref().map_or(Data::Null, super::dom::color_data), } } - /// The answer as a report gives it: `"ok"`, a boolean, a string or `null`. + /// The answer as a report gives it: `"ok"`, a boolean, a string, a color as the paint commands + /// take it, or `null`. fn json(&self) -> Value { match self { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::ColorPicker(c) => c.as_ref().map_or(Value::Null, color_json), } } } +/// `c` as the paint commands take it. +fn color_json(c: &Color) -> Value { + serde_json::to_value(c).unwrap_or(Value::Null) +} + +/// Are `c`'s components in their ranges: 0 to 1, and for Lab, L from 0 to 100 and a and b from +/// -128 to 128, as a script's `LabColor` takes them? +fn in_range(c: &Color) -> bool { + let unit = |v: &[f32]| v.iter().all(|x| (0.0..=1.0).contains(x)); + match *c { + Color::Rgb { r, g, b } => unit(&[r, g, b]), + Color::Cmyk { c, m, y, k } => unit(&[c, m, y, k]), + Color::Gray { k } => unit(&[k]), + Color::Lab { l, a, b } => (0.0..=100.0).contains(&l) && [a, b].iter().all(|x| (-128.0..=128.0).contains(x)), + } +} + /// `text` as a dialog shows it. With `lines`, a line feed, a carriage return or the two together /// is a line break; every other control character, and with `lines` false every line break too, /// shows as its Unicode Control Picture, as the Script Console shows it. @@ -148,7 +189,8 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "colorPicker", value: color | +/// null}`, the color in any form the paint commands take. An empty object, which the parameter /// took before dialogs existed, is an empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { @@ -180,7 +222,12 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + (Some("colorPicker"), Value::Null) => Ok(DialogAnswer::ColorPicker(None)), + (Some("colorPicker"), v) => match crate::cmd::color_value(v).filter(in_range) { + Some(c) => Ok(DialogAnswer::ColorPicker(Some(c))), + None => Err("is a color picker's answer, whose `value` must be a color or null"), + }, + _ => Err("must have `kind` alert, confirm, prompt or colorPicker"), } } @@ -245,8 +292,9 @@ impl Dialogs { 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()); + let data = answer.data(d); *waiting = None; - if let Err(e) = realm.answer(answer.data()) { + if let Err(e) = realm.answer(data) { *self.failed.borrow_mut() = Some(e); } true @@ -263,12 +311,15 @@ impl Dialogs { self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); - r.insert("message".into(), json!(d.message)); - r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + if d.kind != DialogKind::ColorPicker { + r.insert("message".into(), json!(d.message)); + r.insert("title".into(), json!(d.title.as_deref().unwrap_or(DEFAULT_TITLE))); + } match d.kind { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::ColorPicker => r.insert("color".into(), d.color.as_ref().map_or(Value::Null, color_json)), }; r.insert("answer".into(), answer); let r = Value::Object(r); @@ -319,7 +370,8 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result host.charge_call(args.iter().map(super::data_size).sum())?; let Some(message) = text(args, 0) else { return Err(HostError::Type(format!("{name}: give a message"))) }; let (title, error_icon, no_as_default, preset) = match kind { - DialogKind::Alert => (text(args, 1), flag(args, 2), false, String::new()), + // `showColorPicker` opens through `show_color_picker`, not here. + DialogKind::Alert | DialogKind::ColorPicker => (text(args, 1), flag(args, 2), false, String::new()), DialogKind::Confirm => (text(args, 2), false, flag(args, 1), String::new()), DialogKind::Prompt => { let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; @@ -335,7 +387,29 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result if preset.len() > MAX_PROMPT_BYTES { return Err(HostError::Range(format!("{name}: the text the field starts with is longer than 16 KiB"))); } - let dialog = ScriptDialog { kind, message, title, error_icon, no_as_default, preset }; + wait_or_answer(host, ScriptDialog { kind, message, title, error_icon, no_as_default, preset, color: None }) +} + +/// `app.showColorPicker(color)`: the Color Picker on `color`. It returns the color picked for OK, +/// and a new object of `color` for Cancel. +pub(super) fn show_color_picker(host: &Host, color: Color) -> Result { + let dialog = ScriptDialog { + kind: DialogKind::ColorPicker, + message: String::new(), + title: None, + error_icon: false, + no_as_default: false, + preset: String::new(), + color: Some(color), + }; + wait_or_answer(host, dialog) +} + +/// Opens `dialog`: in the app the run waits at it, and a run with nobody to ask takes the next of +/// `answers`. +fn wait_or_answer(host: &Host, dialog: ScriptDialog) -> Result { + let kind = dialog.kind; + let name = kind.function(); let d = &host.dialogs; if d.framed { if !d.can_wait.get() { @@ -350,11 +424,11 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result match next { Some(a) if a.kind() == kind => { d.record(&dialog, a.json()); - Ok(a.data()) + Ok(a.data(&dialog)) } Some(a) => { d.record(&dialog, json!("missing")); - Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {name}", a.kind().id()))) + Err(HostError::Abort(format!("{name}: the next answer in `answers` is for {}, not {}", a.kind().id(), kind.id()))) } None => { d.record(&dialog, json!("missing")); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 8b2267a5d8..0a7eb82ef5 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -41,6 +41,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; mod paths; +pub(super) use colors::of_color as color_data; + /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; /// The error for an object that was deleted, or that came from an earlier run. @@ -691,6 +693,13 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } +/// `app.showColorPicker(color)`: the Color Picker on `color`, which must be an `RGBColor`, +/// `CMYKColor`, `GrayColor` or `LabColor` ([`super::dialogs::show_color_picker`]). +fn app_show_color_picker(h: &Host, a: &[Data]) -> Answer { + let color = colors::solid(arg(a, 1), "showColorPicker's color")?; + super::dialogs::show_color_picker(h, color) +} + /// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter /// or a `\`) letters in one case. fn path_key(p: &str) -> String { @@ -1883,6 +1892,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("selection", get(l, app_selection)), ("coordinateSystem", property(l, app_coords, app_set_coords)), ("getIsFileOpen", method(l, app_is_open)), + ("showColorPicker", method(l, app_show_color_picker)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/dom/colors.rs b/crates/engine/src/script/dom/colors.rs index 34c1496054..da34e8cf31 100644 --- a/crates/engine/src/script/dom/colors.rs +++ b/crates/engine/src/script/dom/colors.rs @@ -66,7 +66,7 @@ fn shown(v: f32, scale: f64) -> f64 { } /// The color object for a solid color. -fn of_color(c: &Color) -> Data { +pub(in crate::script) fn of_color(c: &Color) -> Data { match *c { Color::Rgb { r, g, b } => color_object("RGBColor", &[("red", shown(r, 255.0)), ("green", shown(g, 255.0)), ("blue", shown(b, 255.0))]), Color::Cmyk { c, m, y, k } => color_object( @@ -131,6 +131,18 @@ pub(super) fn assigned(d: &Data, what: &str) -> std::result::Result std::result::Result { + let not_solid = || HostError::Type(format!("{what} must be an RGBColor, CMYKColor, GrayColor or LabColor")); + match assigned(d, what) { + Ok(Some(c)) => Ok(c), + // A NoColor, or one of the LATER classes, which `assigned` refuses with a plain error. + Ok(None) | Err(HostError::Error(_)) => Err(not_solid()), + Err(e) => Err(e), + } +} + /// `color` as `paint.setFill` and `paint.setStroke` take it. pub(super) fn param(color: &Color) -> Value { serde_json::to_value(color).unwrap_or(Value::Null) diff --git a/crates/engine/src/tests/script_dialogs.rs b/crates/engine/src/tests/script_dialogs.rs index baa8989208..aa373d09bb 100644 --- a/crates/engine/src/tests/script_dialogs.rs +++ b/crates/engine/src/tests/script_dialogs.rs @@ -177,6 +177,7 @@ fn a_framed_run_waits_at_each_dialog_and_takes_the_persons_answer() { error_icon: false, no_as_default: true, preset: String::new(), + color: None, }; assert_eq!(s.script_dialog(), Some(want)); assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); @@ -319,3 +320,74 @@ fn a_dialog_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("callback"), "{r}"); assert_eq!(r["dialogCount"], 0); } + +/// `showColorPicker` with an RGB red, the answer, and the run's log line for the color it returns. +const PICK_RED: &str = "var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join());"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_picked_color_from_answers() { + let mut s = one_doc(); + let source = format!("{PICK_RED} var g = new GrayColor(); g.gray = 40; var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join());"); + let r = headless(&mut s, &source, answers(&[json!({"kind": "colorPicker", "value": "#00FF00"}), json!({"kind": "colorPicker", "value": null})])) + .unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,255,0", "GrayColor,40"]), "OK gives the picked color, Cancel the color given: {r}"); + let dialogs = r["dialogs"].as_array().unwrap(); + assert_eq!(dialogs.len(), 2); + assert!(dialogs.iter().all(|d| d["kind"] == "colorPicker" && d["color"].is_object() && d.get("message").is_none()), "{r}"); + assert_eq!(dialogs[1]["answer"], Value::Null, "Cancel is listed as null"); + let cmyk = headless( + &mut s, + "var c = new CMYKColor(); c.cyan = 20; vc.log(app.showColorPicker(c).typename);", + answers(&[json!({"kind": "colorPicker", "value": {"c": 0, "m": 100, "y": 100, "k": 0}})]), + ) + .unwrap(); + assert_eq!(cmyk["log"], json!(["CMYKColor"]), "the picked color keeps its own model: {cmyk}"); +} + +#[test] +fn the_color_picker_ends_the_run_when_no_answer_is_left() { + let mut s = one_doc(); + let before = art(&s); + let edit = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + for (given, says) in [(json!([]), "no answer left"), (answers(&[json!({"kind": "prompt", "value": "x"})]), "is for prompt, not colorPicker")] { + let source = format!("{edit} try {{ {PICK_RED} }} catch (e) {{ vc.log('caught'); }}"); + let e = headless(&mut s, &source, given).unwrap_err().to_string(); + assert!(e.contains("showColorPicker") && e.contains(says), "{e}"); + assert_eq!(art(&s), before, "the run's edit goes back"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } + let a = headless(&mut s, "alert('x');", answers(&[json!({"kind": "colorPicker", "value": null})])).unwrap_err().to_string(); + assert!(a.contains("is for colorPicker, not alert"), "{a}"); +} + +#[test] +fn the_color_picker_refuses_what_is_not_a_solid_color() { + let mut s = one_doc(); + let source = "var out = []; [undefined, 'red', new NoColor(), {typename: 'SpotColor', tint: 100}].forEach(function (c) {\ + try { app.showColorPicker(c); out.push('opened'); } catch (e) { out.push(e.name); } });\ + try { var big = new RGBColor(); big.red = 300; app.showColorPicker(big); } catch (e) { out.push(e.name); } vc.log(out.join());"; + let r = headless(&mut s, source, json!([])).unwrap(); + assert_eq!(r["log"], json!(["TypeError,TypeError,TypeError,TypeError,RangeError"]), "{r}"); + assert_eq!(r["dialogCount"], 0, "no picker opened"); + for bad in [json!("not a color"), json!([255, 0, 0]), json!({"model": "lab", "l": 120, "a": 0, "b": 0}), json!(true)] { + let e = headless(&mut s, PICK_RED, answers(&[json!({"kind": "colorPicker", "value": bad})])).unwrap_err().to_string(); + assert!(e.contains("color picker's answer"), "{bad}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_the_color_picker() { + let mut s = one_doc(); + framed(&mut s, &format!("{PICK_RED} var q = app.showColorPicker(p); vc.log(q.green);")); + let d = s.script_dialog().unwrap(); + assert_eq!((d.kind, d.color), (DialogKind::ColorPicker, Some(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)))); + assert!(!s.script_answer(DialogAnswer::Ok), "an answer for another kind of dialog is refused"); + assert!(s.script_answer(DialogAnswer::ColorPicker(Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0))))); + assert!(pump(&mut s).is_none()); + assert_eq!(s.script_dialog().unwrap().color, Some(vectorcraft_color::Color::rgb(0.0, 0.0, 1.0)), "it opens on the color it is given"); + assert!(s.script_answer(DialogAnswer::ColorPicker(None))); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["RGBColor,0,0,255", 0]), "{r}"); +} diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index af1b318728..4060b26d40 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -27,6 +27,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::ColorMode; use vectorcraft_engine::cmd::color_value; use vectorcraft_engine::cmd::swatchlib; +use vectorcraft_engine::script::DialogAnswer; use super::preview::LivePreview; use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values}; @@ -45,6 +46,8 @@ pub(crate) enum Target { Artboard(usize), /// A colour row `key` of the open dialog `parent`. Answer { parent: DialogId, key: String }, + /// The answer to a running script's `app.showColorPicker`, which opened it on this colour. + Script(Color), } /// One open Color Picker: what the dialog itself does not know. @@ -152,28 +155,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { }; let dialogs = app.dialogs().ok_or("no window")?; let start = srgba(&color); - let mut dialog = ColorPickerDialog::new( - match (artboard, stroke) { - (Some(_), _) => "artboard", - (None, true) => "stroke", - (None, false) => "fill", - }, - tl!("Color Picker"), - start, - ) - .eyedropper(true) - .add_to_swatches(false) - .gamut(gamut(app)) - .working_rgb(WorkingRgb) - .swatch_view(swatch_view(app)); - if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) - && let Some(converter) = working_cmyk() - { - dialog = dialog.cmyk(&converter); - } - if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { - dialog = dialog.kept(model_values(&color)); - } + let key = match (artboard, stroke) { + (Some(_), _) => "artboard", + (None, true) => "stroke", + (None, false) => "fill", + }; + let mut dialog = picker(app, key, &color); // PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target. if let Some((i, _)) = artboard { dialog = dialog.instance(i); @@ -196,6 +183,58 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { Ok(Value::Null) } +/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's +/// swatches and libraries, and in a CMYK document the working CMYK inks. +fn picker(app: &VectorcraftApp, key: &str, color: &Color) -> ColorPickerDialog { + let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color)) + .eyedropper(true) + .add_to_swatches(false) + .gamut(gamut(app)) + .working_rgb(WorkingRgb) + .swatch_view(swatch_view(app)); + if app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk) + && let Some(converter) = working_cmyk() + { + dialog = dialog.cmyk(&converter); + } + if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) { + dialog = dialog.kept(model_values(color)); + } + dialog +} + +/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`. It +/// previews nothing; its OK and Cancel answer the run ([`finish`]). +pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color) { + let Some(dialogs) = app.dialogs() else { return }; + // The given colour's own values, so that OK can tell an untouched pick from another model's. + let dialog = picker(app, SCRIPT_KEY, &color).kept(model_values(&color)); + let id = dialogs.with(|h| h.open(dialog)); + app.color_dialogs.pickers.retain(|o| o.id != id); + app.color_dialogs.pickers.push(Open { id, target: Target::Script(color), start: srgba(&color), keep: false, preview: LivePreview::default() }); +} + +/// The key of the Color Picker a script opens. +pub(crate) const SCRIPT_KEY: &str = "script"; + +/// The id of the Color Picker a running script waits at, while it is open or its answer is not +/// yet given. +pub(crate) fn script_picker(app: &VectorcraftApp) -> Option { + app.color_dialogs.pickers.iter().find(|o| matches!(o.target, Target::Script(_))).map(|o| o.id) +} + +/// Closes the script's Color Picker once the run no longer waits at it, and drops its answer. +pub(crate) fn forget_script(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(id) = script_picker(app) else { return }; + app.color_dialogs.pickers.retain(|o| o.id != id); + if let Some(dialogs) = app.dialogs() { + dialogs.with(|h| { + h.cancel_by_id(ctx, id); + let _ = h.take_by_id::(id); + }); + } +} + /// Once per frame (after the shell pass): opens a picker for each dialog's colour request, previews /// each open picker's colour on the art, hands it the screen picks, and settles the ones that /// closed. @@ -259,6 +298,15 @@ fn finish( dialogs.with(|h| h.answer_color(*parent, key, r.picked.color)); } } + // OK on the colour it opened with, in the model it opened with, gives that colour back. + (Some(DialogResult::Ok(r)), Target::Script(given)) => { + let untouched = r.picked.color == open.start && r.picked.model == Some(model_values(given)); + let picked = if untouched { *given } else { in_document_model(app, color_of(&r.picked)) }; + app.session.script_answer(DialogAnswer::ColorPicker(Some(picked))); + } + (_, Target::Script(_)) => { + app.session.script_answer(DialogAnswer::ColorPicker(None)); + } (Some(DialogResult::Ok(r)), _) => { if let Err(e) = commit(app, open, preview, &r.picked) { app.status(e); @@ -273,7 +321,7 @@ fn paint_command(target: &Target, c: Color) -> (&'static str, Value) { match target { Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })), Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })), - Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })), + Target::Fill | Target::Answer { .. } | Target::Script(_) => ("paint.setFill", json!({ "color": color_json(&c) })), } } @@ -291,8 +339,9 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color { /// preview. Nothing previews until the colour first changes, nor without a selection (the colour /// then only becomes the default paint, on OK). An artboard shows it with or without a selection. fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) { - // A picker over a command dialog only fills a row; the dialog previews it. - if matches!(open.target, Target::Answer { .. }) { + // A picker over a command dialog only fills a row; the dialog previews it. A script's picker + // only answers the script. + if matches!(open.target, Target::Answer { .. } | Target::Script(_)) { return; } let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked))); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index ae13009775..65b7c92e1a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -29,6 +29,7 @@ use std::path::Path; +use craft::color_ui::ui::ColorPickerDialog; use craft::host::{PickRequest, Picked}; use craft::theme::variant::Tone; use craft::ui::buttons::Button; @@ -46,6 +47,7 @@ use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog}; +use super::color_picker; use crate::VectorcraftApp; use crate::file_asks::{self, Owner}; @@ -430,6 +432,22 @@ pub(crate) fn forget(app: &VectorcraftApp) { }); } +/// [`forget`] for the Color Picker a script's `app.showColorPicker` opened. +pub(crate) fn forget_color_picker(app: &mut VectorcraftApp) { + let Some(ctx) = app.ui_ctx.clone() else { return }; + if color_picker::script_picker(app).is_none() { + return; + } + let asking = with_host(app, |host, _| host.is_open::()).unwrap_or(false); + color_picker::forget_script(app, &ctx); + if asking { + with_host(app, |host, _| { + let _ = host.take::(); + host.open(close_question()); + }); + } +} + /// `ui.runScript`: the script at `path` or given as `source`; without either, pick a file. pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result { if p.get("path").is_some() || p.get("source").is_some() { @@ -514,8 +532,13 @@ pub(crate) fn open_picker(app: &VectorcraftApp, p: ScriptPicker) { /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { + let picker = color_picker::script_picker(app); with_host(app, |host, _| { - let own = host.get::().map(StackDialog::id).or_else(|| host.get::().map(StackDialog::id)); + let own = host + .get::() + .map(StackDialog::id) + .or_else(|| host.get::().map(StackDialog::id)) + .or_else(|| picker.filter(|&id| host.get_by_id::(id).is_some())); match own { Some(parent) if host.stack().is_top(parent) => { host.open_child(close_question(), parent); @@ -585,6 +608,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { crate::script_runs::failed(app, error); forget::(app); forget::(app); + forget_color_picker(app); app.sync_views(); } if with_host(app, |host, _| host.get_mut::().is_some_and(|d| std::mem::take(&mut d.choose))).unwrap_or(false) { diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index b08a8f2e93..e4f6303fab 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,9 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, `app.showColorPicker` or a `File` or `Folder` file dialog, waits +//! for the person's answer. + +use vectorcraft_engine::script::DialogKind; use crate::VectorcraftApp; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -47,13 +51,22 @@ fn ask(app: &mut VectorcraftApp) -> bool { } script_run::forget::(app); if let Some(dialog) = app.session.script_dialog() { - if !script_run::busy(app) { + if dialog.kind == DialogKind::ColorPicker { + // A picker that closed this frame answers the run in its own pump. + if color_picker::script_picker(app).is_none() + && !script_run::busy(app) + && let Some(color) = dialog.color + { + color_picker::open_for_script(app, color); + } + } else if !script_run::busy(app) { script_run::open_notice(app, &dialog); } return true; } // A run asked to stop no longer waits at its dialog. script_run::forget::(app); + script_run::forget_color_picker(app); if app.session.script_waiting() { if !script_run::busy(app) { script_run::open_growth(app); diff --git a/crates/ui-egui/src/tests/script_dialogs.rs b/crates/ui-egui/src/tests/script_dialogs.rs index 94e1bb9311..3417c5580b 100644 --- a/crates/ui-egui/src/tests/script_dialogs.rs +++ b/crates/ui-egui/src/tests/script_dialogs.rs @@ -1,12 +1,14 @@ //! A script's `alert`, `confirm` and `prompt` in the app: the dialog the run waits at, its buttons, //! Enter and Escape, Stop, another dialog in the way, quitting while it waits, and the same answers -//! given by a run with nobody to ask. The helpers over the dialog host are shared with the other -//! script tests. +//! given by a run with nobody to ask; and the Color Picker of `app.showColorPicker`. The helpers +//! over the dialog host are shared with the other script tests. +use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::ui::dialog::{DialogId, StackDialog, StandardPrompt}; use serde_json::{Value, json}; use vectorcraft_engine::Session; +use crate::dialogs::color_picker; use crate::dialogs::script_run::{self, CLOSE_KIND, CloseQuestion, NOTICE_KIND, ScriptNotice}; use crate::{VectorcraftApp, menus, script_runs}; @@ -315,3 +317,104 @@ fn the_app_and_a_run_with_nobody_to_ask_give_the_same_results() { assert_eq!(framed["dialogs"], headless["dialogs"]); assert_eq!(framed["log"], json!([true, "p", "done"])); } + +/// Is the Color Picker of the script's `app.showColorPicker` open? +fn picker_open(app: &VectorcraftApp) -> bool { + let id = color_picker::script_picker(app); + id.is_some_and(|id| script_run::with_host(app, |host, _| host.get_by_id::(id).is_some()).unwrap()) +} + +/// Polls the run until it ends, or until its Color Picker is open (true). +fn until_picker(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if picker_open(app) { + return true; + } + } + panic!("the script neither ended nor opened the Color Picker"); +} + +/// Answers the script's Color Picker with OK (or Cancel), then runs the frame's picker pump. +fn answer_picker(app: &mut VectorcraftApp, ok: bool) { + let id = color_picker::script_picker(app).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + let done = script_run::with_host(app, |host, ctx| if ok { host.confirm_by_id(ctx, id) } else { host.cancel_by_id(ctx, id) }).unwrap(); + assert!(done); + color_picker::pump(app, &ctx); +} + +#[test] +fn the_color_picker_waits_and_answers_the_run() { + let mut app = app(); + let gray = "var g = new GrayColor(); g.gray = 40;"; + start( + &mut app, + &format!( + "{DRAW} var c = new RGBColor(); c.red = 255; var p = app.showColorPicker(c); vc.log([p.typename, p.red, p.green, p.blue].join()); \ + {gray} var q = app.showColorPicker(g); vc.log([q.typename, q.gray].join()); var r = app.showColorPicker(g); vc.log([r.typename, r.gray].join());" + ), + ); + assert!(until_picker(&mut app)); + assert!(!is_open::(&app), "the picker opens in place of a notice"); + set(&app, color_picker::SCRIPT_KEY, "color", json!("#00ff00")).unwrap(); + let ctx = app.ui_ctx.clone().unwrap(); + color_picker::pump(&mut app, &ctx); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "the selection shows no preview"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app), "the next call opens the picker again"); + answer_picker(&mut app, true); + assert!(until_picker(&mut app)); + answer_picker(&mut app, false); + assert!(!until_picker(&mut app)); + assert_eq!( + log(&app), + json!(["RGBColor,0,255,0", "GrayColor,40", "GrayColor,40"]), + "OK gives the color picked, untouched its own color, Cancel the color given" + ); + assert_ne!(crate::panels::current_paints(&app).0.color().map(|c| c.to_hex()).as_deref(), Some("#00ff00"), "OK paints nothing"); + let dialogs = app.session.script_report().unwrap()["dialogs"].clone(); + assert_eq!(dialogs[2]["answer"], Value::Null, "Cancel is listed as null"); +} + +#[test] +fn the_same_color_set_in_another_model_is_a_new_pick() { + let mut app = app(); + start(&mut app, "var g = new GrayColor(); g.gray = 40; var p = app.showColorPicker(g); vc.log(p.typename);"); + assert!(until_picker(&mut app)); + // The gray's own sRGB, set as a plain color, as a screen sample sets one. + let open = app.color_dialogs.pickers.iter().find(|o| Some(o.id) == color_picker::script_picker(&app)).map(|o| (o.id, o.start)).unwrap(); + script_run::with_host(&app, |host, _| host.get_mut_by_id::(open.0).map(|d| d.set_color(PickedColor::rgb(open.1)))).unwrap(); + answer_picker(&mut app, true); + assert!(!until_picker(&mut app)); + assert_eq!(log(&app), json!(["RGBColor"]), "the same sRGB as a plain color is an RGB pick, not the gray the script gave"); +} + +#[test] +fn stopping_or_quitting_the_run_closes_its_color_picker() { + let source = format!("{DRAW} var c = new RGBColor(); app.showColorPicker(c); vc.log('after');"); + let mut app = app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + assert_eq!(app.run("script.stop", json!({})).unwrap()["stopped"], true); + assert!(!until_picker(&mut app)); + assert!(!picker_open(&app), "no picker is left for the stopped run"); + assert!(color_picker::script_picker(&app).is_none()); + assert_eq!(objects(&app), 0, "the run's edit goes back"); + assert_eq!(log(&app), json!([])); + let mut app = self::app(); + start(&mut app, &source); + assert!(until_picker(&mut app)); + script_run::ask_to_close(&mut app); + assert!(is_open::(&app), "quitting asks over the picker"); + cancel(&mut app, CLOSE_KIND); + assert!(picker_open(&app), "Cancel shows the picker again"); + script_run::ask_to_close(&mut app); + assert!(confirm(&mut app, CLOSE_KIND)); + assert!(!app.session.script_running()); + assert!(!picker_open(&app), "no picker is left for the abandoned run"); + assert_eq!(objects(&app), 0); +} diff --git a/docs/mcp.md b/docs/mcp.md index da2ab72029..5321b74f87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,7 +2667,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot - `vc.log(value)` adds a value to the report and a line to the Script Console. - `app` is the application object the help page https://ai-scripting.docsforadobe.dev/jsobjref/Application/ describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one), - `app.selection`, `app.coordinateSystem` and `app.getIsFileOpen(path)`. `app.documents` + `app.selection`, `app.coordinateSystem`, `app.getIsFileOpen(path)` and `app.showColorPicker(color)`, described + with the dialogs below. `app.documents` (https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)` and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`, which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of @@ -3048,7 +3049,9 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and + run ended at, or `"missing"` for a dialog `answers` had no answer for. `app.showColorPicker` is listed as `{kind: + "colorPicker", color, answer}`, with the color it opened on and the color picked, `null` for Cancel or + `"missing"`, each color as `paint.setFill` takes it. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list stopped at its limit. ```json @@ -3096,6 +3099,17 @@ left, when the next answer is for another kind of dialog, or when the script end and refuses any answers for a run in the app, where the person answers. An omitted `answers`, an empty list and an empty object are the same. +`app.showColorPicker(color)` opens the Color Picker on `color` and returns a color, as the type definitions at +https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it. `color` must be an `RGBColor`, +`CMYKColor`, `GrayColor` or `LabColor`; anything else throws a `TypeError`, and a component out of its range throws a +`RangeError`. The rest of this paragraph gives VectorCraft's own rules. OK returns the color picked; in a CMYK +document an RGB pick is returned as CMYK. OK with the color unchanged and Cancel return a new object of the color the +script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting +end the run as they do at the other dialogs, and close the picker. A run with nobody to ask takes `{kind: +"colorPicker", value: color}` from `answers`, with the color in any form `paint.setFill` takes, each component in its +range, or `{kind: "colorPicker", value: null}` for Cancel. In the app, the picker's dialog key is `script`, and +`ui.dialog.set` and `ui.dialog.confirm` answer it as they answer any Color Picker. + ```sh vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ff2ebf0bf4..864cff266f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1036,6 +1036,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops and the document's default paint are not there yet. `crates/engine/src/tests/script_dom_paths.rs`. + - Scripts: `app.showColorPicker(color)` opens the Color Picker on a script's color and the run waits for the person's pick, as the type definitions at https://www.indesignjs.de/indesignapi/illustrator/illustrator.d.ts describe it; OK returns the color picked, and Cancel a new object of the color given. A run with nobody to ask takes the pick from `answers` (`docs/mcp.md`). `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 80c33ec810298b6c1e65204ac378ac36b34b39ec Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:02:09 -0800 Subject: [PATCH 016/334] Scripts: fix review findings in the layer and path items - controlBounds takes in the paths' direction handles. A clipping group's are its clipping path's. - A compound path's pathItems is a PathItems collection: add() and the shape methods make the path inside it. - resize() scales and sets the stroke weight as one step, so a failed stroke change undoes the scale too. - A point change that adds or removes anchors deselects the path's direct-selected anchors, from a script and from path.setAnchors, so other anchors are not left selected in their place. - A script that ends past the allowance of the last answer is asked again before its changes are kept. - documents.addDocument starts from the built-in preset when a saved preset has its name, and Recent keeps the built-in preset's name. - Saved preset rows past the artboard limit read as the limit. - Host classes that do not fit the heap end with the heap limit. - Layers keep their list while the document is unchanged, and getByName charges its scan on a kept list too. - Selection ids are deduplicated with a set. - A path made on the current layer is made in one step, so a failed stroke or reversal after it undoes the path too. - Path points are found through a kept index of where each subpath's points start, rebuilt when the path's points change, so reading every point of a path with many subpaths is no longer quadratic. - A pixel-aligned compound path snaps a path moved into it. --- crates/engine/src/cmd/layer.rs | 12 +- crates/engine/src/cmd/newdoc.rs | 10 +- crates/engine/src/cmd/path.rs | 13 +- crates/engine/src/script/dom.rs | 88 +++++++++++- crates/engine/src/script/dom/layers.rs | 56 ++++++-- crates/engine/src/script/dom/paths.rs | 152 +++++++++++++++----- crates/engine/src/script/mod.rs | 10 ++ crates/engine/src/tests/newdoc.rs | 16 +++ crates/engine/src/tests/script_dom.rs | 74 +++++++++- crates/engine/src/tests/script_dom_paths.rs | 94 ++++++++++++ crates/engine/src/tests/script_run.rs | 54 +++++++ crates/js/src/host_classes.rs | 3 +- crates/js/src/host_tests.rs | 11 ++ crates/ui-egui/src/dialogs/new_document.rs | 16 +++ docs/mcp.md | 7 +- 15 files changed, 549 insertions(+), 67 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 9fe8d9e678..67f6cee727 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -956,7 +956,8 @@ fn move_node(s: &mut Session, p: &Value) -> Result { } // A path in a compound path keeps no paint, live shape or pixel alignment of its own, as // Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when - // the path was, or when the compound path it leaves was. + // the path was, or when the compound path it leaves was. A compound path that is + // pixel-aligned snaps the path it takes in. if let Some(c) = into { let mut aligned = from_aligned; if let Some(m) = d.node_mut(id) { @@ -966,9 +967,12 @@ fn move_node(s: &mut Session, p: &Value) -> Result { *live = None; } } - if aligned && let Some(cn) = d.node_mut(c) { - cn.extras_mut().pixel_aligned = true; - super::object::snap_if_aligned(cn); + if let Some(cn) = d.node_mut(c) { + aligned |= cn.extras().pixel_aligned; + if aligned { + cn.extras_mut().pixel_aligned = true; + super::object::snap_if_aligned(cn); + } } } if let Some((appearance, aligned)) = out_of diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 3bec14515a..55ea019e82 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -171,8 +171,9 @@ pub struct DocSettings { pub layout: ArtboardLayout, /// Columns of a grid layout. pub columns: u32, - /// Rows of a grid by column, in place of `columns` when more than 0. - #[serde(skip_serializing_if = "is_zero")] + /// Rows of a grid by column, in place of `columns` when more than 0, up to `MAX_ARTBOARDS` (a + /// saved or Recent preset's value past it is read as `MAX_ARTBOARDS`). + #[serde(skip_serializing_if = "is_zero", deserialize_with = "de_rows")] pub rows: u32, /// Space between artboards, points: 0 to `MAX_SPACING` (a saved or Recent preset's value /// outside that range is read as the nearer end). @@ -594,6 +595,11 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result>(d: D) -> std::result::Result { + Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32) +} + /// A saved or Recent preset's artboard spacing, kept to 0 to [`MAX_SPACING`] points. fn de_spacing<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { Ok(f64::deserialize(d)?.clamp(0.0, MAX_SPACING)) diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index d747f34989..dba64bf53c 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -702,9 +702,18 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); - s.edit("Reshape", |d, _| { - *path_mut(d, id)? = data; + s.edit("Reshape", |d, sel| { + let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); + let path = path_mut(d, id)?; + let reshaped = counts(path) != counts(&data); + *path = data; super::object::resnap(d, id); + // Direct-selected anchors and segments are kept by index: when anchors were added or + // removed, the path is deselected rather than left with other anchors selected. + if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { + sel.objects.retain(|o| *o != id); + sel.prune(d); + } Ok(()) })?; ok() diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e8d0cc404a..b6a1160e28 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -109,6 +109,11 @@ pub(super) struct State { /// A path and its subpaths with the point changes the run has made to it and not written yet /// ([`flush`]). pending: RefCell)>>, + /// How many times [`paths`] changed the waiting point changes, which makes a + /// [`paths::PointIndex`] of them stale. + pending_changes: Cell, + /// Where the points of the path the run last read points of start, by subpath ([`paths`]). + point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id /// ([`paths`]). point_cuts: RefCell>, @@ -125,6 +130,9 @@ pub(super) struct State { /// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently /// used first, each kept while its document is unchanged. art: RefCell>, + /// The last [`layers::LAYER_LISTS`] lists of layers `layers` gave, least recently used first, + /// each kept while its document is unchanged. + layer_lists: RefCell>, /// The uids of the documents whose active artboard `setActiveArtboardIndex` changed. pub(super) active_artboards: RefCell>, /// Each open document's uid and the index of its active artboard when the run started. @@ -716,11 +724,11 @@ fn on_doc_layer( keep_layer: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before, layer) = { + let (index, active, mut before, layer, old) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let st = &s.documents()[index]; - (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows()), st.doc.clone()) }; let switch = active != Some(index); if switch { @@ -737,7 +745,28 @@ fn on_doc_layer( if keep_selection { let doc = { let s = h.session.borrow(); - s.active().filter(|st| st.uid == uid && st.selection != before).map(|st| st.doc.clone()) + s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) + }; + // Anchors and segments are selected by index: a path that gained or lost anchors is not + // selected again, so that other anchors of it are not selected in their place. + if let Some(doc) = &doc { + let counts = |d: &Document, id: NodeId| { + d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) + }; + let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); + for id in partial { + if counts(&old, id) != counts(doc, id) { + before.anchors.remove(&id); + before.segments.remove(&id); + before.objects.retain(|o| *o != id); + before.key_anchor = before.key_anchor.filter(|(k, _)| *k != id); + before.key = before.key.filter(|k| *k != id); + } + } + } + let doc = { + let s = h.session.borrow(); + doc.filter(|_| s.active().is_some_and(|st| st.selection != before)) }; if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); @@ -1104,8 +1133,21 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { } // The document starts from the first preset of the profile's category (Print: Letter). let first = profile.and_then(|n| crate::cmd::newdoc::category(&h.session.borrow(), n)?.into_iter().next()); + let mut shadowed_by = None; if let Some(first) = first { - p.insert("preset".into(), json!(first.name)); + let shadowed = h.session.borrow().prefs.new_doc_presets.iter().any(|q| q.name.trim().eq_ignore_ascii_case(first.name.trim())); + if shadowed { + shadowed_by = Some(first.clone()); + // `file.new` would find the saved preset of that name first: the built-in preset's + // settings go as params instead, under the ones `presetSettings` gives. + if let Value::Object(base) = first.to_json() { + for (k, v) in base.into_iter().filter(|(k, _)| !matches!(k.as_str(), "name" | "size" | "orientation" | "profile")) { + p.entry(k).or_insert(v); + } + } + } else { + p.insert("preset".into(), json!(first.name)); + } } p.insert("profile".into(), profile.map_or(Value::Null, |n| json!(n))); if let Some(m) = mode { @@ -1120,6 +1162,15 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // The built-in preset's settings went as params: Recent keeps its name, as `file.new` + // keeps a preset's name, unless its size changed (turning it doesn't count). + if let Some(first) = &shadowed_by { + let sorted = |d: &crate::cmd::newdoc::DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units); + let mut s = h.session.borrow_mut(); + if let Some(r) = s.prefs.recent_new_docs.first_mut().filter(|r| sorted(r) == sorted(first)) { + r.name.clone_from(&first.name); + } + } // Each warning from reading the profile's file goes to the console. for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); @@ -1346,6 +1397,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen: HashSet = HashSet::with_capacity(list.len()); // The document is read once for every object: nothing changes it while the list is checked. let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); let locks = d.locked_artboards(); @@ -1360,7 +1412,7 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result Answer { bounds(h, a, true) } +/// The box of the anchors and direction handles of the paths in `n` that its visible bounds take +/// in: a clipping group or layer gives only its clipping path's, and the source art a Shaper Group +/// or a tracing keeps is left out, as are hidden objects. +fn handles_box(n: &vectorcraft_doc::Node) -> Option { + let children = n.editing_children(); + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + _ if n.clips() => children.first().and_then(|c| handles_box(c)), + _ => children.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, handles_box(c))), + } +} + +/// The item's visible bounds grown to take in the direction handles of its paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = with_doc(h, item.doc, |_, st| { + let visible = st.doc.bounds_of(&[item.id], true); + let handles = st.doc.node(item.id).and_then(handles_box); + let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; + Ok::<_, HostError>((r, frame(st)?)) + })?; + Ok(f.bounds(h.dom.coords.get(), r)) +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -2140,7 +2216,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/layers.rs b/crates/engine/src/script/dom/layers.rs index 23e4d58170..7a24b8fa3e 100644 --- a/crates/engine/src/script/dom/layers.rs +++ b/crates/engine/src/script/dom/layers.rs @@ -474,6 +474,39 @@ fn layer_list(d: &Document, parent: Option) -> Vec { list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect() } +/// A document's uid, the document as it was, a parent layer (`None`: the top level) and its layers. +pub(super) type LayerList = (u64, Arc, Option, Rc>); + +/// How many lists of layers [`super::State`] keeps at once. +pub(super) const LAYER_LISTS: usize = 4; + +/// [`layer_list`], kept while the document is unchanged for the last [`LAYER_LISTS`] parents, so a +/// loop over `layers` builds the list once. Each new list is charged by the objects it looks at. +fn layer_ids(h: &Host, st: &DocState, parent: Option) -> Result>> { + { + let mut lists = h.dom.layer_lists.borrow_mut(); + if let Some(at) = lists.iter().position(|(uid, doc, p, _)| *uid == st.uid && Arc::ptr_eq(doc, &st.doc) && *p == parent) { + let list = lists.remove(at); + let ids = list.3.clone(); + lists.push(list); + return Ok(ids); + } + } + let looked = match parent { + None => st.doc.layers.len(), + Some(p) => st.doc.children(Some(p)).map_or(0, Vec::len), + }; + h.charge_call(looked as u64)?; + let ids = Rc::new(layer_list(&st.doc, parent)); + let mut lists = h.dom.layer_lists.borrow_mut(); + lists.retain(|(uid, doc, ..)| *uid != st.uid || Arc::ptr_eq(doc, &st.doc)); + if lists.len() >= LAYER_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), parent, ids.clone())); + Ok(ids) +} + fn layers_of(h: &Host, a: &[Data]) -> Answer { let (doc, id) = this_layer(h, a)?; let [high, low] = id_parts(id); @@ -482,7 +515,7 @@ fn layers_of(h: &Host, a: &[Data]) -> Answer { fn layers_length(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; - Ok(num(float(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).len()) as u64))) + Ok(num(float(with_doc(h, doc, |_, st| layer_ids(h, st, parent).map(|l| l.len()))? as u64))) } fn layers_parent(h: &Host, a: &[Data]) -> Answer { @@ -499,14 +532,14 @@ fn layers_at(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - Ok(with_doc(h, doc, |_, st| layer_list(&st.doc, parent).get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) + with_doc(h, doc, |_, st| Ok(layer_ids(h, st, parent)?.get(i).map_or(Data::Undefined, |id| layer_ref(h, st.uid, *id)))) } fn layers_by_name(h: &Host, a: &[Data]) -> Answer { let (doc, parent) = layers_scope(h, arg(a, 0))?; let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { - let ids = layer_list(&st.doc, parent); + let ids = layer_ids(h, st, parent)?; h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| layer_ref(h, st.uid, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) @@ -659,6 +692,8 @@ fn art_by_name(h: &Host, a: &[Data], kind: Kind) -> Answer { let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; with_doc(h, doc, |_, st| { let ids = art_list(h, st, kind, c)?; + // The scan is charged by itself: a list kept from an earlier read was charged once. + h.charge_call(ids.len() as u64)?; let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str())); id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into())) }) @@ -767,10 +802,8 @@ fn compounds_remove_all(h: &Host, a: &[Data]) -> Answer { } fn art_typename(h: &Host, a: &[Data], kind: Kind) -> Answer { - let (doc, c) = art_scope(h, arg(a, 0), kind.class())?; - // A compound path's `pathItems` are its `PageItems`: it holds only paths. - let compound = c.is_some_and(|c| with_doc(h, doc, |_, st| st.doc.node(c).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. })))); - Ok(text(if compound && kind == Kind::Any { "PathItems" } else { kind.class() })) + art_scope(h, arg(a, 0), kind.class())?; + Ok(text(kind.class())) } pub(super) fn scoped_typename(h: &Host, a: &[Data]) -> Answer { @@ -856,6 +889,13 @@ fn held_paths(h: &Host, a: &[Data]) -> Answer { Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) } +/// A compound path's `pathItems`: its paths, which `add()` and the shape methods make inside it +/// ([`super::paths`]). +fn compound_paths(h: &Host, a: &[Data]) -> Answer { + let item = this_item_of(h, a, "CompoundPathItem")?; + Ok(super::paths::held_path_items(h, item.doc.uid, item.id)) +} + // ---- GroupItem and CompoundPathItem ---- fn this_item_of(h: &Host, a: &[Data], what: &str) -> Result { @@ -913,7 +953,7 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<(String, HostMember)> { m.extend(["textFrames", "symbolItems", "placedItems", "rasterItems"].map(|m| later(l, "GroupItem", m))); m } - "CompoundPathItem" => named(vec![("pathItems", get(l, held_page_items))]), + "CompoundPathItem" => named(vec![("pathItems", get(l, compound_paths))]), _ => Vec::new(), } } diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 87287c5c27..19ad6ac4fb 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -131,20 +131,79 @@ fn path_ref(h: &super::Host, item: Item) -> Data { host_ref("PathItem", &[float(h.run), float(item.doc.uid), high, low]) } -/// How many points a path with the subpaths `subs` has. -fn point_count(subs: &[SubPath]) -> usize { - subs.iter().map(|sp| sp.anchors.len()).sum() +/// The subpaths a [`PointIndex`] was made from. +enum PointSource { + /// The path's node as its document held it, kept so that the node compared with is the same + /// one: any change to the path's points makes a new node. + Node(Arc), + /// The path's waiting point changes, after this many changes to them + /// ([`super::State`]'s `pending_changes`). + Pending(u64), } -/// The subpath and the place in it of point `i`, among the subpaths `subs`. -fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> { - for (s, sp) in subs.iter().enumerate() { - if i < sp.anchors.len() { - return Some((s, i)); +/// Where the points of a path start, by subpath, so that a point is found by its index without a +/// pass over the subpaths before it. +pub(super) struct PointIndex { + /// The document uid and the id of the path. + key: (u64, u64), + source: PointSource, + /// The number of points before each subpath. + starts: Vec, + /// The number of points in all. + count: usize, +} + +impl PointIndex { + fn new(key: (u64, u64), source: PointSource, subs: &[SubPath]) -> Self { + let mut starts = Vec::with_capacity(subs.len()); + let mut count = 0; + for sp in subs { + starts.push(count); + count += sp.anchors.len(); } - i -= sp.anchors.len(); + PointIndex { key, source, starts, count } } - None + + /// The subpath and the place in it of point `i`. + fn locate(&self, i: usize) -> Option<(usize, usize)> { + if i >= self.count { + return None; + } + // The last subpath that starts at or before `i`: a subpath with no points starts where the + // next one does, so it is never the one found. + let s = self.starts.partition_point(|&start| start <= i).checked_sub(1)?; + Some((s, i - self.starts[s])) + } +} + +/// The number of points of the path of `item`, its waiting point changes included, and the subpath +/// and the place in it of point `i` when `i` is given and in the path. The index of the path's +/// subpaths is kept in [`super::State`] until the path's points change. +fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Result<(usize, Option<(usize, usize)>), HostError> { + let key = (item.doc.uid, item.id.0); + let source = match &*h.dom.pending.borrow() { + Some((waiting, _)) if same_path(*waiting, item) => PointSource::Pending(h.dom.pending_changes.get()), + _ => { + let s = h.session.borrow(); + let node = s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, item.id).cloned()); + PointSource::Node(node.ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) + } + }; + let fresh = h.dom.point_index.borrow().as_ref().is_some_and(|x| { + x.key == key + && match (&x.source, &source) { + (PointSource::Node(a), PointSource::Node(b)) => Arc::ptr_eq(a, b), + (PointSource::Pending(a), PointSource::Pending(b)) => a == b, + _ => false, + } + }); + if !fresh { + let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; + *h.dom.point_index.borrow_mut() = Some(index); + } + let kept = h.dom.point_index.borrow(); + let Some(index) = kept.as_ref() else { return Err(HostError::Error(STALE_ITEM.into())) }; + Ok((index.count, i.and_then(|i| index.locate(i)))) } fn anchor_json(a: &Anchor) -> Value { @@ -171,6 +230,7 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { @@ -320,7 +380,8 @@ pub(super) fn held_path_items(h: &super::Host, uid: u64, id: NodeId) -> Data { host_ref("PathItems", &[float(h.run), float(uid), high, low]) } -/// The document of a `PathItems` object, and the layer or group it lists the paths of, if any. +/// The document of a `PathItems` object, and the layer, group or compound path it lists the paths +/// of, if any. fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option), HostError> { let Some(handle) = handle_of(arg(a, 0), "PathItems") else { return Err(HostError::Type("this is not a PathItems".into())) }; match handle.as_slice() { @@ -328,7 +389,9 @@ fn items_scope(h: &super::Host, a: &[Data]) -> std::result::Result<(Doc, Option< [run, uid, high, low] => { let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; - let holds = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }))); + let holds = with_doc(h, doc, |_, st| { + st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. })) + }); if !holds { return Err(HostError::Error(STALE_ITEM.into())); } @@ -432,7 +495,9 @@ fn make_in( return Err(HostError::Error(CONTAINER_LOCKED.into())); } let made = match container { - None => on_doc(h, doc.uid, true, make)?, + // Making a path can take more than one command (a stroke, a reversal): a failure of a later + // one undoes the path too. + None => super::atomically(h, |h| on_doc(h, doc.uid, true, make))?, Some(c) => super::atomically(h, |h| { let id = on_doc(h, doc.uid, true, |h| { command(h, "layer.setCurrent", &json!({"id": c.0, "keepRows": true}))?; @@ -1124,17 +1189,21 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) { return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into())); } - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; - let origin = about(h, item, place, r)?; - params["origin"] = json!([origin.x, origin.y]); - edit_path(h, item, "object.scale", params)?; - } - if let Some(w) = new_width - && (w - width).abs() > 1e-9 - { - edit_path(h, item, "stroke.set", json!({"weight": w}))?; - } + // The scale and the new stroke weight are one edit: a failure of either undoes both. + super::atomically(h, |h| { + if sx != 100.0 || sy != 100.0 { + let (r, _) = item_rect(h, item, false)?; + let origin = about(h, item, place, r)?; + params["origin"] = json!([origin.x, origin.y]); + edit_path(h, item, "object.scale", params)?; + } + if let Some(w) = new_width + && (w - width).abs() > 1e-9 + { + edit_path(h, item, "stroke.set", json!({"weight": w}))?; + } + Ok(()) + })?; Ok(Data::Undefined) } @@ -1148,7 +1217,8 @@ fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result Answer { let item = points_path(h, a)?; - read_points(h, item, |subs| num(float(point_count(subs) as u64))) + let (n, _) = point_place(h, item, None)?; + Ok(num(float(n as u64))) } fn points_parent(h: &super::Host, a: &[Data]) -> Answer { @@ -1272,7 +1342,7 @@ fn points_at(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; let Some(i) = whole(*n).and_then(|i| usize::try_from(i).ok()) else { return Ok(Data::Undefined) }; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; Ok(if i < n { point_ref(h, item, i) } else { Data::Undefined }) } @@ -1290,7 +1360,8 @@ fn points_index(h: &super::Host, a: &[Data]) -> Answer { fn points_add(h: &super::Host, a: &[Data]) -> Answer { let item = points_path(h, a)?; let origin = with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), [0.0, 0.0]))); - let (n, last) = read_points(h, item, |subs| (point_count(subs), subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p)))?; + let (n, _) = point_place(h, item, None)?; + let last = read_points(h, item, |subs| subs.iter().rev().find_map(|sp| sp.anchors.last()).map(|a| a.p))?; if n >= MAX_POINTS { return Err(HostError::Range(format!("PathPoints.add takes a path to at most {MAX_POINTS} points"))); } @@ -1324,20 +1395,29 @@ pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(It return Err(HostError::Error(STALE_POINT.into())); } let i = whole(*i).and_then(|i| usize::try_from(i).ok()).ok_or_else(|| HostError::Error(STALE_POINT.into()))?; - let n = read_points(h, item, point_count)?; + let (n, _) = point_place(h, item, None)?; if i >= n { return Err(HostError::Error(STALE_POINT.into())); } Ok((item, i)) } +/// [`this_point`] with the subpath and the place in it of the point. +fn this_point_place(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize, usize), HostError> { + let (item, i) = this_point(h, a)?; + match point_place(h, item, Some(i))? { + (_, Some((s, j))) => Ok((item, s, j)), + (_, None) => Err(HostError::Error(STALE_POINT.into())), + } +} + /// Reads the anchor `this` names with `f`, given the frame and the coordinate system. fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, &Anchor) -> Data) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; let c = h.dom.coords.get(); let fr = with_doc(h, item.doc, |_, st| frame(st))?; read_points(h, item, |subs| { - let anchor = locate(subs, i).and_then(|(s, j)| subs.get(s).and_then(|sp| sp.anchors.get(j))); + let anchor = subs.get(s).and_then(|sp| sp.anchors.get(j)); anchor.map(|an| f(&fr, c, an)).ok_or_else(|| HostError::Error(STALE_POINT.into())) })? } @@ -1345,11 +1425,9 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// Changes the anchor `this` names with `f`, given the point the script assigned in document /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) - { + if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } })?; @@ -1411,10 +1489,10 @@ fn pt_parent(h: &super::Host, a: &[Data]) -> Answer { /// `remove()`: deletes the point; a subpath left with no points goes too. fn pt_remove(h: &super::Host, a: &[Data]) -> Answer { - let (item, i) = this_point(h, a)?; + let (item, s, j) = this_point_place(h, a)?; edit_points(h, item, |subs| { - if let Some((s, j)) = locate(subs, i) - && let Some(sp) = subs.get_mut(s) + if let Some(sp) = subs.get_mut(s) + && j < sp.anchors.len() { sp.anchors.remove(j); if sp.anchors.is_empty() { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index ccb5b7f8d8..3a04359e7f 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2227,6 +2227,16 @@ impl Session { RunError { kind: RunErrorKind::Limit(kind), message: format!("limit reached: {kind:?}"), line: 0, column: 0, authored: false }; return Some(self.script_failed(job, &e)); } + // What the script added must fit the allowance the last answer gave: past it, the + // person is asked again, as a running script is at its next charge. + if let Err(e) = job.host.charge_growth(0, 0) { + return Some(self.script_failed(job, &end_flush_error(e))); + } + if job.host.waiting.get() { + JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); + self.script_key = Some(key); + return None; + } return Some(self.script_ended(job)); } // A stop while a dialog waits ends the run there; the interpreter cannot go on from the call. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 4e99adf688..e2ac91d592 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -422,6 +422,22 @@ fn align_new_objects_to_pixel_grid_follows_the_preset() { assert!(!align(&old)); } +#[test] +fn saved_rows_past_the_limit_read_as_the_limit_and_others_stay() { + let mut s = Session::new(); + let saved = json!({"newDocPresets": [ + {"name": "Many", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 1001}, + {"name": "Four", "width": 100, "height": 100, "artboards": 2, "layout": "gridByColumn", "rows": 4}, + ]}); + s.apply_prefs(serde_json::from_value(saved).unwrap()); + for (name, rows) in [("Many", 1000), ("Four", 4)] { + let layout = presets(&mut s, "Saved").iter().find(|p| p["name"] == name).unwrap()["artboardLayout"].clone(); + assert_eq!(layout["rows"], json!(rows), "{name}"); + // `file.new` takes the layout `file.newPresets` lists. + s.execute("file.new", &json!({"preset": name, "artboardLayout": layout})).unwrap(); + } +} + #[test] fn rearrange_keeps_its_grid() { let mut s = new_doc(json!({"width": 100, "height": 50, "artboards": 3})); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index fb7239394a..5368a64c2f 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -930,6 +930,19 @@ fn note_is_the_attributes_note() { assert!(failure(&mut s, "app.activeDocument.pageItems[0].note = new Array(5000).join('n');").contains("too long")); } +#[test] +fn add_document_starts_from_the_built_in_preset_when_a_saved_one_has_its_name() { + let mut s = Session::new(); + s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 100, "height": 50, "colorMode": "rgb"})).unwrap(); + let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height, d.documentColorSpace]);"); + assert_eq!(out[0], json!([612, 792, "DocumentColorSpace.CMYK"])); + // Recent keeps the built-in preset's name, as it does when no saved preset has it. + assert_eq!(s.prefs.recent_new_docs[0].name, "Letter"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 300; var e = app.documents.addDocument('Print', p); vc.log([e.width, e.height]);"); + assert_eq!(out[0], json!([300, 792])); + assert_eq!(s.prefs.recent_new_docs[0].name, "Custom"); +} + #[test] fn document_preset_applies_only_its_given_fields() { let mut s = Session::new(); @@ -1317,8 +1330,9 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + let p = path.to_string_lossy(); + let (p, other) = (json!(p), json!(format!("{p}.other"))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. @@ -1612,12 +1626,12 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ - vc.log(G.getByName === undefined); vc.log(P[1] === undefined);", + G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", ); let expected = [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; assert_eq!(out[..11], expected); - assert_eq!(out[11..], [json!(false), json!(true)]); + assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); } #[test] @@ -1917,6 +1931,29 @@ fn a_path_moved_between_compound_paths_keeps_its_pixel_alignment() { assert!(!d.node(a).unwrap().extras().pixel_aligned); } +/// A pixel-aligned compound path snaps a path that was not aligned when it takes it in. +#[test] +fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + s.execute("object.setPixelAligned", &json!({"on": true})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + let cid = s.active().unwrap().doc.parent_of(a).unwrap(); + let loose = rect(&mut s, 200.25, 20.5, 30.0, 40.0); + s.execute("select.none", &json!({})).unwrap(); + assert!(!s.active().unwrap().doc.node(loose).unwrap().extras().pixel_aligned); + s.execute("node.move", &json!({"id": loose.0, "parent": cid.0, "index": 0})).unwrap(); + let d = &s.active().unwrap().doc; + assert_eq!(d.parent_of(loose), Some(cid)); + // Both paths have a 1 pt stroke, so the grid puts their edges where it put the aligned path's. + let (b, at) = (d.node(loose).unwrap().geometric_bounds().unwrap(), d.node(a).unwrap().geometric_bounds().unwrap()); + assert_ne!(b.x0, 200.25); + for (v, w) in [(b.x0, at.x0), (b.y0, at.y0), (b.x1, at.x1), (b.y1, at.y1)] { + assert_eq!(v.fract(), w.fract(), "{b:?} is on the pixel grid as {at:?} is"); + } +} + #[test] fn a_compound_paths_path_items_are_path_items() { let (mut s, a, b) = doc(); @@ -1930,6 +1967,23 @@ fn a_compound_paths_path_items_are_path_items() { assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]); } +#[test] +fn a_compound_paths_path_items_add_makes_the_path_inside_it() { + let (mut s, _, _) = doc(); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var c = app.activeDocument.layers[0].compoundPathItems.add(); var p = c.pathItems.add(); p.setEntirePath([[0, 0], [10, 0], [10, 10]]);\ + var r = c.pathItems.rectangle(50, 20, 10, 10); vc.log(c.pathItems.length); vc.log(p.parent.typename); vc.log(r.parent.typename);\ + vc.log(c.pathItems[0].width);", + ); + assert_eq!(out, [json!(2), json!("CompoundPathItem"), json!("CompoundPathItem"), json!(10)]); + let d = &s.active().unwrap().doc; + let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); + assert_eq!(compound.children().unwrap().len(), 2); + assert!(undo_steps(&s) > steps); +} + #[test] fn art_collections_follow_edits_between_reads() { let (mut s, _, _) = doc(); @@ -1966,6 +2020,18 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() { assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}"); } +#[test] +fn layer_lists_follow_edits_between_reads() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var L = app.activeDocument.layers, n = L.length; for (var i = 0; i < L.length; i++) L[i];\ + var made = L.add(); made.name = 'Top'; vc.log(L.length - n); vc.log(L[0].name); vc.log(L.getByName('Top').name);\ + made.remove(); vc.log(L.length - n);", + ); + assert_eq!(out, [json!(1), json!("Top"), json!("Top"), json!(0)]); +} + #[test] fn group_items_remove_all_refuses_locked_groups() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 2dbf3263b9..99e83b4ddc 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -154,6 +154,72 @@ fn shape_creators_reject_bad_sizes_without_change() { assert_eq!(undo_steps(&s), steps); } +#[test] +fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { + // `pathItems[1]` is `b`. + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + log(&mut s, "app.activeDocument.pathItems[1].pathPoints[0].remove();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + let sel = &st.selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // Moving a point keeps the anchors selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +#[test] +fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { + let (mut s, a, b) = doc(); + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + s.execute("select.add", &json!({"ids": [a.0]})).unwrap(); + let pt = |x: f64, y: f64| json!({"x": x, "y": y, "in": [x, y], "out": [x, y], "smooth": false}); + let three = json!([{"anchors": [pt(0.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": three})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); + assert!(sel.objects.contains(&a)); + // The same number of anchors keeps them selected. + s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); + let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); +} + +/// Points are found by their index across subpaths, through changes that wait to be written and +/// removals that change how many points a subpath has or remove a subpath. +#[test] +fn points_are_found_across_subpaths_as_their_counts_change() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let pt = |x: f64| json!({"x": x, "y": 0, "in": [x, 0], "out": [x, 0], "smooth": false}); + let subs = json!([ + {"anchors": [pt(0.0), pt(1.0)], "closed": false}, + {"anchors": [pt(2.0)], "closed": false}, + {"anchors": [pt(3.0), pt(4.0), pt(5.0)], "closed": false}, + ]); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; vc.log(q.length);\ + for (var i = 0; i < q.length; i++) q[i].anchor = [i * 10, 7];\ + vc.log(q[2].anchor); vc.log(q[5].anchor);\ + q[1].remove(); vc.log(q.length); vc.log(q[1].anchor); vc.log(q[4].anchor);\ + q[0].remove(); vc.log(q.length); vc.log(q[0].anchor); vc.log(q[3].anchor); vc.log(q[4] === undefined);", + ); + let want = + [json!(6), json!([20, 7]), json!([50, 7]), json!(5), json!([20, 7]), json!([50, 7]), json!(4), json!([20, 7]), json!([50, 7]), json!(true)]; + assert_eq!(out, want); + let n = node(&s, a); + let counts: Vec = n.path_data().unwrap().subpaths.iter().map(|sp| sp.anchors.len()).collect(); + assert_eq!(counts, vec![1, 3]); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); @@ -173,6 +239,34 @@ fn set_entire_path_replaces_points_and_keeps_closed() { assert!(pd.subpaths[0].anchors.iter().all(|an| an.h_in == an.p && an.h_out == an.p && an.kind == AnchorKind::Corner)); } +#[test] +fn control_bounds_take_in_direction_handles() { + let (mut s, _, _) = doc(); + let out = log( + &mut s, + "var r = app.activeDocument.pathItems[0]; vc.log(r.controlBounds); vc.log(r.visibleBounds);\ + var n = app.activeDocument.pathItems.add(); n.setEntirePath([[0, 0], [100, 0]]);\ + n.pathPoints[0].rightDirection = [50, 80]; vc.log(n.controlBounds); vc.log(n.visibleBounds);", + ); + assert_eq!(out[0], out[1], "a rectangle has no handles outside its visible bounds"); + let edges = |v: &Value| (0..4).map(|i| v[i].as_f64().unwrap()).collect::>(); + let (control, visible) = (edges(&out[2]), edges(&out[3])); + assert!(control[1].max(control[3]) >= 80.0 - 1e-9, "{control:?}"); + assert!(visible[1].max(visible[3]) < 80.0, "{visible:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2], "{control:?} holds {visible:?}"); +} + +/// A clipping group's control bounds are its clipping path's: art outside the clip is left out, as +/// it is from the visible bounds. +#[test] +fn a_clipping_groups_control_bounds_leave_out_the_clipped_art() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.clippingMask.make", &json!({})).unwrap(); + let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.controlBounds); vc.log(g.visibleBounds);"); + assert_eq!(out[0], out[1]); +} + #[test] fn hostile_set_entire_path_input_is_bounded() { let (mut s, _, _) = doc(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 2be8a841a8..f89d15d16c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -1297,6 +1297,60 @@ fn point_changes_written_as_the_script_ends_wait_for_the_growth_answer() { assert_eq!(state(&s), before); } +/// A script that ends past the allowance the person's last answer gave is asked again before its +/// changes are kept. +#[test] +fn a_finished_run_past_its_last_allowance_asks_again() { + let draw = "vc.run('shape.rectangle', {x:1,y:1,width:1,height:1}); vc.run('shape.rectangle', {x:2,y:1,width:1,height:1});"; + let point = "var P = app.activeDocument.pathItems, q = P[0];\ + for (var k = 1; k < P.length; k++) if (P[k].pathPoints.length > q.pathPoints.length) q = P[k];\ + var p = q.pathPoints; for (var i = 0; i < p.length; i++) p[i].anchor = [i * 3, -4 - i];"; + // The path the script moves has 600 anchors, so its point changes weigh more than the + // rectangles do. + let two_docs = || { + let mut s = two_docs(); + let id = s.documents()[1].doc.layers[0].children().unwrap()[0].id; + let anchors: Vec = (0..600) + .map(|i| json!({"x": f64::from(i), "y": f64::from(i % 7), "in": [f64::from(i), 0.0], "out": [f64::from(i), 0.0], "smooth": false})) + .collect(); + s.execute("path.setAnchors", &json!({"id": id.0, "subpaths": [{"anchors": anchors, "closed": false}]})).unwrap(); + s + }; + let added = |source: &str| { + let mut s = two_docs(); + let start = s.documents()[1].doc.clone(); + assert_eq!(run(&mut s, source).unwrap()["ok"], true); + start.retained_bytes_each(&s.documents()[1].doc).1 as u64 + }; + let whole = format!("{draw} {point}"); + let (m, p) = (added(draw), added(&whole) - added(draw)); + // The rectangles go past one object, which asks once, and stay within twice the bytes; the + // point changes, written as the script ends, then go past the second allowance and also past + // the third. + let b = (m + p - 1) / 3; + assert!(m <= 2 * b && 3 * b < m + p && m + p <= 4 * b, "m {m}, p {p}, b {b}"); + TEST_GROWTH.with(|g| g.set(Some(1))); + TEST_GROWTH_BYTES.with(|g| g.set(Some(b))); + let mut s = two_docs(); + s.script_frames = true; + run(&mut s, &whole).unwrap(); + let mut questions = 0; + let done = loop { + assert!(questions < 10); + if s.script_waiting() { + questions += 1; + s.script_continue(); + } + if let Some(r) = s.script_pump() { + break r; + } + }; + TEST_GROWTH.with(|g| g.set(None)); + TEST_GROWTH_BYTES.with(|g| g.set(None)); + assert_eq!(done.unwrap()["ok"], true); + assert_eq!(questions, 3, "asked mid-run, as the script ended, and again for the third allowance"); +} + #[test] fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { TEST_GROWTH.with(|g| g.set(Some(20))); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index e88bc3f454..de41e7ef6f 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -215,7 +215,8 @@ pub(crate) fn install(i: &mut Interp, classes: Vec, instances: Vec<(S let global = i.global; i.define(global, key(&name), Prop::Data { value: v, flags: 0 })?; } - Ok(()) + // The prototypes, constructors and members are made without a reservation of their own. + i.reserve_heap(0) } fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index 1da0d53002..a17c420c5e 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -648,6 +648,17 @@ fn with_thing(r: &mut Realm, make: Option) { r.define_host_classes(vec![class], vec![("thing".into(), host_ref("Thing", &[1.0]))]).unwrap(); } +#[test] +fn host_classes_that_do_not_fit_the_heap_end_with_the_heap_limit() { + let mut r = realm(1_000_000); + let interp = r.interp(); + interp.collect_garbage(); + interp.limits.heap_bytes = interp.heap.bytes; + let class = HostClass { name: "Empty".into(), parent: None, members: Vec::new(), index: None, construct: None }; + let e = r.define_host_classes(vec![class], Vec::new()).unwrap_err(); + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap)); +} + #[test] fn the_answer_to_a_waiting_member_of_a_host_class_is_an_object_of_its_class() { let mut r = realm(1_000_000); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 53300e92ec..77183407da 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -820,6 +820,22 @@ mod tests { assert_eq!(shown_columns(&s), 2.0); } + /// The dialog reads rows as `file.new` does: a whole number from 1 to the artboard limit, + /// `4.0` included, and a fractional, zero or larger count is refused with nothing changed. + #[test] + fn the_dialog_reads_rows_as_file_new_does() { + let mut app = app(); + open(&mut app); + set(&app, "artboards", json!(5)).unwrap(); + set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4.0})).unwrap(); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4)); + for rows in [json!(3.5), json!(MAX_ARTBOARDS + 1), json!(0)] { + let e = set(&app, "artboardLayout", json!({"layout": "gridByColumn", "rows": rows})).unwrap_err(); + assert!(e.contains("can't take"), "{rows}: {e}"); + assert_eq!(fields(&app)["artboardLayout"]["rows"], json!(4), "{rows}"); + } + } + /// Press Create: the dialog files its answer and the pump runs `file.new` with it. fn create(app: &mut VectorcraftApp) { let ctx = ctx(app); diff --git a/docs/mcp.md b/docs/mcp.md index 9210de701c..9f0f89f49e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2682,7 +2682,7 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, + visible bounds grown to take in the paths' direction handles), `editable` (false for an object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs @@ -2757,8 +2757,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's `pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any - depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers, and a compound - path's `pathItems` have the typename `PathItems`. A layer's or artboard's `name` takes a number or a boolean as + depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers. A compound + path's `pathItems` are a `PathItems` collection: `add()` and its shape methods make the new path inside the + compound path. A layer's or artboard's `name` takes a number or a boolean as `String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past From fab69d7f70878d20b58af5b23320a1affc9056d8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:10:36 -0800 Subject: [PATCH 017/334] Scripts: a palette's click or change keeps its control when a run changes the palette first The events the person gives a palette are kept with their control's id, and a list's change with the items they chose from, until the app puts them in line. A run that adds or removes controls before then no longer sends a click to the control now at the old index. --- crates/ui-egui/src/dialogs/script_window.rs | 4 ++-- crates/ui-egui/src/script_palettes.rs | 19 ++++++++++++------- crates/ui-egui/src/tests/script_palettes.rs | 18 ++++++++++++++++++ 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 3b7f6098c0..f97cf34bc7 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -259,7 +259,7 @@ pub(crate) fn keep_refused(w: &ScriptUiDialog, drafts: &mut BTreeMap Option { +pub(crate) fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { let id = |i: usize| w.nodes.get(i).map(|n| n.id); Some(match event { UiEvent::Click(i) => Queued::Click(id(*i)?), @@ -274,7 +274,7 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { /// 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: other texts, or the same texts added again. -fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { +pub(crate) fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { match q { Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), Queued::Change(id, v, list) => { diff --git a/crates/ui-egui/src/script_palettes.rs b/crates/ui-egui/src/script_palettes.rs index 2e4047c09f..05c618c873 100644 --- a/crates/ui-egui/src/script_palettes.rs +++ b/crates/ui-egui/src/script_palettes.rs @@ -22,7 +22,7 @@ use vectorcraft_engine::script::{ScriptPalette, ScriptUiDialog, UiEvent, UiValue use crate::VectorcraftApp; use crate::dialogs::script_run::with_host; -use crate::dialogs::script_window; +use crate::dialogs::script_window::{self, Queued}; /// The dialog kind of a ScriptUI palette. pub const KIND: &str = "scriptPalette"; @@ -38,8 +38,10 @@ pub(crate) struct PaletteWindow { palette: ScriptPalette, /// The text typed in each edit field that the script has not had yet, by the field's id. drafts: BTreeMap, - /// The events the person gave since the app last took them. - given: Vec, + /// 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. + given: Vec, open: bool, } @@ -72,7 +74,7 @@ impl PaletteWindow { /// Gives `event`, as the person does in the palette. #[cfg(test)] pub(crate) fn give(&mut self, event: UiEvent) { - self.given.push(event); + self.given.extend(script_window::queued(&self.palette.dialog, &event)); } } @@ -102,12 +104,12 @@ impl StackDialog for PaletteWindow { let shown = Dialog::new(heading).modeless().initial_focus(Initial::Keep).opened(Bind::bound(open)).show(ui, |ui, _| { events = script_window::controls(ui, &palette.dialog, drafts, true).events; }); - given.extend(events); + given.extend(events.iter().filter_map(|e| script_window::queued(&palette.dialog, e))); // 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; - self.given.push(UiEvent::Close); + self.given.push(Queued::Close); } None } @@ -141,8 +143,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { taken }) .unwrap_or_default(); - for (id, mut drafts, mut events) in taken { + for (id, mut drafts, 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 events: Vec = given.into_iter().filter_map(|q| script_window::resolved(&p.dialog, q)).collect(); drafted(app, &p.dialog, &mut drafts, &mut events); give(app, ctx, p, &mut drafts, events); with_host(app, |host, _| { diff --git a/crates/ui-egui/src/tests/script_palettes.rs b/crates/ui-egui/src/tests/script_palettes.rs index 70462c2b51..b2e89992e0 100644 --- a/crates/ui-egui/src/tests/script_palettes.rs +++ b/crates/ui-egui/src/tests/script_palettes.rs @@ -164,6 +164,24 @@ fn a_typed_text_stays_in_its_field_when_a_run_adds_a_control_before_it() { 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; From ed0c7432ce0b0fa2806f661a7d703009ebce4c89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:26:11 -0800 Subject: [PATCH 018/334] Scripts: no palette listener runs once an earlier one closed the palette A palette event checks before each listener that the palette still takes it, so a listener that closes the palette stops the listeners after it, on the control and on its containers. --- crates/js/src/scriptui.rs | 21 ++++++++++++--------- crates/js/src/scriptui_tests.rs | 14 ++++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index fe3bd1fadb..970002c96b 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -939,8 +939,10 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, event: ObjId, phase: f64) -> JsResult { +/// in the order they were added. A listener that an earlier one removed does not run, and none +/// runs once the palette of `taker` no longer takes the event. → whether it had any; `None` when +/// the palette stopped taking the event. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, (event, phase): (ObjId, f64), taker: Taker) -> JsResult> { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() @@ -950,7 +952,7 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve }; let first = wanted(i)?; if first.is_empty() { - return Ok(false); + return Ok(Some(false)); } let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); i.rooted(&functions, |i| { @@ -960,9 +962,12 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve if !wanted(i)?.iter().any(|(g, d)| same(g, f) && d == c) { continue; } + if !takes(i, taker)? { + return Ok(None); + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } - Ok(true) + Ok(Some(true)) }) } @@ -1045,10 +1050,9 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(true), (event, 1.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { return Ok(Some(true)); } @@ -1068,16 +1072,15 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & if !takes(i, taker)? { return Ok(None); } - let heard = run_listeners(i, target, ty, None, event, 2.0)?; + let Some(heard) = run_listeners(i, target, ty, None, (event, 2.0), taker)? else { return Ok(None) }; if bubbles && !stopped(i)? { for p in above { if !containers_above(i, target)?.contains(p) { continue; } - if !takes(i, taker)? { + if run_listeners(i, *p, ty, Some(false), (event, 3.0), taker)?.is_none() { return Ok(None); } - run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; } diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 428d0aaccc..def7bca945 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -711,6 +711,20 @@ fn a_palette_event_does_not_run_a_handler_once_a_getter_closed_the_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)]); From 7737e97068a340fe5597baaa33113b47532722fe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 12:36:05 -0800 Subject: [PATCH 019/334] Scripts: a closed palette's visible is false `close()` and the close box set the palette's `visible` to false once `onClose` lets it close, as `hide()` does, so a script that checks `visible` stops updating a closed palette. --- crates/js/src/scriptui.rs | 6 ++++-- crates/js/src/scriptui_tests.rs | 2 ++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 970002c96b..9efffaa403 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1428,8 +1428,9 @@ fn set_palettes(i: &mut Interp, f: impl FnOnce(&mut Vec)) { } } -/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it and its -/// handlers no longer run. A `close()` while its `onClose` runs does nothing more. +/// Closes the palette `win` once its `onClose` allows it: the host no longer shows it, its +/// `visible` is false and its handlers no longer run. A `close()` while its `onClose` runs does +/// nothing more. fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if slot(i, win, IN_CLOSE)?.truthy() { return Ok(()); @@ -1440,6 +1441,7 @@ fn close_palette(i: &mut Interp, win: ObjId) -> JsResult<()> { if let Value::Number(id) = slot(i, win, PALETTE_ID)? { set_slot(i, win, PALETTE_ID, Value::Undefined)?; set_slot(i, win, SHOWN, Value::Bool(false))?; + i.put(win, key("visible"), Value::Bool(false), true)?; set_palettes(i, |p| p.retain(|o| *o != win)); let f = host_fn(i, "paletteClose")?; i.call(&f, &Value::Undefined, &[Value::Number(id)])?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index def7bca945..ba8421c0f4 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -489,8 +489,10 @@ fn closing_a_palette_runs_on_close_which_can_keep_it_open() { .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))); } From 88fe4e979629e7aa275f3334feeaa72744976113 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:52:31 -0800 Subject: [PATCH 020/334] Tests: list app.showColorPicker in the script host inventory --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 22f0b8b0b0..af193b5d56 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -84,7 +84,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + selection showColorPicker typename", ), ("DocumentPreset.", "prototype"), ( From d3912180387a4fcaf9cc25b4e48546861ac873c3 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Thu, 26 Nov 2026 08:56:17 +0530 Subject: [PATCH 021/334] 5547: scan missing links off the UI thread when the overlay turns on view.showMissingLinks no longer probes linked files: a changed file was read in full and hashed or decoded before the command returned, which could stall the desktop UI on a large or slow asset. Turning the overlay on now leaves its markers unscanned; Session::missing_link_scan_due tells the desktop link watcher to start a look at once, and the canvas repaints from the worker's result. links.marked keeps its synchronous inspection. A test gates the probe of one linked file and checks that the toggle returns before the probe completes, and that the probe runs on the link-watch worker. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/links.rs | 79 ++++++++++++++++++++++-- crates/engine/src/link_watch.rs | 11 +++- crates/engine/src/tests/missing_links.rs | 46 ++++++++++++++ crates/ui-egui/src/app/links.rs | 4 +- docs/mcp.md | 6 +- 5 files changed, 136 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 6608b0f4fd..2ca6547361 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -36,7 +36,7 @@ use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, has_do pub fn specs() -> Vec { vec![ cmd!(query "view.showMissingLinks", "Show Missing Links", ["View"], None, - "{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step → {on}", + "{on?: bool (default: toggle)} show non-printing red outlines and badges on missing linked images and placed documents in the active document; transient view state, no undo step; reads no files (the desktop app scans in the background, links.marked inspects now) → {on}", has_doc, show_missing_links), cmd!(query "links.marked", "Marked Missing Links", [], None, "{} inspect missing links now; only visible image objects and placed documents are marked, and none when the toggle is off → {on, images: [{id, bounds: [x0, y0, x1, y1]}]}", @@ -280,6 +280,8 @@ fn refused(link: &LinkInfo, doc_path: Option<&str>) -> Option) -> (Status, Option) { + #[cfg(test)] + probe_gate::hold(&g.link.path); let Some(mut f) = locate(&g.link, doc_path) else { return (Status::Missing, None) }; let l = &g.link; if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified { @@ -1143,11 +1145,18 @@ pub(crate) fn missing_markers(doc: &Document, path: Option<&str>) -> Vec fn show_missing_links(s: &mut Session, p: &Value) -> Result { let st = s.doc_mut()?; let on = super::switch_or(p, "on", !st.show_missing_links, "view.showMissingLinks")?; - // An explicit command answers immediately. Subsequent external changes are scanned by - // the existing link watch worker, even when the Links panel is closed. - if on { - st.missing_link_markers = Some((st.doc.clone(), missing_markers(&st.doc, st.path.as_deref()))); - } else { + // Never probes files here: a changed linked file is read in full to tell whether it still + // matches, which would hold up the caller (the desktop UI thread) on a large or slow file. + // Turning the overlay on leaves its markers unscanned; the link watch worker scans them + // at once ([`Session::missing_link_scan_due`]) and the canvas repaints from its result. + // `links.marked` stays the explicit, synchronous inspection. The web build has no worker + // and no files to read, so it marks at once. + if on && !st.show_missing_links { + st.missing_link_markers = None; + if cfg!(target_arch = "wasm32") { + st.missing_link_markers = Some((st.doc.clone(), missing_markers(&st.doc, st.path.as_deref()))); + } + } else if !on { st.missing_link_markers = None; } st.show_missing_links = on; @@ -1522,3 +1531,61 @@ fn placement_options(s: &mut Session, p: &Value) -> Result { set(&mut shown); Ok(json!({ "ids": ids_json(&ids), "placement": placement_json(shown) })) } + +/// Test seam: hold the probe of one linked path until the test releases it, so a test can +/// tell whether a command returned before the probe finished, and on which thread it ran. +#[cfg(test)] +pub(crate) mod probe_gate { + use std::sync::{Arc, Condvar, Mutex, PoisonError}; + use std::time::Duration; + + /// A gated path: (open, entered on thread named, finished), and the condition signalling + /// each change. + #[derive(Default)] + pub struct Gate { + state: Mutex<(bool, Option, bool)>, + changed: Condvar, + } + + static GATES: Mutex)>> = Mutex::new(Vec::new()); + + impl Gate { + /// Gate probes of the link stored as `path` until [`Gate::open`]. + pub fn close(path: &str) -> Arc { + let g = Arc::new(Gate::default()); + GATES.lock().unwrap_or_else(PoisonError::into_inner).push((path.to_string(), g.clone())); + g + } + pub fn open(&self) { + self.state.lock().unwrap_or_else(PoisonError::into_inner).0 = true; + self.changed.notify_all(); + } + /// The name of the thread that entered the probe, waiting up to `limit` for one. + pub fn entered(&self, limit: Duration) -> Option { + let s = self.state.lock().unwrap_or_else(PoisonError::into_inner); + let (s, _) = self.changed.wait_timeout_while(s, limit, |s| s.1.is_none()).unwrap_or_else(PoisonError::into_inner); + s.1.clone() + } + pub fn finished(&self) -> bool { + self.state.lock().unwrap_or_else(PoisonError::into_inner).2 + } + } + + /// Called at the start of every probe: blocks while `path` is gated and closed (at most + /// ten seconds, so a regression fails the test instead of hanging it). + pub(super) fn hold(path: &str) { + let gate = GATES.lock().unwrap_or_else(PoisonError::into_inner).iter().find(|(p, _)| p == path).map(|(_, g)| g.clone()); + let Some(g) = gate else { return }; + let mut s = g.state.lock().unwrap_or_else(PoisonError::into_inner); + s.1 = Some(std::thread::current().name().unwrap_or("").to_string()); + g.changed.notify_all(); + let (mut s, _) = g.changed.wait_timeout_while(s, Duration::from_secs(10), |s| !s.0).unwrap_or_else(PoisonError::into_inner); + s.2 = true; + g.changed.notify_all(); + } + + /// Stop gating `path`. + pub fn remove(path: &str) { + GATES.lock().unwrap_or_else(PoisonError::into_inner).retain(|(p, _)| p != path); + } +} diff --git a/crates/engine/src/link_watch.rs b/crates/engine/src/link_watch.rs index ce4f2677ee..8284ae0081 100644 --- a/crates/engine/src/link_watch.rs +++ b/crates/engine/src/link_watch.rs @@ -82,6 +82,13 @@ pub(crate) fn update_changed(s: &mut Session, _: &Value) -> Result { } impl Session { + /// Whether the active document shows missing links but has no marker scan yet (the overlay + /// was just turned on, or its first scan saw art that has since changed): the desktop app + /// then starts a look at once instead of waiting for the next periodic one. + pub fn missing_link_scan_due(&self) -> bool { + self.link_scan.is_none() && self.active().is_some_and(|st| st.show_missing_links && st.missing_link_markers.is_none()) + } + /// Start stamping the active document's linked files on a worker thread, unless a look is /// still running (or the build has no files to look at: the web app). pub fn start_link_scan(&mut self) { @@ -95,8 +102,10 @@ impl Session { let opened_by = st.opened_by.clone(); let marker_doc = st.show_missing_links.then(|| st.doc.clone()); if files.is_empty() { + // Nothing linked, so nothing missing: an empty scan, which also ends + // [`Session::missing_link_scan_due`] without starting a worker. if let Some(st) = self.docs.iter_mut().find(|st| st.uid == uid) { - st.missing_link_markers = None; + st.missing_link_markers = st.show_missing_links.then(|| (st.doc.clone(), vec![])); } return; } diff --git a/crates/engine/src/tests/missing_links.rs b/crates/engine/src/tests/missing_links.rs index be7244e532..f093a36ec2 100644 --- a/crates/engine/src/tests/missing_links.rs +++ b/crates/engine/src/tests/missing_links.rs @@ -116,6 +116,52 @@ fn missing_link_worker_refreshes_without_the_panel_and_ignores_old_art() { } } +#[test] +fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_watcher() { + use crate::cmd::links::probe_gate::{self, Gate}; + use std::time::Duration; + let dir = Folder::new("marker-toggle-nonblocking"); + let path = dir.file("art.png"); + write(&path, &png(20, 20, RED)); + let mut s = session(); + let id = place(&mut s, &path); + std::fs::remove_file(&path).unwrap(); + let stored = crate::tests_links::image(&s, id).link.unwrap().path; + let gate = Gate::close(&stored); + // The toggle returns while the probe of the (slow) linked file is held closed. + assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true})); + assert!(!gate.finished(), "the toggle waited for the file probe"); + assert!(s.doc().unwrap().missing_link_markers.is_none()); + assert!(s.doc().unwrap().marked_missing_links().is_empty()); + // The desktop app starts the watcher's look at once, and the probe runs there. + assert!(s.missing_link_scan_due()); + s.start_link_scan(); + assert!(!s.missing_link_scan_due()); + assert_eq!(gate.entered(Duration::from_secs(10)).as_deref(), Some("link-watch")); + assert!(s.poll_link_scan().is_none(), "the look ended before its probe was released"); + gate.open(); + s.wait_link_scan(); + s.poll_link_scan().unwrap().unwrap(); + probe_gate::remove(&stored); + assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]); + assert!(!s.missing_link_scan_due()); + // Turning it on again while on keeps the markers; off clears them. + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert_eq!(s.doc().unwrap().marked_missing_links(), vec![id]); + s.execute("view.showMissingLinks", &json!({"on": false})).unwrap(); + assert!(!s.missing_link_scan_due()); +} + +#[test] +fn missing_link_scan_for_a_document_without_links_ends_without_a_worker() { + let mut s = session(); + s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(); + assert!(s.missing_link_scan_due()); + s.start_link_scan(); + assert!(s.link_scan.is_none()); + assert!(!s.missing_link_scan_due()); +} + #[test] fn missing_link_markers_include_placed_documents_and_exclude_hidden_art() { let dir = Folder::new("marker-placed"); diff --git a/crates/ui-egui/src/app/links.rs b/crates/ui-egui/src/app/links.rs index 7d91162908..32baa99baf 100644 --- a/crates/ui-egui/src/app/links.rs +++ b/crates/ui-egui/src/app/links.rs @@ -79,7 +79,9 @@ impl VectorcraftApp { let last: f64 = ctx.data(|d| d.get_temp(last_key)).unwrap_or(f64::NEG_INFINITY); // The active document as the last look saw it: its uid and revision. let (seen_key, doc) = (egui::Id::unique("linkWatch.seen"), self.session.active().map(|d| (d.uid, d.revision))); - if now - last >= 2.0 || (focused && !was_focused) { + // View › Show Missing Links just turned on: its first scan runs on the worker now, and + // the canvas repaints from the result (the toggle itself never reads files). + if now - last >= 2.0 || (focused && !was_focused) || self.session.missing_link_scan_due() { // Walking the document's links costs a pass over it: only when a look is due. // `start_link_scan` starts none for a document without links, which then doesn't // wake the app for looks of its own (any frame still looks once one is due). diff --git a/docs/mcp.md b/docs/mcp.md index d9bace9acb..092b8e7c79 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -27,8 +27,10 @@ Use `run_command` (or its `command_run` alias) with these engine commands: `links.marked` refreshes file status and returns `{on, images: [{id, bounds: [x0, y0, x1, y1]}]}` for visible missing linked images and placed documents in the active document. When the toggle is off, `images` is empty; `links.list {show: "missing"}` still lists missing -links independently. Neither command changes selection or undo history. The desktop canvas -draws a red outline and badge, checks files in the background about every two seconds even +links independently. Neither command changes selection or undo history. `view.showMissingLinks` +never reads linked files, so it returns at once even for a large or slow file; `links.marked` is +the explicit, synchronous inspection. The desktop canvas draws a red outline and badge, scans +files in the background as soon as the toggle turns on and then about every two seconds even with the Links panel closed, and removes markers after repair. The toggle is per open document and starts off on reopen. Markers are never saved as artwork, rendered into exports or printing, or exposed as selectable objects. Headless mode exposes the same state and From a8cd6180cefc3a238760796dd6f4957756d4c604 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 20:47:22 -0800 Subject: [PATCH 022/334] Scripts: fix further review findings in the layer and path items - Point changes that add, remove or replace points deselect the path's direct-selected anchors even when the counts come out the same; path.setAnchors takes `reshaped` for this and refuses a non-boolean. - Moving points or handles, changing a point's type or setting `closed` keeps the index of where each subpath's points start. - A failed write keeps the waiting point changes. - Restoring the selection keeps a segment-only path to its segments. - getIsFileOpen folds `\` and letter case only on Windows. - Assigning `undefined` to Document.selection throws with nothing changed. - A document's path list is charged for the objects it looks at. - A made path keeps an id above 2^53. - A host object's handle is charged to the heap limit. - docs/mcp.md states that node.move into a compound path also needs its layer and groups shown and unlocked and no locked artboard. --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/path.rs | 13 +++- crates/engine/src/script/dom.rs | 37 +++++++--- crates/engine/src/script/dom/paths.rs | 81 ++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 63 +++++++++++++++- crates/engine/src/tests/script_dom_paths.rs | 34 +++++++++ crates/js/src/heap.rs | 7 ++ crates/js/src/host_classes.rs | 2 +- docs/mcp.md | 18 +++-- 9 files changed, 212 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 67f6cee727..02ed82d101 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -120,7 +120,7 @@ pub fn specs() -> Vec { "Reorder", [], None, - "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", + "{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard, and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does", has_doc, move_node ), diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index cc11f6f824..06d089ab08 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -68,7 +68,7 @@ pub fn specs() -> Vec { "Set Anchors", [], None, - "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}]} replace a path's geometry", + "{id, subpaths: [{anchors: [{x,y,in?,out?,smooth?: bool (left out: smooth when both handles are pulled out and in line)}], closed}], reshaped?: bool (true: the anchors were added, removed or replaced, so the path's direct-selected anchors are deselected even when each subpath keeps its count)} replace a path's geometry", has_doc, set_anchors ), @@ -757,14 +757,19 @@ fn set_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>>()?, ); + let replaced = match p.get("reshaped") { + None => false, + Some(Value::Bool(v)) => *v, + Some(_) => return Err(bad("path.setAnchors", "reshaped must be a boolean")), + }; s.edit("Reshape", |d, sel| { let counts = |pd: &PathData| pd.subpaths.iter().map(|sp| sp.anchors.len()).collect::>(); let path = path_mut(d, id)?; - let reshaped = counts(path) != counts(&data); + let reshaped = replaced || counts(path) != counts(&data); *path = data; super::object::resnap(d, id); - // Direct-selected anchors and segments are kept by index: when anchors were added or - // removed, the path is deselected rather than left with other anchors selected. + // Direct-selected anchors and segments are kept by index: when anchors were added, + // removed or replaced, the path is deselected rather than left with other anchors selected. if reshaped && (sel.anchors.remove(&id).is_some() | sel.segments.remove(&id).is_some()) { sel.objects.retain(|o| *o != id); sel.prune(d); diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index b6a1160e28..2a716a1bb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -44,6 +44,8 @@ use crate::{DocState, Document, NodeId, NodeKind, Session}; mod colors; pub(super) mod layers; mod paths; +#[cfg(test)] +pub(crate) use paths::index_builds; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -112,6 +114,12 @@ pub(super) struct State { /// How many times [`paths`] changed the waiting point changes, which makes a /// [`paths::PointIndex`] of them stale. pending_changes: Cell, + /// Whether the waiting point changes added, removed or replaced points, so that writing them + /// deselects the path's direct-selected anchors even when the counts come out the same. + pending_reshaped: Cell, + /// The path [`flush`] is writing reshaped changes to, whose direct-selected anchors and + /// segments [`on_doc`] does not select again. + reshaping: Cell>, /// Where the points of the path the run last read points of start, by subpath ([`paths`]). point_index: RefCell>, /// How many times the points the run read of each path went stale, by document uid and path id @@ -626,12 +634,15 @@ fn restore_selection(h: &Host, doc: &Document, before: &crate::doc::Selection) - command(h, "select.set", &json!({"ids": kept.iter().map(|i| i.0).collect::>()}))?; } else { // One `select.anchorsMany` selects every object in its order: a partly selected path with - // its anchors, a whole path with all of them and any other object with none. + // its anchors, a whole path with all of them and any other object with none. A path with + // only segments selected gets no anchors here, so `select.segments` below selects it with + // just those segments. let items: Vec = kept .iter() .map(|i| { let anchors: Vec<[usize; 2]> = match before.anchors.get(i) { Some(a) => a.iter().map(|(p, k)| [*p, *k]).collect(), + None if before.segments.contains_key(i) => Vec::new(), None => doc.node(*i).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, k, _)| [s, k]).collect()).unwrap_or_default(), }; json!({"id": i.0, "anchors": anchors}) @@ -747,15 +758,16 @@ fn on_doc_layer( let s = h.session.borrow(); s.active().filter(|st| st.uid == uid).map(|st| st.doc.clone()) }; - // Anchors and segments are selected by index: a path that gained or lost anchors is not - // selected again, so that other anchors of it are not selected in their place. + // Anchors and segments are selected by index: a path that gained, lost or replaced anchors + // is not selected again, so that other anchors of it are not selected in their place. if let Some(doc) = &doc { let counts = |d: &Document, id: NodeId| { d.node(id).and_then(|n| n.path_data()).map(|p| p.subpaths.iter().map(|sp| sp.anchors.len()).collect::>()) }; + let reshaped = h.dom.reshaping.get().filter(|it| it.doc.uid == uid).map(|it| it.id); let partial: Vec = before.anchors.keys().chain(before.segments.keys()).copied().collect(); for id in partial { - if counts(&old, id) != counts(doc, id) { + if reshaped == Some(id) || counts(&old, id) != counts(doc, id) { before.anchors.remove(&id); before.segments.remove(&id); before.objects.retain(|o| *o != id); @@ -840,13 +852,15 @@ fn app_set_coords(h: &Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// A path as `getIsFileOpen` compares it: `\` and `/` alike, and on Windows paths (a drive letter -/// or a `\`) letters in one case. +/// A path as `getIsFileOpen` compares it, without a trailing `/`: on Windows, `\` and `/` alike and +/// letters in one case; elsewhere `\` is part of a name and case counts. fn path_key(p: &str) -> String { - let windows = p.contains('\\') || p.as_bytes().get(1) == Some(&b':'); - let p = p.replace('\\', "/"); - let p = p.trim_end_matches('/').to_string(); - if windows { p.to_lowercase() } else { p } + path_key_on(p, cfg!(windows)) +} + +/// [`path_key`] for Windows when `windows`, else for macOS and Linux. +pub(crate) fn path_key_on(p: &str, windows: bool) -> String { + if windows { p.replace('\\', "/").trim_end_matches('/').to_lowercase() } else { p.trim_end_matches('/').to_string() } } /// `app.getIsFileOpen(path)`: whether a document open in the run has the file `path`. The path is @@ -1391,7 +1405,8 @@ fn selection_of(h: &Host, uid: u64) -> Answer { /// `[]`. Every one must be an object of that document that can be selected. fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result, HostError> { let list: Vec<&Data> = match v { - Data::Null | Data::Undefined => Vec::new(), + Data::Null => Vec::new(), + Data::Undefined => return Err(HostError::Type("the selection takes a page item, a list of them, null or [], not undefined".into())), Data::Array(a) if a.len() > MAX_LISTED => return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects"))), Data::Array(a) => a.iter().collect(), d => vec![d], diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index 19ad6ac4fb..e6867d8b55 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, coordinate, edit_item, editable, find_doc, float, - frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, point_get, - point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, colors, command, command_value, coordinate, edit_item, editable, + find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, + point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -176,6 +176,18 @@ impl PointIndex { } } +#[cfg(test)] +thread_local! { + /// How many times [`point_place`] built a [`PointIndex`] on this thread. + static INDEX_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times a [`PointIndex`] was built on this thread. +#[cfg(test)] +pub(crate) fn index_builds() -> u64 { + INDEX_BUILDS.with(std::cell::Cell::get) +} + /// The number of points of the path of `item`, its waiting point changes included, and the subpath /// and the place in it of point `i` when `i` is given and in the path. The index of the path's /// subpaths is kept in [`super::State`] until the path's points change. @@ -198,6 +210,8 @@ fn point_place(h: &super::Host, item: Item, i: Option) -> std::result::Re } }); if !fresh { + #[cfg(test)] + INDEX_BUILDS.with(|n| n.set(n.get() + 1)); let index = read_points(h, item, |subs| PointIndex::new(key, source, subs))?; *h.dom.point_index.borrow_mut() = Some(index); } @@ -230,12 +244,27 @@ fn read_points(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T) /// locked, unless it changes nothing. A path that is aligned to the pixel grid, or is in an object /// that is, is written at once, so that its points read as the grid snaps them. fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) -> T) -> std::result::Result { - h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + edit_points_keeping(h, item, false, f) +} + +/// [`edit_points`]. With `counts_kept`, `f` leaves the number of subpaths and of points in each as +/// they are, so a [`PointIndex`] of the waiting changes stays good. +fn edit_points_keeping( + h: &super::Host, + item: Item, + counts_kept: bool, + f: impl FnOnce(&mut Vec) -> T, +) -> std::result::Result { if let Some((waiting, subs)) = &mut *h.dom.pending.borrow_mut() && same_path(*waiting, item) { + if !counts_kept { + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); + h.dom.pending_reshaped.set(true); + } return Ok(f(subs)); } + h.dom.pending_changes.set(h.dom.pending_changes.get().wrapping_add(1)); flush(h)?; let mut subs = read_path(h, item, |_, _, pd| pd.subpaths.clone())?; let r = f(&mut subs); @@ -249,6 +278,7 @@ fn edit_points(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec) return Err(cannot_edit(item.id)); } *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(!counts_kept); if aligned { flush(h)?; } @@ -262,9 +292,13 @@ fn write_path(h: &super::Host, item: Item, subs: Vec) -> std::result::R } /// Writes the waiting point changes of a path ([`edit_points`]) with one `path.setAnchors`, unless -/// the path has those points already. +/// the path has those points already. Changes that added, removed or replaced points are written +/// with `reshaped`, so the path's direct-selected anchors are deselected even when the counts come +/// out the same, and the selection the run puts back leaves them out. When the write fails, the +/// changes stay waiting. pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { let Some((item, subs)) = h.dom.pending.borrow_mut().take() else { return Ok(()) }; + let reshaped = h.dom.pending_reshaped.replace(false); let same = { let s = h.session.borrow(); let node = s.documents().iter().find(|d| d.uid == item.doc.uid).and_then(|st| st.doc.node(item.id)); @@ -277,7 +311,18 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> { } let subpaths: Vec = subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::>(), "closed": sp.closed})).collect(); - edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))?; + let mut params = json!({"id": item.id.0, "subpaths": subpaths}); + if reshaped { + params["reshaped"] = json!(true); + } + let kept = h.dom.reshaping.replace(reshaped.then_some(item)); + let r = edit_item(h, item, "path.setAnchors", ¶ms); + h.dom.reshaping.set(kept); + if let Err(e) = r { + *h.dom.pending.borrow_mut() = Some((item, subs)); + h.dom.pending_reshaped.set(reshaped); + return Err(e); + } Ok(()) } @@ -336,8 +381,8 @@ pub(super) const PATH_LISTS: usize = 4; /// The ids of a document's paths, in the order of its page items, or of the paths directly in the /// layer or group `container`, topmost first. The last [`PATH_LISTS`] lists are kept while their -/// documents are unchanged, so a loop over a collection builds its list once. A new list of a -/// container is charged by the objects it looks at. +/// documents are unchanged, so a loop over a collection builds its list once. A new list is +/// charged by the objects it looks at. fn path_items(h: &super::Host, st: &DocState, container: Option) -> std::result::Result>, HostError> { { let mut lists = h.dom.paths.borrow_mut(); @@ -357,6 +402,7 @@ fn path_items(h: &super::Host, st: &DocState, container: Option) -> std: } None => { let all = super::page_items(h, st); + h.charge_call(all.len() as u64)?; Rc::new(all.iter().copied().filter(|i| st.doc.node(*i).is_some_and(is_path)).collect()) } }; @@ -464,13 +510,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer { Ok(Data::Undefined) } -/// The id in the result of a command that made an object. -fn made_id(r: &Data) -> std::result::Result { - let id = match r { - Data::Object(o) => o.iter().find(|(k, _)| k == "id").and_then(|(_, v)| if let Data::Number(n) = v { whole(*n) } else { None }), - _ => None, - }; - id.map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) +/// The id in the result of a command that made an object, read from the command's own result (not +/// the script's copy, whose numbers are exact only up to 2^53). +fn made_id(r: &(Data, Value)) -> std::result::Result { + r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into())) } /// The error of a path made in a layer or group that is hidden or locked, or that is in a hidden or @@ -516,7 +559,7 @@ fn make_in( /// contents ([`make_in`]), and reverses the new path's direction when `reversed`. → the new path. fn make(h: &super::Host, doc: Doc, container: Option, id: &str, params: &Value, reversed: bool) -> Answer { make_in(h, doc, container, |h| { - let id = made_id(&drawing_normally(h, || command(h, id, params))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, id, params))?)?; if reversed { command(h, "path.reverse", &json!({"ids": [id.0]}))?; } @@ -673,7 +716,7 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer { let ap = h.session.borrow().new_art(); ap.fill_paint().is_none() && ap.stroke_paint().is_none() }; - let id = made_id(&drawing_normally(h, || command(h, "path.create", &json!({"d": ""})))?)?; + let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?)?; if unpainted { keeping_paint(h, || command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]})))?; } @@ -697,7 +740,7 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer { fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer { let closed = boolean(arg(a, 1), "closed")?; let item = this_path(h, a)?; - edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; + edit_points_keeping(h, item, true, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?; Ok(Data::Undefined) } @@ -1426,7 +1469,7 @@ fn read_point(h: &super::Host, a: &[Data], f: impl FnOnce(&super::Frame, Coords, /// coordinates (for a point property) or the value itself. fn edit_point(h: &super::Host, a: &[Data], f: impl FnOnce(&mut Anchor)) -> Answer { let (item, s, j) = this_point_place(h, a)?; - edit_points(h, item, |subs| { + edit_points_keeping(h, item, true, |subs| { if let Some(an) = subs.get_mut(s).and_then(|sp| sp.anchors.get_mut(j)) { f(an); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5368a64c2f..06bf3e83b0 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -855,6 +855,32 @@ fn a_page_item_with_a_large_id_keeps_its_id() { assert!(s.active().unwrap().doc.node(a).is_none()); } +/// A path the script makes keeps its id when the id is past 2^53, where the script's numbers round. +#[test] +fn a_path_made_with_a_large_id_keeps_its_id() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let big = (1u64 << 53) + 1; + s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big)); + let out = log(&mut s, "var p = app.activeDocument.pathItems.rectangle(10, 10, 20, 20); p.name = 'big'; vc.log(p.name);"); + assert_eq!(out, vec![json!("big")]); + let d = &s.active().unwrap().doc; + assert_eq!(d.node(NodeId(big)).and_then(|n| n.name.clone()).as_deref(), Some("big")); +} + +/// Assigning `undefined` to the selection, as a lookup past the end of a list gives, throws and +/// leaves the selection as it was; `null` still clears it. +#[test] +fn assigning_undefined_to_the_selection_throws() { + let (mut s, a, _) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let e = failure(&mut s, "var d = app.activeDocument; d.selection = d.pageItems[99];"); + assert!(e.contains("TypeError") || e.contains("not undefined"), "{e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); + log(&mut s, "app.activeDocument.selection = null;"); + assert!(s.active().unwrap().selection.objects.is_empty()); +} + #[test] fn only_class_constructors_construct() { let (mut s, _, _) = doc(); @@ -1349,6 +1375,18 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let _ = std::fs::remove_file(path); } +/// `getIsFileOpen` folds `\` into `/` and letter case only by Windows' rules: on macOS and Linux a +/// `\` is part of a file name, so `a\b.svg` is not the file `b.svg` in the folder `a`. +#[test] +fn get_is_file_open_compares_paths_by_the_platform_s_rules() { + use crate::script::dom::path_key_on; + assert_ne!(path_key_on("/tmp/work/a\\b.svg", false), path_key_on("/tmp/work/a/b.svg", false)); + assert_ne!(path_key_on("/tmp/work/A.svg", false), path_key_on("/tmp/work/a.svg", false)); + assert_eq!(path_key_on("/tmp/work/", false), path_key_on("/tmp/work", false)); + assert_eq!(path_key_on("C:\\Work\\A.svg", true), path_key_on("c:/work/a.svg", true)); + assert_eq!(path_key_on("C:\\Work\\", true), path_key_on("c:/work", true)); +} + #[test] fn hostile_dom_values_do_not_reenter_or_exceed_limits() { let (mut s, _, _) = doc(); @@ -1626,12 +1664,15 @@ fn a_layers_and_a_groups_path_items_list_only_the_paths_directly_in_them_topmost vc.log(P.length); vc.log(P[0].width); vc.log(P.typename); vc.log(P.parent.typename);\ vc.log(G.length); vc.log(G[0].width); vc.log(G[1].width); vc.log(G.parent.typename); vc.log(d.pathItems.length);\ var sub = L.layers.add(); sub.pathItems.rectangle(10, 10, 5, 5); vc.log(L.pathItems.length); vc.log(sub.pathItems.length);\ - G[1].name = 'B'; vc.log(G.getByName('B') === G[1]); vc.log(G.index('B') === G[1]); vc.log(P[1] === undefined);", + sub.pathItems[0].name = 'B'; P[0].name = 'B'; G[1].name = 'B'; G[0].name = 'B';\ + vc.log(G.getByName('B') === G[0]); vc.log(G.index('B') === G[0]); vc.log(P.getByName('B') === P[0]); vc.log(P[1] === undefined);", ); let expected = [json!(1), json!(30), json!("PathItems"), json!("Layer"), json!(2), json!(70), json!(50), json!("GroupItem"), json!(3), json!(1), json!(1)]; assert_eq!(out[..11], expected); - assert_eq!(out[11..], [json!(true), json!(true), json!(true)]); + // With the sublayer's path above the group, the layer's own path and both of the group's paths + // named `B`, each collection's named lookups give its own topmost path. + assert_eq!(out[11..], [json!(true), json!(true), json!(true), json!(true)]); } #[test] @@ -1716,6 +1757,22 @@ fn path_items_of_a_hidden_or_locked_layer_or_group_make_no_path() { assert!(failure(&mut s, src).contains(REFUSED), "{src}"); assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); } + // Caught inside the script, each refusal leaves both collections as they were, and the group, + // shown and unlocked itself, is refused for its locked layer. + let out = log( + &mut s, + "var L = app.activeDocument.layers[0], g = app.activeDocument.groupItems[0], m = [];\ + var n = [L.pathItems.length, g.pathItems.length];\ + try { L.pathItems.rectangle(10, 10, 5, 5); } catch (e) { m.push(e.message); }\ + try { g.pathItems.add(); } catch (e) { m.push(e.message); }\ + try { g.pathItems.ellipse(); } catch (e) { m.push(e.message); }\ + vc.log(m); vc.log([L.pathItems.length, g.pathItems.length]); vc.log(n);", + ); + let refused: Vec<&str> = out[0].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(refused.len(), 3, "{out:?}"); + assert!(refused.iter().all(|m| m.contains(REFUSED)), "{out:?}"); + assert_eq!(out[1], out[2], "the collections are unchanged inside the script"); + assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), locked); s.execute("layer.setProps", &json!({"id": lid.0, "locked": false})).unwrap(); s.execute("layer.setProps", &json!({"id": gid.0, "visible": false})).unwrap(); let hidden = format!("{:?}", s.active().unwrap().doc.layers); @@ -1981,7 +2038,7 @@ fn a_compound_paths_path_items_add_makes_the_path_inside_it() { let d = &s.active().unwrap().doc; let compound = d.layers[0].children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Compound { .. })).unwrap(); assert_eq!(compound.children().unwrap().len(), 2); - assert!(undo_steps(&s) > steps); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); } #[test] diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 99e83b4ddc..0ac6a14eff 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -170,6 +170,12 @@ fn removing_a_point_deselects_a_path_with_direct_selected_anchors() { s.execute("select.anchors", &json!({"id": b.0, "anchors": [[0, 1]], "mode": "set"})).unwrap(); log(&mut s, "var p = app.activeDocument.pathItems[1].pathPoints[0]; p.anchor = [p.anchor[0] + 1, p.anchor[1]];"); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + // Removing a point and adding one in a single write ends with as many points, but the + // selected anchor's index now names another point, so the path is deselected. + log(&mut s, "var pp = app.activeDocument.pathItems[1].pathPoints; pp[0].remove(); pp.add();"); + let st = s.active().unwrap(); + assert_eq!(st.doc.node(b).and_then(|n| n.path_data()).map(|p| p.anchors().count()), Some(3)); + assert!(!st.selection.anchors.contains_key(&b), "{:?}", st.selection); } #[test] @@ -188,6 +194,14 @@ fn set_anchors_with_other_anchor_counts_deselects_the_paths_anchors() { let moved = json!([{"anchors": [pt(1.0, 0.0), pt(9.0, 0.0), pt(9.0, 9.0)], "closed": true}]); s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved})).unwrap(); assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + // `reshaped` deselects them at the same count; a value that is not a boolean is refused. + for bad in [json!(null), json!(1), json!("yes")] { + assert!(s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": bad})).is_err(), "{bad}"); + } + assert_eq!(s.active().unwrap().selection.anchors[&b].len(), 1); + s.execute("path.setAnchors", &json!({"id": b.0, "subpaths": moved, "reshaped": true})).unwrap(); + let sel = &s.active().unwrap().selection; + assert!(!sel.objects.contains(&b) && !sel.anchors.contains_key(&b), "{sel:?}"); } /// Points are found by their index across subpaths, through changes that wait to be written and @@ -220,6 +234,26 @@ fn points_are_found_across_subpaths_as_their_counts_change() { assert_eq!(counts, vec![1, 3]); } +/// Moving every point of a path, one at a time, keeps the index of where its subpaths' points +/// start: the index is built again only when a change adds or removes points. +#[test] +fn moving_each_point_keeps_the_index_of_the_subpaths() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + let subs: Vec = + (0..50).map(|i| json!({"anchors": [{"x": i, "y": 0, "in": [i, 0], "out": [i, 0], "smooth": false}], "closed": false})).collect(); + s.execute("path.setAnchors", &json!({"id": a.0, "subpaths": subs})).unwrap(); + let before = crate::script::dom::index_builds(); + let out = log( + &mut s, + "var q = app.activeDocument.pathItems[0].pathPoints; for (var i = 0; i < q.length; i++) q[i].anchor = [i, 7]; vc.log(q[49].anchor);", + ); + assert_eq!(out, vec![json!([49, 7])]); + let built = crate::script::dom::index_builds() - before; + assert!(built <= 3, "the index was built {built} times"); +} + #[test] fn set_entire_path_replaces_points_and_keeps_closed() { let (mut s, a, _) = doc(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index bddab84fd6..f541c221e6 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -779,11 +779,18 @@ fn trace_object(o: &Object, work: &mut Vec, strings: &mut StringSizes) -> u extra = XML_LIST_BYTES + XML_REF_BYTES * (state.input.len() + state.kept.len()); } Class::UnitValue(_) => extra = UNIT_VALUE_BYTES, + Class::Host(h) => extra = host_handle_bytes(h.handle.len()), _ => {} } OBJECT_BYTES + PROP_BYTES * (o.props.len() + syms) + extra } +/// The bytes an object of a host class keeps for a handle of `numbers` numbers: the handle itself +/// and its copy in the realm's map of host objects. +pub(crate) fn host_handle_bytes(numbers: usize) -> usize { + numbers.saturating_mul(16) +} + fn add_name(name: &XmlName, strings: &mut StringSizes) { strings.add_key(&name.local); name.uri.iter().chain(&name.prefix).for_each(|k| strings.add_key(k)); diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index de41e7ef6f..0d0b7ec69c 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -155,7 +155,7 @@ impl Interp { } return Ok(Value::Object(id)); } - self.reserve_heap(crate::heap::OBJECT_BYTES)?; + self.reserve_heap(crate::heap::OBJECT_BYTES.saturating_add(crate::heap::host_handle_bytes(handle.len())))?; let mut o = Object::new(Class::Host(HostObj { class, handle: handle.into() }), Some(proto)); o.extensible = false; let id = self.heap.alloc_object(o); diff --git a/docs/mcp.md b/docs/mcp.md index 72d0c0f0f1..7ba136cb52 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2749,11 +2749,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, - a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + a list of at most 10,000, `null` or `[]`; `undefined` (such as a page item looked up past the end of a list) + throws a `TypeError`, and an object that cannot be selected throws `Cannot select`, each with nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or with `selected`. Assigning a page item's `selected` leaves the direct-selected anchors and segments of the other - selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, - letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when + selected objects selected. `getIsFileOpen` compares the path with the open documents' files as text (on Windows, + letter case is ignored and `\` matches `/`; on macOS and Linux, `\` is part of a file name) and does not resolve the + path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, Document and PageItem pages list, such as `Document.views`, `PageItem.blendingMode`, `PageItem.rotate` and @@ -2825,7 +2826,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group, index 0 puts it directly above the clipping path), as one undo step named Group, and gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path. - The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path, where the path + The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path (its layer and + groups shown and unlocked too, and not on a locked artboard), where the path gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel alignment. @@ -2859,6 +2861,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one `path.setAnchors` before the script uses any other member or command, or the points of another path, and when the script ends; a path aligned to the pixel grid, or in an object that is, is written at each change, so its points read as the grid snaps them. + Writing changes that added, removed or replaced points deselects the path's direct-selected anchors, even when the + path ends with as many points as before; changes that only move points or handles, change a point's type or set + `closed` keep them selected. `pathPoints` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/) has `length`, `[i]`, `index(i)`, `add()` and `removeAll()`, and each `PathPoint` (https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/) has `anchor`, @@ -6744,7 +6749,8 @@ and `layerRows`, the rows highlighted in the panel. that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts - a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that + a path into a shown, unlocked compound path whose layer and groups are also shown and unlocked and that is not on + a locked artboard (see `object.newGroup` for the paint the path keeps or takes). A row that either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join, From 637facb057236984dfb89bfe8707fdbf200bb639 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:27:19 -0800 Subject: [PATCH 023/334] Scripts: empty objects read zero control bounds and turn or scale as no-ops - controlBounds of an object with nothing in it reads zeros, like its geometric and visible bounds. - path.rotate and path.resize of a path with no anchors change nothing. - The path tests make the first rectangle last, so pathItems[0] is the topmost path as pageItems lists it. --- crates/engine/src/script/dom.rs | 9 ++++++--- crates/engine/src/script/dom/paths.rs | 17 ++++++++++------- crates/engine/src/tests/script_dom.rs | 8 ++++---- crates/engine/src/tests/script_dom_paths.rs | 13 +++++++++++-- .../tests/it/script_host_vs_scriptcheck.rs | 5 ++++- 5 files changed, 35 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 4a40865c1f..2ef5503fb0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1851,10 +1851,13 @@ fn item_control(h: &Host, a: &[Data]) -> Answer { let (r, f) = with_doc(h, item.doc, |_, st| { let visible = st.doc.bounds_of(&[item.id], true); let handles = st.doc.node(item.id).and_then(handles_box); - let r = vectorcraft_geom::union_opt(visible, handles).ok_or_else(|| HostError::Error("the object has no bounds".into()))?; - Ok::<_, HostError>((r, frame(st)?)) + Ok::<_, HostError>((vectorcraft_geom::union_opt(visible, handles), frame(st)?)) })?; - Ok(f.bounds(h.dom.coords.get(), r)) + // An object with nothing in it has no bounds, and they read as zeros like its other bounds. + match r { + Some(r) => Ok(f.bounds(h.dom.coords.get(), r)), + None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])), + } } fn item_position(h: &Host, a: &[Data]) -> Answer { diff --git a/crates/engine/src/script/dom/paths.rs b/crates/engine/src/script/dom/paths.rs index e735b8f153..ffe1a23264 100644 --- a/crates/engine/src/script/dom/paths.rs +++ b/crates/engine/src/script/dom/paths.rs @@ -58,9 +58,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, Realm, Ru use vectorcraft_tools::params::gradient_params; use super::{ - Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, editable, - find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, point, - point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, + Answer, Coords, Doc, Item, Link, NOT_FOUND, STALE_ITEM, arg, boolean, class, class_text, colors, command, command_value, coordinate, edit_item, + editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method, named, num, number, on_doc, pair, + point, point_get, point_method, point_property, property, this_doc, typename_of, whole, with_doc, }; use crate::{DocState, NodeId, NodeKind}; @@ -1202,8 +1202,10 @@ fn path_rotate(h: &super::Host, a: &[Data]) -> Answer { let place = about_name(arg(a, 6))?; let mut params = json!({"angle": angle}); transform_options(a, 2, &mut params)?; - if angle.rem_euclid(360.0) != 0.0 { - let (r, _) = item_rect(h, item, false)?; + // A path with no anchors has no bounds to turn about, and turning it changes nothing. + if angle.rem_euclid(360.0) != 0.0 + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.rotate", params)?; @@ -1234,8 +1236,9 @@ fn path_resize(h: &super::Host, a: &[Data]) -> Answer { } // The scale and the new stroke weight are one edit: a failure of either undoes both. super::atomically(h, |h| { - if sx != 100.0 || sy != 100.0 { - let (r, _) = item_rect(h, item, false)?; + if (sx != 100.0 || sy != 100.0) + && let (Some(r), _) = item_rect(h, item, false)? + { let origin = about(h, item, place, r)?; params["origin"] = json!([origin.x, origin.y]); edit_path(h, item, "object.scale", params)?; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 0be17f5d71..09c856dbcf 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -717,10 +717,10 @@ fn selecting_an_item_keeps_the_direct_selected_anchors_of_others() { s.execute("select.add", &json!({"ids": [b.0]})).unwrap(); let anchors = s.active().unwrap().selection.anchors.clone(); assert!(anchors.contains_key(&a)); - log(&mut s, "app.activeDocument.pageItems[1].selected = false;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = false;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.clone()), (vec![a], anchors.clone())); - log(&mut s, "app.activeDocument.pageItems[1].selected = true;"); + log(&mut s, "app.activeDocument.pageItems[0].selected = true;"); let sel = &s.active().unwrap().selection; assert_eq!((sel.objects.clone(), sel.anchors.get(&a)), (vec![a, b], anchors.get(&a))); } @@ -2428,7 +2428,7 @@ fn every_page_item_has_its_layer_and_members_check_this() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\ - vc.log(p.layer.name); vc.log(d.pageItems[0].layer.name); vc.log(p.layer.layers.typename);\ + vc.log(p.layer.name); vc.log(d.pageItems[1].layer.name); vc.log(p.layer.layers.typename);\ vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);", ); assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]); @@ -2542,7 +2542,7 @@ fn page_items_report_their_available_members_as_their_own() { ); assert_eq!(out[0], json!([true, true, true, true, true, true, true])); // Members that are not available yet, unknown names and inherited ones are not the object's own. - assert_eq!(out[1], json!([false, false, false, false, false, false])); + assert_eq!(out[1], json!([false, true, true, false, false, false])); // `for`-`in` lists the properties, not the methods or the members that are not available yet. assert_eq!(out[2], json!([true, true, -1, -1])); } diff --git a/crates/engine/src/tests/script_dom_paths.rs b/crates/engine/src/tests/script_dom_paths.rs index 0ac6a14eff..94b638ccc7 100644 --- a/crates/engine/src/tests/script_dom_paths.rs +++ b/crates/engine/src/tests/script_dom_paths.rs @@ -30,8 +30,9 @@ fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId { fn doc() -> (Session, NodeId, NodeId) { let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); - let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); + // `pathItems[0]` is the topmost path, so `a` is made last. let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0); + let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0); s.execute("select.none", &json!({})).unwrap(); (s, a, b) } @@ -564,6 +565,14 @@ fn identity_transforms_of_an_empty_path_do_nothing() { } } +#[test] +fn turning_or_scaling_an_empty_path_changes_nothing() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + log(&mut s, "var n = app.activeDocument.pathItems.add(); n.rotate(90); n.resize(50, 50);"); + assert_eq!(undo_steps(&s), 1, "only the path is added"); +} + /// The paint of the fill (`fill`) or stroke of `id`. fn paint_of(s: &Session, id: NodeId, fill: bool) -> Paint { let n = node(s, id); @@ -935,7 +944,7 @@ fn locked_paths_and_wrong_objects_are_refused() { } assert_eq!(art(&s), before); s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap(); - let e = failure(&mut s, "var t = app.activeDocument.pageItems[2]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); + let e = failure(&mut s, "var t = app.activeDocument.pageItems[0]; Object.getOwnPropertyDescriptor(PathItem.prototype, 'closed').get.call(t);"); assert!(e.contains("not a PathItem"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(PathPoint.prototype, 'anchor').get.call({});"); assert!(e.contains("not a PathPoint"), "{e}"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index f5a2e83aed..24722a3adc 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -153,7 +153,10 @@ const INSIDE: &[(&str, &str)] = &[ width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition", ), ("PathItems.", "prototype"), - ("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename"), + ( + "PathItems.prototype.", + "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename", + ), ("PathItem.", "prototype"), ( "PathItem.prototype.", From 994bad51142c2467458019a69daa35cbad5d3eda Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 14:58:23 +0530 Subject: [PATCH 024/334] 5547: markers ask only whether a linked file is missing missing_markers called probe, which reads and hashes a linked file whose size or modification time differs from its stored link. With Update Links set to Manually that difference stays, so every look of the link watcher read the whole file again while the markers were on, for a Modified result the markers throw away. They now use missing(), which returns the same answer as probe for Missing (not found, or found but unreadable) and opens a changed file without reading its content. probe is unchanged for its other callers. The toggle test also checks that no probe runs on the calling thread. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/links.rs | 20 +++++++++++++++++++- crates/engine/src/tests/missing_links.rs | 1 + 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 2ceb25b5fa..509a3959cb 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -487,6 +487,24 @@ fn probe(g: &Group, base: LinkBase) -> (Status, Option) { (if same { Status::Ok } else { Status::Modified }, Some(f)) } +/// Whether [`probe`] would find group `g`'s file missing, without reading or hashing its content. +/// A changed file is opened to check it can be read, and nothing more: the canvas markers ask only +/// this, and with Update Links set to Manually a changed file keeps differing from its stored link, +/// so a full probe would read the whole file again on every look while the markers are on. +fn missing(g: &Group, base: LinkBase) -> bool { + #[cfg(test)] + probe_gate::hold(&g.link.path); + let Some(f) = locate(&g.link, base) else { return true }; + let l = &g.link; + if !g.plate_files.is_empty() && super::place::dcs::plate_files_changed(&g.plate_files, &f.path) { + return false; + } + if l.size == Some(f.size) && l.modified.is_some() && l.modified == f.modified { + return false; + } + fileio::read_file_head(&f.path, 0).is_err() +} + /// Is image `key` of `d` showing its preview (its file not read)? fn previewing(d: &Document, key: &str) -> bool { d.images.get(key).is_none_or(ImageBlob::is_proxy) @@ -2554,7 +2572,7 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap Vec { groups(doc, None) .iter() - .filter(|g| !g.ids.is_empty() && probe(g, base).0 == Status::Missing) + .filter(|g| !g.ids.is_empty() && missing(g, base)) .flat_map(|g| g.ids.iter().copied()) .filter(|id| doc.is_visible(*id)) .collect() diff --git a/crates/engine/src/tests/missing_links.rs b/crates/engine/src/tests/missing_links.rs index f093a36ec2..277d92b648 100644 --- a/crates/engine/src/tests/missing_links.rs +++ b/crates/engine/src/tests/missing_links.rs @@ -131,6 +131,7 @@ fn turning_missing_links_on_returns_before_the_file_probe_and_scans_on_the_link_ // The toggle returns while the probe of the (slow) linked file is held closed. assert_eq!(s.execute("view.showMissingLinks", &json!({"on": true})).unwrap(), json!({"on": true})); assert!(!gate.finished(), "the toggle waited for the file probe"); + assert_eq!(gate.entered(Duration::ZERO), None, "the toggle probed the file on the calling thread"); assert!(s.doc().unwrap().missing_link_markers.is_none()); assert!(s.doc().unwrap().marked_missing_links().is_empty()); // The desktop app starts the watcher's look at once, and the probe runs there. From e53bf6452bf1fd25e3c3602edd417582d0145f94 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 18:25:58 +0530 Subject: [PATCH 025/334] 5547: Show Missing Links is a switching label The View item reads Show or Hide Missing Links, so the engine lists it in SWITCHING_LABELS. Without it, main's menu checks fail: engine_commands_with_two_labels_are_known_to_the_engine and desktop_items_of_placeable_menus_are_known_to_the_engine (Hide Missing Links unknown to the engine), and a placed plug-in command named like either label would leave its plug-in's submenu. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/plugin.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index bb8d3372ae..da3b6f821a 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -629,6 +629,7 @@ pub const SWITCHING_LABELS: &[&str] = &[ "Lock Guides", "Hide Slices", "Show Print Tiling", + "Show Missing Links", "Lock Grid", "Edit Envelope", "Edit Contents", From 7038a2cb13c3d33156f08c506a80761cc9c28110 Mon Sep 17 00:00:00 2001 From: ruchirguitar Date: Fri, 27 Nov 2026 20:16:31 +0530 Subject: [PATCH 026/334] 5547: mark missing art shown or restored while the overlay is on missing_markers left out hidden artwork when it scanned, so a missing link on a hidden layer when View > Show Missing Links turned on got no marker once shown: until the next look on the desktop, and never in the web app, which has no link watch worker and marked only once, when the toggle turned on. The scan now keeps hidden art, and the canvas leaves it out while it is hidden (links.marked lists visible art as before). The web app now finds its markers again in place whenever the art changed (Session::mark_missing_links_in_place), so artwork restored or placed while the overlay is on is marked too. It has no files to read; the desktop still scans on the link watch worker, and the toggle reads no files on either. A regression covers hide, enable, show through the worker and in place, and delete then undo in place. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/links.rs | 24 +++++---------- crates/engine/src/link_watch.rs | 16 ++++++++++ crates/engine/src/tests/missing_links.rs | 39 ++++++++++++++++++++++++ crates/ui-egui/src/app.rs | 6 ++++ 4 files changed, 69 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 509a3959cb..20c93c4adc 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2567,15 +2567,12 @@ pub(crate) fn statuses(st: &crate::DocState) -> BTreeMap