Scripts: image removeAll keeps art on a locked artboard; setters check the item first

placedItems.removeAll() and rasterItems.removeAll() checked only whether
each image and its layers and groups were shown and unlocked, then passed
the ids to edit.clear, which deletes named objects without checking
artboard locks. Both now throw "cannot delete objects on a locked
artboard" with the image ids and delete nothing, as pageItems.removeAll()
does.

Assigning matrix read the value before the item, so a stale image or an
add() result without a file threw the matrix error. Assigning file to an
add() result that was placed and then embedded threw "PlacedItem.file is
read-only: use relink". Both now check the item first and throw "Stale
page item" or "PlacedItem.file is required".

A File that a host class member returns now charges its new path string
to the script heap, in the same reservation as the File object.

docs/gaps.md G6 and the M13 row in docs/roadmap.md list the placed and
raster image classes; docs/mcp.md states the removeAll and setter rules.
This commit is contained in:
dotCooCoo committed 2026-11-21 21:04:47 -08:00
1 parent edd8afaca7
commit f0a1e6398f
7 files changed
+110 -12

No files matched your search

+15 -6
View File
@@ -40,8 +40,9 @@ use vectorcraft_geom::{Affine, Point};
use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts};
use super::{
Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, editable, find_doc,
float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, with_doc,
Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item,
editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole,
with_doc,
};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -218,19 +219,26 @@ fn list_index(h: &Host, a: &[Data], placed: bool) -> Answer {
}
/// `removeAll()`: deletes every image of the collection in one command. A hidden or locked one, or
/// one in a hidden or locked layer or group, stops it before anything is deleted.
/// one in a hidden or locked layer or group, stops it before anything is deleted, and so does one on
/// a locked artboard.
fn list_remove_all(h: &Host, a: &[Data], placed: bool) -> Answer {
let doc = list_doc(h, a, placed)?;
let (ids, refused) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let ids = images(h, st, placed)?;
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused))
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("cannot delete hidden or locked objects: {list}")));
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -374,6 +382,7 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer {
};
let k = slot_of(h, run, uid, slot)?;
if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_some()) {
this_of(h, a, "PlacedItem")?;
return Err(HostError::Error(FILE_READ_ONLY.into()));
}
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
@@ -469,8 +478,8 @@ fn area_of(m: Affine) -> bool {
/// A matrix with no area, one that puts a corner of the image outside the canvas, or a distorted
/// image is refused before anything changes; the matrix the image has already changes nothing.
fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
let m = matrix_value(arg(a, 1))?;
let item = this_of(h, a, cls)?;
let m = matrix_value(arg(a, 1))?;
let delta = with_doc(h, item.doc, |_, st| {
let Some((n, im)) = st.doc.node(item.id).and_then(|n| if let NodeKind::Image(im) = &n.kind { Some((n, im)) } else { None }) else {
return Err(HostError::Error(STALE_ITEM.into()));
@@ -425,6 +425,62 @@ fn image_file_getter_hides_a_link_to_an_open_document_out_of_scope() {
let _ = std::fs::remove_dir_all(base);
}
/// Assigning `file` or `matrix` checks the item before the value: an `add()` result with no file
/// throws `PlacedItem.file is required`, and one that was embedded throws `Stale page item`.
#[test]
fn assignments_check_the_item_before_the_value() {
let base = folder("receiver");
let a = base.join("main/a.png");
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
let out = log(
&mut s,
&base,
&format!(
"var d = app.activeDocument, n = d.placedItems.add(), p = d.placedItems.add(), m = [];\
try {{ n.matrix = null; }} catch (e) {{ m.push(e.message); }}\
p.file = new File('{0}'); p.embed();\
try {{ p.file = new File('{0}'); }} catch (e) {{ m.push(e.message); }}\
try {{ p.matrix = null; }} catch (e) {{ m.push(e.message); }}\
try {{ d.rasterItems[0].matrix = null; }} catch (e) {{ m.push(e.name); }}\
vc.log(m);",
js_path(&a)
),
);
assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "Stale page item", "TypeError"])]);
let _ = std::fs::remove_dir_all(base);
}
/// `removeAll()` deletes no image when one is on a locked artboard, in both collections.
#[test]
fn remove_all_keeps_images_on_a_locked_artboard() {
let base = folder("locked-board");
let a = base.join("main/a.png");
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
let linked = place(&mut s, &a, true);
let embedded = place(&mut s, &a, false);
let lock = |s: &mut Session, locked: bool| {
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = locked;
Ok(())
})
.unwrap();
};
lock(&mut s, true);
let steps = undo_steps(&s);
let e = failure(&mut s, &base, "app.activeDocument.placedItems.removeAll();");
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", linked.0)), "{e}");
let e = failure(&mut s, &base, "app.activeDocument.rasterItems.removeAll();");
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", embedded.0)), "{e}");
assert_eq!(images(&s).len(), 2);
assert_eq!(undo_steps(&s), steps);
lock(&mut s, false);
let out = log(&mut s, &base, "var d = app.activeDocument; d.placedItems.removeAll(); d.rasterItems.removeAll(); vc.log(d.pageItems.length);");
assert_eq!(out, vec![json!(0)]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn stale_and_foreign_placed_items_are_refused() {
let base = folder("stale");
+14 -3
View File
@@ -195,10 +195,20 @@ fn parsed(i: &mut Interp, this: &Value, what: &str, name: &str) -> JsResult<Valu
/// A new object with prototype `proto` for the path `fs`, already in the platform's form.
fn instance(i: &mut Interp, proto: ObjId, fs: Value) -> JsResult<Value> {
new_instance(i, proto, fs, false)
}
/// [`instance`], which also charges the heap for the string of `fs` when `charge_path` is set, for
/// a path string made for the new object alone.
fn new_instance(i: &mut Interp, proto: ObjId, fs: Value, charge_path: bool) -> JsResult<Value> {
let Value::String(path) = fs.clone() else { return Err(i.type_error("File: the host gave no path")) };
let line_feed = host_value(i, "lineFeed")?;
i.rooted(&[fs, line_feed.clone()], |i| {
i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + string_bytes(path.len()))?;
let path_bytes = string_bytes(path.len());
i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES + path_bytes)?;
if charge_path {
i.heap.bytes = i.heap.bytes.saturating_add(path_bytes);
}
let o = i.heap.alloc_object(Object::new(Class::FsEntry(path.clone()), Some(proto)));
i.rooted(&[Value::Object(o)], |i| {
set_slot(i, o, ERROR, Value::str(""))?;
@@ -1153,10 +1163,11 @@ pub fn file_ref(path: &str) -> crate::Data {
}
impl Interp {
/// A new `File` for `path`, which a member of a host class gave ([`file_ref`]).
/// A new `File` for `path`, which a member of a host class gave ([`file_ref`]). The new string
/// of the path is charged to the heap, as [`crate::Data::String`] is when it is written.
pub(crate) fn write_file_ref(&mut self, path: &str) -> JsResult<Value> {
let proto = classes(self)?.file_proto;
instance(self, proto, Value::str(path))
new_instance(self, proto, Value::str(path), true)
}
}
+18
View File
@@ -685,6 +685,24 @@ fn a_read_of_a_class_on_another_branch_gives_a_new_object() {
assert_eq!(r.run(script).unwrap(), JsValue::String("true,true,true,false,true,true,true,true,true".into()));
}
/// The path of a `File` a member of a host class gives is charged to the heap.
#[test]
fn the_path_of_a_file_a_host_class_gives_is_charged_to_the_heap() {
let bytes_after = |len: usize| {
let mut r = realm(1_000_000);
let current: HostFunction = Rc::new(|_| Ok(Data::String("d".into())));
r.define_file_classes(vec![("current".into(), HostItem::Function(current))]).unwrap();
let file: HostFunction = Rc::new(move |_| Ok(file_ref(&"p".repeat(len))));
let members = vec![("file".to_string(), HostMember::Method(file))];
let maker = HostClass { name: "Maker".into(), parent: None, members, index: None, construct: None };
r.define_host_classes(vec![maker], vec![("maker".into(), host_ref("Maker", &[]))]).unwrap();
assert_eq!(r.run("var f = maker.file(); f instanceof File"), Ok(JsValue::Bool(true)));
r.interp().heap.bytes
};
let (short, long) = (bytes_after(1), bytes_after(100_000));
assert!(long >= short + 2 * 99_999, "{short} {long}");
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_wait() {
let mut r = realm(1_000_000);
+2 -1
View File
@@ -809,7 +809,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the
other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new
documents, each document's selection and its page items. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and
`rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
runs a script in a named engine whose globals last between runs,
File › Scripts lists the scripts of the Scripts folder, and
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
+4 -1
View File
@@ -2751,7 +2751,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot
that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning
`matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of
the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
a pixel. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the
a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete
objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the
item before the value, so a stale item throws `Stale page item` and an `add()` result without a file throws
`PlacedItem.file is required` whatever the value. A run keeps at most 1,024 `placedItems.add()` results, and one that was not given a file is dropped at the
end of the run. `contentVariable`, `trace`, `colorants`, `colorize` and `overprint` are not available yet.
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
+1 -1
View File
@@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`PlacedItem` and `RasterItem`); the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 |
| M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |