From 1c7fc27b42a1a8438c868b704dc45eb933b8f6f9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:18:13 -0800 Subject: [PATCH 1/3] Scripts: app.selectTool picks a tool app.selectTool(name) takes a tool's id (pen), its label (Pen Tool) or a tool name in the form scripts pass, returns true, and makes that tool the current tool when the run ends without an error. The tool chosen last in a run counts, and a run that fails leaves the tool as it was. An unknown name throws, a name that is not a string throws a TypeError, and a name over 4,096 bytes throws a RangeError. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/script/dom.rs | 77 ++++++++++++++++++++++++++- crates/engine/src/script/mod.rs | 8 +++ crates/engine/src/tests/script_dom.rs | 29 ++++++++++ docs/mcp.md | 8 ++- docs/target-app-parity.md | 2 +- 5 files changed, 121 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index cb901014b5..a3456e8590 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -25,6 +25,9 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. +//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at +//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an +//! error. A run that fails leaves the tool as it was. //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; @@ -88,7 +91,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the lists of page items and the /// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read, /// each kept while its document is unchanged, whether a call's own savepoint ([`atomically`]) is -/// open, and the settings of each `DocumentPreset` the run made. +/// open, the settings of each `DocumentPreset` the run made, and the tool `app.selectTool` chose +/// last. #[derive(Default)] pub(super) struct State { coords: Cell, @@ -96,6 +100,7 @@ pub(super) struct State { locked: RefCell>, saving: Cell, presets: RefCell>>, + tool: Cell>, } impl State { @@ -103,6 +108,12 @@ impl State { pub(super) fn saving(&self) -> bool { self.saving.get() } + + /// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool + /// when the run ends without an error. + pub(super) fn chosen_tool(&self) -> Option<&'static str> { + self.tool.get() + } } /// Runs `f`, whose commands are kept together or put back together: when `f` fails, every @@ -732,6 +743,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer { Ok(Data::Bool(open)) } +/// The start of the tool names that scripts pass to `app.selectTool`, as the list at +/// gives them. +const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass + +/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the +/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's +/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own. +const TOOL_NAMES: &[(&str, &str)] = &[ + ("Select Tool", "selection"), + ("Direct Select Tool", "directSelection"), + ("Direct Object Select Tool", "groupSelection"), + ("Direct Lasso Tool", "lasso"), + ("Path Type Tool", "typeOnPath"), + ("Vertical Path Type Tool", "verticalTypeOnPath"), + ("Line Tool", "lineSegment"), + ("Shape Construction Regular Polygon Tool", "polygon"), + ("Shape Construction Star Tool", "star"), + ("Shape Construction Spiral Tool", "spiral"), + ("Brush Tool", "paintbrush"), + ("Freehand Tool", "pencil"), + ("Freehand Smooth Tool", "smooth"), + ("Freehand Erase Tool", "pathEraser"), + ("Corner Join Tool", "join"), + ("Knife Tool", "knife"), + ("New Twirl Tool", "twirl"), + ("Cyrstallize Tool", "crystallize"), + ("Planar Paintbucket Tool", "livePaintBucket"), + ("Planar Face Select Tool", "livePaintSelection"), + ("Mesh Editing Tool", "mesh"), + ("Gradient Vector Tool", "gradient"), + ("Crop Tool", "artboard"), + ("Slice Select Tool", "sliceSelection"), + ("Scroll Tool", "hand"), + ("Page Tool", "printTiling"), +]; + +/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the +/// list [`TOOL_NAME_PREFIX`] cites. +fn tool_named(name: &str) -> Option<&'static str> { + let tools = || vectorcraft_tools::catalog::all_tools(); + if let Some(t) = tools().find(|t| t.id == name || t.label == name) { + return Some(t.id); + } + let rest = name.strip_prefix(TOOL_NAME_PREFIX)?; + if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) { + return vectorcraft_tools::tool_info(id).map(|t| t.id); + } + tools().find(|t| t.label == rest).map(|t| t.id) +} + +/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The +/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar +/// does; the tool chosen last in a run is the one that counts. A name no tool has throws. +fn app_select_tool(h: &Host, a: &[Data]) -> Answer { + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) }; + if name.len() > MAX_TEXT_BYTES { + return Err(HostError::Range("the tool name is too long".into())); + } + let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?; + h.dom.tool.set(Some(id)); + Ok(Data::Bool(true)) +} + // ---- Documents ---- fn docs_length(h: &Host, _: &[Data]) -> Answer { @@ -1948,6 +2022,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)), + ("selectTool", method(l, app_select_tool)), ]); application.push(later(l, "Application", "beep")); let preset = { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index affacab584..dc4bd20008 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -2291,7 +2291,15 @@ impl Session { }); host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); + let tool = host.dom.chosen_tool(); self.end_job(job, false); + // The tool `app.selectTool` chose last becomes the current tool, as a choice on the + // toolbar makes it; the run's changes are kept when the tool cannot be chosen. + if let Some(id) = tool + && let Err(e) = self.select_tool(id, self.last_view) + { + report["toolError"] = json!(e.to_string()); + } self.script_report = Some(report.clone()); Ok(report) } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 60e3a71521..a0c6e8afbc 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1314,6 +1314,35 @@ fn prototype_changes_cannot_forge_a_page_item() { assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None); } +#[test] +fn select_tool_makes_the_named_tool_current_when_the_run_ends() { + let (mut s, _, _) = doc(); + assert_eq!(s.tool_id(), "selection"); + // A tool's id, its label and a name in the form scripts pass all choose it; the last one counts. + assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]); + assert_eq!(s.tool_id(), "pen"); + log(&mut s, "app.selectTool('Rectangle Tool');"); + assert_eq!(s.tool_id(), "rectangle"); + log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');"); + assert_eq!(s.tool_id(), "directSelection"); + log(&mut s, "app.selectTool('Adobe Select Tool');"); + assert_eq!(s.tool_id(), "selection"); + // An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool. + assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\"")); + assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named")); + let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }"); + assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]); + assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop")); + let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }"); + assert_eq!(out, vec![json!("TypeError")]); + assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long")); + assert_eq!(s.tool_id(), "selection"); + // With no document open the tool is chosen too. + let mut empty = Session::new(); + log(&mut empty, "app.selectTool('Adobe Freehand Tool');"); + assert_eq!(empty.tool_id(), "pencil"); +} + #[test] fn unsupported_members_say_so() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..5b4d5b342b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2622,7 +2622,13 @@ 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.selectTool(name)`. `selectTool` + (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942) takes a tool's id + (`pen`), its label (`Pen Tool`) or a tool name in the form that thread lists, returns `true`, and makes the tool it + names the current tool when the run ends without an error; the tool chosen last in a run is the one that counts, + and a run that fails leaves the tool as it was. A name no tool has throws `No tool is named ""`, a name that + is not a string throws a `TypeError`, and a name of more than 4,096 bytes throws a `RangeError`. Which tool each + name in that thread chooses is VectorCraft's own reading; names with no VectorCraft tool throw. `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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..607fd49b5e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - 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, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). `app.selectTool(name)` makes the named tool the current tool when the run ends (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `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 24d91e2acf564c5124618e7357e6f0abe202fa19 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 22:31:57 -0800 Subject: [PATCH 2/3] Script checker: app.selectTool counts as the document model, not a feature only the reference app has --- crates/scriptcheck/src/catalog.rs | 2 +- crates/scriptcheck/src/tests.rs | 2 +- docs/mcp.md | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/scriptcheck/src/catalog.rs b/crates/scriptcheck/src/catalog.rs index 0045c764f2..c1203504ca 100644 --- a/crates/scriptcheck/src/catalog.rs +++ b/crates/scriptcheck/src/catalog.rs @@ -181,7 +181,7 @@ features! { ScriptuiDrawing "scriptui.drawing" Dialogs, ScriptuiPalette "scriptui.palette" HostOnly, ScriptuiWindow "scriptui.window" Dialogs, - SelectTool "selectTool" HostOnly, + SelectTool "selectTool" Dom, Socket "socket" HostOnly, UnitValue "unitValue" Language, Xml "xml" HostOnly, diff --git a/crates/scriptcheck/src/tests.rs b/crates/scriptcheck/src/tests.rs index 6985791fe1..2d57f40f94 100644 --- a/crates/scriptcheck/src/tests.rs +++ b/crates/scriptcheck/src/tests.rs @@ -1521,7 +1521,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() { fn application_methods_are_features_not_members() { let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n"); assert!(r.members.is_empty(), "{:?}", r.members); - assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]); + assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 350d017c4f..6902e16314 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2563,9 +2563,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, `app.selectTool` included), `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 and actions). - `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines, and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and `locale`. A directive is read where it starts a line, written `#name` or `//@name`. From 7f7effc8fbd8695a9ba30e649a14b7fc687ffe1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:59:51 -0800 Subject: [PATCH 3/3] Scripts: New Document profiles are read without following a link, and review fixes - A New Document profile is opened without following a link (O_NOFOLLOW on Unix, FILE_FLAG_OPEN_REPARSE_POINT on Windows), and its kind and bytes are read from that open file. A link put in the profile's place after the plain-file check is refused instead of read. - Page item and layer handles go stale when their document is reverted. - controlBounds holds the control points of the object's paths. - PageItems.toString() throws Stale document for a collection kept from an earlier run. - Assigning an object the opacity it reports runs no command, except on a graph mark or label whose graph keeps another opacity. - An object-model edit and the steps that restore the selection, layer and active document succeed or fail together. - hasOwnProperty and propertyIsEnumerable stop at an unavailable member that hides one of a parent class. - Assigning a name that a non-extensible host object inherits no longer looks the name up with the object's indexer. - The Application prototype inventory lists selectTool. - docs/mcp.md names the Stale document error, and the parity line says the tool changes only when the run ends without an error. --- crates/engine/Cargo.toml | 7 +- crates/engine/src/cmd/newdoc.rs | 6 +- crates/engine/src/script/dom.rs | 80 +++++++++++++++---- crates/engine/src/store.rs | 46 +++++++++++ crates/engine/src/tests/script_dom.rs | 77 ++++++++++++++++-- crates/engine/src/tests/store.rs | 18 +++++ .../tests/it/script_host_vs_scriptcheck.rs | 2 +- crates/js/src/host_classes.rs | 14 +++- crates/js/src/host_tests.rs | 19 +++++ crates/js/src/interp.rs | 13 +-- docs/mcp.md | 7 +- docs/target-app-parity.md | 2 +- 12 files changed, 252 insertions(+), 39 deletions(-) diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 7e6028b045..bb8277a9ab 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -70,10 +70,11 @@ serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } -# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in -# Cargo.lock (tempfile, ui-egui), so this adds no new crate. +# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a +# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile, +# ui-egui), so this adds no new crate. [target.'cfg(unix)'.dependencies] -rustix = { workspace = true, features = ["std", "process"] } +rustix = { workspace = true, features = ["std", "process", "fs"] } # Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), # and whether two paths a script names are one file (`script::files`). Already in Cargo.lock diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 8272f7d8cb..47dd425555 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -1017,11 +1017,13 @@ impl Session { match std::fs::symlink_metadata(&path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), // A link is refused: the script's gate does not check where it leads. - Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()), + Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()), _ => {} } crate::file_access::check_read(&file).map_err(denied)?; - crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) + // Read without following a link, so a link put in the file's place since the check + // above is refused too. + crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some) })?; let Some(bytes) = read else { return Ok(None) }; // The color profiles the file carries are installed where missing, as opening it installs diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 1f4d8de478..ca7bc3ba77 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -367,6 +367,14 @@ fn find_doc(h: &Host, run: f64, uid: f64) -> Option { s.documents().iter().position(|d| d.uid == uid).map(|index| Doc { index, uid }) } +/// [`find_doc`] for the handle of an object in a document: none as well when the document was +/// reverted since the handle was made, as its objects were read again from its file. +fn find_doc_of_object(h: &Host, run: f64, uid: f64, reverts: f64) -> Option { + let doc = find_doc(h, run, uid)?; + let s = h.session.borrow(); + (whole(reverts) == Some(s.documents()[doc.index].reverts)).then_some(doc) +} + /// The document `d` names: a `Document` or a `PageItems` object. fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result { let Some(handle) = handle_of(d, class) else { return Err(HostError::Type(format!("this is not a {class}"))) }; @@ -379,8 +387,8 @@ fn doc_of(h: &Host, d: &Data, class: &str) -> std::result::Result std::result::Result { let Some(handle) = handle_of(d, "PageItem") else { return Err(HostError::Type("this is not a page item".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a page item".into())) }; + let doc = find_doc_of_object(h, *run, *uid, *reverts).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let s = h.session.borrow(); let st = &s.documents()[doc.index]; @@ -418,8 +426,8 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { - Some(t) => host_ref(t, &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), - None => host_ref("Layer", &[float(h.run), float(st.uid), id_parts(id)[0], id_parts(id)[1]]), + Some(t) => host_ref(t, &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), + None => host_ref("Layer", &[float(h.run), float(st.uid), float(st.reverts), id_parts(id)[0], id_parts(id)[1]]), }, None => Data::Null, } @@ -653,12 +661,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> /// commands changed it (commands given ids select them first), direct-selected anchors, segments, /// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic /// symbol instance or an Objects on Path group included, less the objects that are now deleted, -/// hidden or locked. +/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together +/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s +/// changes are undone as well. fn on_doc( h: &Host, uid: u64, keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, +) -> std::result::Result { + atomically(h, |h| on_doc_steps(h, uid, keep_selection, f)) +} + +/// The steps of [`on_doc`]. +fn on_doc_steps( + h: &Host, + uid: u64, + keep_selection: bool, + f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { let (index, active, before, layer) = { let s = h.session.borrow(); @@ -1452,6 +1472,11 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer { Ok(text("PageItems")) } +fn items_to_string(h: &Host, a: &[Data]) -> Answer { + items_doc(h, a)?; + Ok(text("[PageItems]")) +} + fn items_parent(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; Ok(doc_ref(h, doc.uid)) @@ -1654,9 +1679,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if !(0.0..=100.0).contains(&v) { return Err(HostError::Range("opacity must be from 0 to 100".into())); } - // A value the getter reports for the item's opacity sends the opacity it has, and - // `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still - // replaces the one the graph keeps for its series or kind. + // A value the getter reports for the item's opacity runs no command, unless the item is a graph + // mark or label whose graph keeps another opacity for its series or kind: then the opacity the + // item has is sent, and replaces the one the graph keeps. // The opacity the item already has may be assigned while its layer is hidden or locked, unless // it would still replace the opacity a graph keeps for the item's series or kind. let item = this_item(h, a)?; @@ -1671,7 +1696,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer { if now.is_none() || keeps_other { refuse_in_closed_layer(h, item)?; } - set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)})) + set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -1717,6 +1742,31 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds, grown to hold the control points of the item's 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 control = st.doc.node(item.id).and_then(control_points_box); + Ok::<_, HostError>((vectorcraft_geom::union_opt(st.doc.bounds_of(&[item.id], true), control), frame(st)?)) + })?; + 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)])), + } +} + +/// The box of the control points of the paths in `n`, the visible members of its groups and +/// compound paths included; none for other art. +fn control_points_box(n: &crate::doc::Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { .. } | NodeKind::Compound { .. } => { + n.children()?.iter().filter(|c| c.visible).fold(None, |acc, c| vectorcraft_geom::union_opt(acc, control_points_box(c))) + } + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; match item_rect(h, item, false)? { @@ -1895,13 +1945,13 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data) -> std::result:: let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); let handle = handle_of(target, "PageItem").or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { + let Some(&[run, uid, reverts, high, low]) = handle.as_deref() else { if handle_of(target, "Document").is_some() { return Err(HostError::Error("a document as the relative object is not available yet".into())); } return Err(HostError::Type("the relative object must be a page item or a layer".into())); }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + let doc = find_doc_of_object(h, run, uid, reverts).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } @@ -2069,8 +2119,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer { fn layer_name(h: &Host, a: &[Data]) -> Answer { let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) }; - let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; - let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let [run, uid, reverts, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) }; + let doc = find_doc_of_object(h, *run, *uid, *reverts).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; let id = id_of(*high, *low).unwrap_or(NodeId(u64::MAX)); with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into()))) } @@ -2223,7 +2273,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("index", method(l, items_index)), ("getByName", method(l, items_by_name)), ("removeAll", method(l, items_remove_all)), - ("toString", class_text("PageItems")), + ("toString", method(l, items_to_string)), ]), Some(function(l, items_at)), )); @@ -2243,7 +2293,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/store.rs b/crates/engine/src/store.rs index 7afab7426d..703597dc45 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -187,6 +187,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result> { Ok(bytes) } +/// What [`read_capped_plain`] tells a path that is not a plain file. +pub(crate) const NOT_PLAIN: &str = "not a plain file"; + +/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without +/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and +/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check +/// is refused with [`NOT_PLAIN`] rather than read. +pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result, String> { + let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) { + Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(), + _ => e.to_string(), + })?; + let m = file.metadata().map_err(|e| e.to_string())?; + if !m.file_type().is_file() || reparse_point(&m) { + return Err(NOT_PLAIN.to_string()); + } + let mut bytes = vec![]; + file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?; + if bytes.len() as u64 > max { + return Err(too_large(max)); + } + Ok(bytes) +} + +/// `path` opened for reading, without following a link there. A pipe put in its place does not hold +/// the open up. +#[cfg(unix)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::unix::fs::OpenOptionsExt; + let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK; + std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path) +} + +/// `path` opened for reading; a link or junction there is opened itself, not its target. +#[cfg(windows)] +fn open_no_link(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000; + std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path) +} + +#[cfg(not(any(unix, windows)))] +fn open_no_link(path: &Path) -> std::io::Result { + std::fs::File::open(path) +} + /// What a file over its cap is told (a detail after the file's name, in the log or an error). fn too_large(max: u64) -> String { format!("larger than {max} bytes") diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 4deef14b04..516992c07e 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was"); } +/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the +/// visible bounds. +#[test] +fn control_bounds_hold_the_handles_of_a_curve() { + let (mut s, _, _) = doc(); + s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, c = p[0], r = p[1];\ + function h(b) { return b[1] - b[3]; }\ + vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\ + vc.log(String(r.controlBounds) === String(r.visibleBounds));", + ); + let heights = out[0].as_array().unwrap(); + let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap()); + // The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve. + assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}"); + assert_eq!(heights[2], json!(true), "{out:?}"); + assert_eq!(out[1], json!(true), "{out:?}"); +} + #[test] fn convert_coordinate_pair_is_inverse_and_y_up() { let mut s = Session::new(); @@ -270,6 +291,7 @@ fn assigning_the_reported_opacity_changes_nothing() { assert_eq!(out, vec![json!(33.3333)]); assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); assert_eq!(undo_steps(&s), steps); + assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command"); // A value close to the reported one but not equal to it is still applied. s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap(); let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); @@ -285,6 +307,14 @@ fn selection_assignment_is_atomic_across_invalid_items() { let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];"); assert!(e.contains("Cannot select PathItem"), "{e}"); assert!(s.active().unwrap().selection.objects.is_empty()); + // With the valid item first and the error caught, the run sees the selection unchanged. + let out = log( + &mut s, + "var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\ + catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);", + ); + assert_eq!(out, vec![json!(true), json!(0)]); + assert!(s.active().unwrap().selection.objects.is_empty()); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); let out = log( &mut s, @@ -680,9 +710,13 @@ fn a_listed_preset_keeps_more_rows_than_artboards() { fn stale_documents_throw_on_every_member() { let (mut s, _, _) = doc(); run(&mut s, "#targetengine keep\nvar d = app.activeDocument, p = d.pageItems, l = p[0].parent;").unwrap(); - for (member, message) in - [("d.typename", "Stale document"), ("d.parent", "Stale document"), ("p.typename", "Stale document"), ("l.typename", "Stale")] - { + for (member, message) in [ + ("d.typename", "Stale document"), + ("d.parent", "Stale document"), + ("p.typename", "Stale document"), + ("p.toString()", "Stale document"), + ("l.typename", "Stale"), + ] { let e = failure(&mut s, &format!("#targetengine keep\n{member};")); assert!(e.contains(message), "{member}: {e}"); } @@ -1192,6 +1226,27 @@ fn wrappers_go_stale_after_delete_and_undo() { assert!(e.contains("Stale page item"), "{e}"); } +/// Reverting a document reads its objects again from its file, so the page items and layers taken +/// before the revert are stale, even where the file has an object under the same id. +#[test] +fn page_items_and_layers_go_stale_when_their_document_is_reverted() { + let (mut s, _, _) = doc(); + let path = std::env::temp_dir().join(format!("vc-dom-revert-{}.{}", std::process::id(), vectorcraft_format::EXTENSION)); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + for (taken, read, message) in [("p[0]", "i.name", "Stale page item"), ("p[0].parent", "i.typename", "Stale")] { + let source = format!("var p = app.activeDocument.pageItems, i = {taken}; p[1].name = 'x'; vc.run('file.revert', {{}}); {read};"); + let e = failure(&mut s, &source); + assert!(e.contains(message), "{taken}: {e}"); + } + let out = log( + &mut s, + "app.activeDocument.pageItems[1].name = 'x'; vc.run('file.revert', {}); var p = app.activeDocument.pageItems;\ + vc.log([p.length, p[0].typename, p[1].name]);", + ); + assert_eq!(out, vec![json!([2, "PathItem", ""])]); + let _ = std::fs::remove_file(path); +} + #[test] fn remove_all_refuses_locked_art_before_deleting_anything() { let (mut s, a, b) = doc(); @@ -1199,6 +1254,14 @@ fn remove_all_refuses_locked_art_before_deleting_anything() { let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); assert!(e.contains(&b.0.to_string()), "{e}"); assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); + // With the error caught, the run that goes on still has both objects. + let out = log( + &mut s, + "var p = app.activeDocument.pageItems; try { p.removeAll(); vc.log('removed'); }\ + catch (e) { vc.log(String(e).indexOf('cannot delete hidden or locked objects') >= 0); } vc.log(p.length);", + ); + assert_eq!(out, vec![json!(true), json!(2)]); + assert_eq!(s.active().unwrap().doc.layers[0].children().unwrap().len(), 2); s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap(); // A locked object inside an unlocked group stops it too. s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); @@ -1345,8 +1408,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 (saved, other) = (json!(p), json!(format!("{p}.other"))); + let query = format!("vc.log(app.getIsFileOpen({saved})); 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. @@ -1652,6 +1716,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() { vc.log(m);", ); assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]); + // A name the collection inherits is not looked up as an object's name when it is assigned. + let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);"); + assert_eq!(out, vec![json!(1)]); } /// `opacity`, `hidden`, `locked` and the position and size setters on an object in a hidden or diff --git a/crates/engine/src/tests/store.rs b/crates/engine/src/tests/store.rs index 21967473bb..dfc603dc59 100644 --- a/crates/engine/src/tests/store.rs +++ b/crates/engine/src/tests/store.rs @@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() { assert!(holds(&[][..], &[])); } +#[cfg(unix)] +#[test] +fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() { + use crate::store::{NOT_PLAIN, read_capped_plain}; + let root = fresh_dir("plain-read"); + let target = root.join("target.bin"); + std::fs::write(&target, b"outside").unwrap(); + let link = root.join("profile.vectorcraft"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string())); + let folder = root.join("folder"); + std::fs::create_dir(&folder).unwrap(); + assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string())); + assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec())); + assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec())); + assert!(read_capped_plain(&target, 6).is_err()); +} + #[test] fn a_saved_preset_replaces_an_oversized_file_in_its_place() { let root = fresh_dir("oversized-put"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 4368ce29b7..aacf3017d5 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -83,7 +83,7 @@ const INSIDE: &[(&str, &str)] = &[ ( "Application.prototype.", "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection selection= toString typename", + selection selection= selectTool toString typename", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index 206f781ef3..a25e0e531a 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -91,6 +91,9 @@ pub(crate) struct Entry { parent: Option, /// The names of the members `hasOwnProperty` reports: every member but the unavailable ones. own: Rc>, + /// The names of the unavailable members, which hide a member of the same name that a parent + /// class has. + unavailable: Rc>, } impl Entry { @@ -143,7 +146,8 @@ pub fn host_ref_parts(d: &Data) -> Option<(&str, Vec)> { impl Interp { /// Whether `k` is a member that `hasOwnProperty` reports on `id`: `id` is an object of a host - /// class, and `k` names an available member of that class or of a class it descends from. + /// class, and `k` names an available member of the nearest class that declares `k`, that class + /// or one it descends from. pub(crate) fn is_host_member(&self, id: ObjId, k: &[u16]) -> JsResult { let Class::Host(h) = &self.object(id)?.class else { return Ok(false) }; let mut class = Some(h.class); @@ -152,6 +156,9 @@ impl Interp { if e.own.contains(k) { return Ok(true); } + if e.unavailable.contains(k) { + return Ok(false); + } class = e.parent; } Ok(false) @@ -307,7 +314,7 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { let r = fill_class(i, proto, &class); i.temp_roots.truncate(mark); let ctor = r?; - let members = class.members.iter().filter(|(_, m)| !matches!(m, HostMember::Unavailable(_))).map(|(name, _)| key(name)).collect(); + let (unavailable, members): (Vec<_>, Vec<_>) = class.members.iter().partition(|(_, m)| matches!(m, HostMember::Unavailable(_))); i.host_classes.push(Entry { name: class.name.as_str().into(), proto, @@ -315,7 +322,8 @@ fn install_class(i: &mut Interp, class: HostClass) -> JsResult<()> { index: class.index, family, parent: parent_class, - own: Rc::new(members), + own: Rc::new(members.into_iter().map(|(name, _)| key(name)).collect()), + unavailable: Rc::new(unavailable.into_iter().map(|(name, _)| key(name)).collect()), }); let global = i.global; i.define(global, key(&class.name), Prop::Data { value: Value::Object(ctor), flags: crate::heap::HIDDEN }) diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index ba0e005ce0..ce695b7e06 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -717,6 +717,25 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() { ); } +#[test] +fn an_unavailable_member_hides_the_member_its_parent_class_has() { + let mut r = realm(1_000_000); + let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0))); + let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into()))); + let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass { + name: name.into(), + parent: parent.map(Into::into), + members: vec![("size".to_string(), member)], + index: None, + construct: None, + }; + let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))]; + let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))]; + r.define_host_classes(classes, objects).unwrap(); + r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap(); + assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into())); +} + #[test] fn a_converted_function_reads_each_argument_as_its_list_says() { let mut r = realm(1_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index f7cb2896a2..f10f0e9566 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -1859,16 +1859,17 @@ impl Interp { None => {} } let proto = self.object(id)?.proto; - match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { + let inherited = match proto.map(|p| self.find_property(p, &k)).transpose()?.flatten() { Some(Prop::Accessor { set: Some(s), .. }) => return self.call(&Value::Object(s), &Value::Object(id), &[v]).map(drop), Some(Prop::Accessor { set: None, .. }) => return self.reject(throw, &k, "it has only a getter"), Some(Prop::Data { flags, .. }) if flags & WRITABLE == 0 => return self.reject(throw, &k, "it is read-only"), - _ => {} - } + found => found.is_some(), + }; if !self.object(id)?.extensible { - // A name that an object of a host class with an indexer lacks is read with the indexer - // first, so assigning it throws what reading it throws. - if array_index(&k).is_none() + // A name that an object of a host class with an indexer lacks, on it and its prototypes, + // is read with the indexer first, so assigning it throws what reading it throws. + if !inherited + && array_index(&k).is_none() && let Some(f) = self.host_indexer(id)? { self.host_index(&f, id, Self::indexer_key(&k), false)?; diff --git a/docs/mcp.md b/docs/mcp.md index 6902e16314..e221d601d1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2709,7 +2709,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 hold the control points of the object's paths), `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 @@ -2761,8 +2761,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot for kinds the help pages give no class. Each change runs a command and joins the run's one undo step for each changed document. A value that changes nothing runs no command, and a change to another document leaves the active tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers - panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was - deleted, or that a named engine kept from an earlier run, throws `Stale page item`. `remove()` on an object that + panel rows as they were before the change. A bad value throws an error and changes nothing. A page item that was + deleted, or that a named engine kept from an earlier run, throws `Stale page item`, and a document or a page item + collection that a named engine kept from an earlier run throws `Stale document`. `remove()` on an object that is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()` when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7d6ec78683..db38ae94f7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1033,7 +1033,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - 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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.selectTool(name)` makes the named tool the current tool when the run ends (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). Layers, paths, type and the other classes are not there yet. `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`.