From ba0441c458a6496b9152924ce895475cfc5e0ae5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:33:43 -0800 Subject: [PATCH 1/5] Scripts: addDocument takes only a DocumentPreset and throws when its profile cannot be read - new DocumentPreset() now makes an object of the DocumentPreset class whose settings the run keeps, so addDocument refuses a plain object, one with a typename of DocumentPreset included, with a TypeError naming presetSettings. - When file.new reports a profileError, addDocument throws an error that names the profile and the reason, and the document made with the defaults is put back. - A script's file.new reads the New Document profile file in the app's own profiles folder; the automation roots in force still apply. Before, the script's file gate refused the folder, so a scripted addDocument never used an edited profile. Docs: docs/mcp.md. --- crates/engine/src/cmd/newdoc.rs | 17 ++- crates/engine/src/file_access.rs | 9 +- crates/engine/src/script/dom.rs | 113 +++++++++++++++--- crates/engine/src/tests/script_dom.rs | 60 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 15 ++- docs/mcp.md | 10 +- 6 files changed, 197 insertions(+), 27 deletions(-) diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 983ef4041d..fb26b13c68 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -984,13 +984,18 @@ impl Session { let file = path.to_string_lossy().to_string(); // Checked before the file is looked for, so a request that may not read the folder learns // nothing of its files, nor where the folder is. + // A script's gate does not apply to reads of the app's own folder; the automation roots in + // force still do. let denied = |_| PROFILE_DENIED.to_string(); - crate::file_access::check_read(&file).map_err(denied)?; - if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { - return Ok(None); - } - crate::file_access::check_read(&file).map_err(denied)?; - let bytes = crate::store::read_capped(&path, MAX_PROFILE_BYTES)?; + let read = crate::file_access::app_folder_read(|| { + crate::file_access::check_read(&file).map_err(denied)?; + if std::fs::symlink_metadata(&path).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound) { + return Ok(None); + } + crate::file_access::check_read(&file).map_err(denied)?; + crate::store::read_capped(&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 // them, so the new document's assigned profiles draw and are saved with it. let (mut doc, _, warnings) = super::fileio::native_file(&bytes).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index c5ecee374e..7c246c6a64 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -206,9 +206,16 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) } +/// Run `f`, a read of a file in one of the app's own folders, with reads exempt from the gate of +/// the script command this thread runs. Unlike [`unconfined`], the roots in force still apply. +pub(crate) fn app_folder_read(f: impl FnOnce() -> T) -> T { + with_gate_reads_exempt(true, f) +} + thread_local! { /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an - /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + /// [`unconfined`] or an [`app_folder_read`] entered after the gate was put in force + /// ([`with_script_gate`]). static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; } diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..f8caab9adb 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -85,13 +85,14 @@ const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM"; const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM"; /// What the object model keeps for one run: its coordinate system, the last list of a document's -/// page items, kept while that document is unchanged, and whether a call's own savepoint -/// ([`atomically`]) is open. +/// page items, kept while that document is unchanged, whether a call's own savepoint +/// ([`atomically`]) is open, and the settings of each `DocumentPreset` the run made. #[derive(Default)] pub(super) struct State { coords: Cell, items: RefCell>, saving: Cell, + presets: RefCell>>, } impl State { @@ -873,10 +874,13 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { return Err(HostError::Range("the startup preset's name is too long".into())); } let (profile, mode) = startup_preset(name).ok_or_else(|| HostError::Error(format!("no startup preset called {name}")))?; + // Only an object `new DocumentPreset()` made: a plain object such as `{width: 500}` is refused. let settings = match given(arg(a, 2)) { None | Some(Data::Null) => Vec::new(), - Some(Data::Object(o)) => o.clone(), - Some(_) => return Err(HostError::Type("presetSettings must be a DocumentPreset".into())), + Some(d) => { + let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + h.dom.presets.borrow()[i].clone() + } }; let field = |k: &str| settings.iter().find(|(n, _)| n == k).map(|(_, v)| v).and_then(given); for k in ["documentBleedLink", "documentBleedOffsetRect", "transparencyGrid"] { @@ -913,23 +917,101 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { if let Some(m) = mode { p.entry("colorMode").or_insert_with(|| json!(m)); } - new_document(h, p) + // A profile whose file could not be read throws, and the document `file.new` made with the + // defaults is put back, with the Recent sizes as they were. + atomically(h, |h| { + let (_, value) = command_value(h, "file.new", &Value::Object(p))?; + if let Some(e) = value.get("profileError") { + let profile = e["profile"].as_str().unwrap_or_default(); + let reason = e["reason"].as_str().unwrap_or_default(); + return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); + } + let s = h.session.borrow(); + let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; + Ok(doc_ref(h, st.uid)) + }) } /// `new DocumentPreset()`: a record of new-document settings with the defaults the help page /// gives; the other settings are -/// left out. -fn new_preset(_: &[Data]) -> Answer { +/// left out. The settings stay with the run, which hands the script an object of the +/// `DocumentPreset` class. +fn new_preset(h: &Host) -> Answer { + let mut presets = h.dom.presets.borrow_mut(); + if presets.len() >= MAX_PRESETS { + return Err(HostError::Range(format!("a script can make at most {MAX_PRESETS} DocumentPresets"))); + } let item = |k: &str, v: Data| (k.to_string(), v); - Ok(Data::Object(vec![ - item("typename", text("DocumentPreset")), + presets.push(vec![ item("artboardLayout", text("DocumentArtboardLayout.GridByRow")), item("artboardRowsOrCols", num(1.0)), item("artboardSpacing", num(20.0)), item("height", num(792.0)), item("numArtboards", num(1.0)), item("width", num(612.0)), - ])) + ]); + Ok(host_ref("DocumentPreset", &[float(h.run), float(presets.len() as u64 - 1)])) +} + +/// The most `DocumentPreset` objects one run can make. +const MAX_PRESETS: usize = 10_000; + +/// The settings a `DocumentPreset` has, each a property a script reads and assigns. +const PRESET_FIELDS: &[&str] = &[ + "artboardLayout", + "artboardRowsOrCols", + "artboardSpacing", + "colorMode", + "documentBleedLink", + "documentBleedOffsetRect", + "height", + "numArtboards", + "previewMode", + "rasterResolution", + "title", + "transparencyGrid", + "units", + "width", +]; + +/// The index in the run's presets of the `DocumentPreset` `d` is, when it is one this run made. +fn preset_of(h: &Host, d: &Data) -> Option { + let handle = handle_of(d, "DocumentPreset")?; + let [run, i] = handle.as_slice() else { return None }; + if whole(*run) != Some(h.run) { + return None; + } + let i = usize::try_from(whole(*i)?).ok()?; + (i < h.dom.presets.borrow().len()).then_some(i) +} + +/// The getter and setter of the `DocumentPreset` setting `key`: an unset one reads `undefined`, and +/// a value is checked when `addDocument` uses it. +fn preset_field(link: &Link, key: &'static str) -> HostMember { + let not_preset = || HostError::Type("this is not a DocumentPreset".into()); + let l = link.clone(); + let get: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let presets = h.dom.presets.borrow(); + Ok(presets[i].iter().find(|(k, _)| k == key).map_or(Data::Undefined, |(_, v)| v.clone())) + }); + let l = link.clone(); + let set: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + let value = arg(&a, 1).clone(); + h.charge_call(16 + data_size(&value))?; + let i = preset_of(&h, arg(&a, 0)).ok_or_else(not_preset)?; + let mut presets = h.dom.presets.borrow_mut(); + let fields = &mut presets[i]; + match fields.iter_mut().find(|(k, _)| k == key) { + Some((_, v)) => *v = value, + None => fields.push((key.to_string(), value)), + } + Ok(Data::Undefined) + }); + HostMember::Property { get, set } } // ---- Document ---- @@ -1723,11 +1805,14 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), application.push(later(l, "Application", "beep")); let preset = { let l = link.clone(); - let f: HostFunction = Rc::new(move |a: Vec| { - current(&l)?.charge_call(64)?; - new_preset(&a) + let f: HostFunction = Rc::new(move |_: Vec| { + let h = current(&l)?; + h.charge_call(64)?; + new_preset(&h) }); - HostClass { name: "DocumentPreset".into(), parent: None, members: Vec::new(), index: None, construct: Some(f) } + let mut members = vec![("typename".to_string(), typename_of("DocumentPreset"))]; + members.extend(PRESET_FIELDS.iter().map(|k| (k.to_string(), preset_field(link, k)))); + HostClass { name: "DocumentPreset".into(), parent: None, members, index: None, construct: Some(f) } }; let mut classes = vec![ class("Application", None, application, None), diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 795161ac1c..a0e63a5d06 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,66 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn add_document_takes_only_a_document_preset() { + let mut s = Session::new(); + for source in [ + "app.documents.addDocument('Print', {width: 500});", + "app.documents.addDocument('Print', {});", + "app.documents.addDocument('Print', {typename: 'DocumentPreset', width: 500});", + "var p = new DocumentPreset(); var q = {}; for (var k in p) q[k] = p[k]; app.documents.addDocument('Print', q);", + "app.documents.addDocument('Print', [612, 792]);", + "app.documents.addDocument('Print', 'DocumentPreset');", + ] { + let e = failure(&mut s, source); + assert!(e.contains("TypeError") && e.contains("presetSettings must be a DocumentPreset"), "{source}: {e}"); + } + assert!(s.documents().is_empty(), "a refused preset makes no document"); + let out = log(&mut s, "var p = new DocumentPreset(); p.width = 500; vc.log(app.documents.addDocument('Print', p).width);"); + assert_eq!(out, vec![json!(500)]); +} + +#[test] +fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-profile-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + // A profile with no file gives the defaults. + let out = log(&mut s, "vc.log(app.documents.addDocument('Web').typename);"); + assert_eq!(out, vec![json!("Document")]); + assert_eq!(s.doc().unwrap().links_from, None); + // A script reads the profile's file in the app's own folder. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let file = dir.join("Print.vectorcraft").to_string_lossy().to_string(); + log(&mut s, "app.documents.addDocument('Print');"); + assert_eq!(s.doc().unwrap().links_from.as_deref(), Some(file.as_str())); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap(); + // file.new itself makes the document with the defaults and reports the profile it could not read. + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["profile"], "Print", "{r}"); + s.execute("file.close", &json!({})).unwrap(); + let recent = s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(); + let e = failure(&mut s, "app.documents.addDocument('Print');"); + assert!(e.contains("Error: the New Document profile Print could not be read"), "{e}"); + assert!(s.documents().is_empty(), "the document made with the defaults is put back"); + // A script that catches the error finds nothing changed. + let out = log( + &mut s, + "var p = new DocumentPreset(); p.width = 333;\ + try { app.documents.addDocument('Print', p); } catch (e) { vc.log(e.name); } vc.log(app.documents.length);", + ); + assert_eq!(out, vec![json!("Error"), json!(0)]); + assert_eq!(s.execute("file.newPresets", &json!({"category": "Recent"})).unwrap(), recent, "the Recent sizes are as they were"); + // A startup preset with no profile reads no file. + let out = log(&mut s, "vc.log(app.documents.addDocument('Basic RGB').documentColorSpace);"); + assert_eq!(out, vec![json!("DocumentColorSpace.RGB")]); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..d9b6b87103 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -73,7 +73,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ( "", - "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPresetType \ + "app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \ DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid Documents ElementPlacement Layer PageItem \ PageItems RulerUnits ZOrderMethod", ), @@ -83,6 +83,14 @@ const INSIDE: &[(&str, &str)] = &[ "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ selection typename", ), + ("DocumentPreset.", "prototype"), + ( + "DocumentPreset.prototype.", + "artboardLayout artboardLayout= artboardRowsOrCols artboardRowsOrCols= artboardSpacing artboardSpacing= colorMode \ + colorMode= constructor documentBleedLink documentBleedLink= documentBleedOffsetRect documentBleedOffsetRect= height \ + height= numArtboards numArtboards= previewMode previewMode= rasterResolution rasterResolution= title title= \ + transparencyGrid transparencyGrid= typename units units= width width=", + ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), ("Document.", "prototype"), @@ -123,9 +131,8 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ]; -/// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` -/// and the page item types. -const BARE_CLASSES: &str = "BlendItem CompoundPathItem DocumentPreset EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ +/// The classes the host adds with nothing but a prototype and its constructor: the page item types. +const BARE_CLASSES: &str = "BlendItem CompoundPathItem EnvelopeItem GraphItem GroupItem IntertwineItem MeshItem PathItem \ PlacedDocumentItem PlacedItem RasterItem RepeatItem SymbolItem TextFrame"; /// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..182e0fe1c8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2633,7 +2633,11 @@ app through the global object `vc`, and writes to the Script Console and runs ot (https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset` starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when - the preset it is given holds one of them with a value other than `null`, and makes no document. + the preset it is given holds one of them with a value other than `null`, and makes no document. A + `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a + `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the + profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) @@ -9045,7 +9049,9 @@ The profile is read on every `file.new`, so a replayed journal or a recorded act runs, as `document.open` reads its file when it runs. A file larger than 64 MiB (VectorCraft's own limit) is not read. When the file cannot be read, is too large or is not a native document, or the request's read roots leave out the folder (whether or not the file exists), the document starts with the defaults and -`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar. The +`file.new`'s result carries `profileError: {profile, reason}`; the desktop app shows the reason in the status bar, and +a script's `app.documents.addDocument` throws it. A script's file access limits do not apply to reading the profile's +file. The reason given when the read roots leave out the folder does not name the folder's path. Color profiles the profile's file carries are installed when they are missing, as `document.open` installs them, and each one that can't be used adds a line to `file.new`'s `warnings`. The new document's links find their files through relative paths from the From 5cb64802585f18dcbaeb3c4bea6136d87172b297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:53:28 -0800 Subject: [PATCH 2/5] Scripts: assigning PageItem.selected keeps how the other objects are selected Setting selected to true or false runs select.add or select.toggle for that one object, so the other objects keep their direct-selected anchors and segments and the key object. Before, it replaced the selection with whole objects. --- crates/engine/src/script/dom.rs | 16 +++++++--------- crates/engine/src/tests/script_dom.rs | 18 ++++++++++++++++++ docs/mcp.md | 4 +++- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index f8caab9adb..e70dfbb86a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1378,17 +1378,15 @@ fn item_selected(h: &Host, a: &[Data]) -> Answer { fn item_set_selected(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let on = boolean(arg(a, 1), "selected")?; - let mut ids = with_doc(h, item.doc, |_, st| st.selection.objects.clone()); - if ids.contains(&item.id) == on { + if with_doc(h, item.doc, |_, st| st.selection.objects.contains(&item.id)) == on { return Ok(Data::Undefined); } - if on { - let mut given = selection_ids(h, item.doc, arg(a, 0))?; - ids.append(&mut given); - } else { - ids.retain(|i| *i != item.id); - } - set_selection(h, item.doc, ids) + // Adding or removing the one object keeps how the others are selected (their direct-selected + // anchors and segments, and the key object). + let ids = if on { selection_ids(h, item.doc, arg(a, 0))? } else { vec![item.id] }; + let id = if on { "select.add" } else { "select.toggle" }; + on_doc(h, item.doc.uid, false, |h| command(h, id, &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; + Ok(Data::Undefined) } /// The item's geometric bounds (`visual`: its visible bounds) in document coordinates and the diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index a0e63a5d06..9d933378ea 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -835,6 +835,24 @@ fn headless_add_document_dialog_fails_without_creating() { assert_eq!(s.documents().len(), 1); } +#[test] +fn setting_selected_keeps_how_the_other_objects_are_selected() { + let (mut s, a, b) = doc(); + let c = rect(&mut s, 200.0, 100.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); + let anchors = s.active().unwrap().selection.anchors.get(&a).cloned(); + assert!(anchors.is_some()); + log( + &mut s, + "var p = app.activeDocument.pageItems;\ + for (var i = 0; i < p.length; i++) { if (p[i].left == 200) p[i].selected = true; if (p[i].left == 100) p[i].selected = false; }", + ); + let sel = &s.active().unwrap().selection; + assert_eq!(sel.objects, vec![a, c]); + assert_eq!(sel.anchors.get(&a).cloned(), anchors, "the direct-selected anchors stay"); +} + #[test] fn add_document_takes_only_a_document_preset() { let mut s = Session::new(); diff --git a/docs/mcp.md b/docs/mcp.md index 182e0fe1c8..a826f5b3b8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2644,7 +2644,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each entry `[i]` gives. Each page item (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/) has `typename`, `parent`, `name`, `note` (the - Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected`, `opacity` (0 to + Attributes panel's note, trimmed as `attributes.set` trims it), `hidden`, `locked`, `selected` (assigning it adds + 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`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` From e15e3e083d652d9dd1b9145663d9b7838a07215e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:35:17 -0800 Subject: [PATCH 3/5] New Document: Columns reads float rows and columns as file.new does The dialog read artboardLayout's rows and columns as whole numbers only, so a value stored as a float (4.0 from ui.dialog.set) fell back to the stored columns while file.new made the grid from it. The dialog now reads both as file.new does: a number of 1 or more, rounded and kept to the artboard limit. --- crates/ui-egui/src/dialogs/new_document.rs | 28 +++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index 6b9abbcb2f..d7c20c0137 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -234,18 +234,20 @@ fn unit(d: &Dialog) -> Unit { } /// The artboard layout fields. A grid by column with rows shows the columns those rows give the -/// current number of artboards, as `file.new` lays them out. +/// current number of artboards, as `file.new` lays them out. Rows and columns are read as +/// `file.new` reads them: a number of 1 or more, rounded and kept to [`MAX_ARTBOARDS`]. fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { let l = d.fields.get("artboardLayout"); let get = |k: &str| l.and_then(|l| l.get(k)); + let count = |k: &str| get(k).and_then(Value::as_f64).filter(|c| c.is_finite() && *c >= 1.0).map(|c| c.round().min(MAX_ARTBOARDS as f64) as u64); let lay = get("layout").and_then(Value::as_str).and_then(ArtboardLayout::parse).unwrap_or_default(); - let rows = get("rows").and_then(Value::as_u64).filter(|r| *r > 0 && lay == ArtboardLayout::GridByColumn); + let rows = count("rows").filter(|_| lay == ArtboardLayout::GridByColumn); let columns = match rows { Some(rows) => { let n = d.f64("artboards", 1.0).round().clamp(1.0, MAX_ARTBOARDS as f64) as u64; n.div_ceil(rows.min(n)) } - None => get("columns").and_then(Value::as_u64).unwrap_or(1), + None => count("columns").unwrap_or(1), }; (lay, columns, get("spacing").and_then(Value::as_f64).unwrap_or(20.0), get("rightToLeft").and_then(Value::as_bool).unwrap_or(false)) } @@ -931,6 +933,26 @@ mod tests { assert_eq!(columns(&app), 2); } + /// Rows and columns stored as floats, as `ui.dialog.set` stores them, show what `file.new` + /// makes of them: rounded, at least 1 and at most the artboard limit. + #[test] + fn columns_read_float_rows_and_columns_as_file_new_does() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(5)); + for (rows, shown) in [(json!(4.0), 2), (json!(3.5), 2), (json!(2.4), 3)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 1, "rows": rows})); + assert_eq!(columns(&app), shown, "rows {rows}"); + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 3.0})); + assert_eq!(columns(&app), 3); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 1e9})); + assert_eq!(columns(&app), super::MAX_ARTBOARDS as u64); + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 0.4})); + assert_eq!(columns(&app), 1); + } + /// Recent shows each entry as it was made: a portrait and a landscape A3 are two cards of /// their own orientations, and only the chosen one is selected (#2860). #[test] From abe8b303ded7186796ad1ac8647f142a02ef1375 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:14:01 -0800 Subject: [PATCH 4/5] Scripts: remove and removeAll keep art on a locked artboard PageItem.remove() and PageItems.removeAll() checked only whether the object 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 object ids and delete nothing, as art on a locked artboard is not editable elsewhere in the document. --- crates/engine/src/script/dom.rs | 26 +++++++++++++++++++++----- crates/engine/src/tests/script_dom.rs | 24 ++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 47 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index e70dfbb86a..bce4edad74 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1249,19 +1249,26 @@ fn items_index(h: &Host, a: &[Data]) -> Answer { } /// `pageItems.removeAll()`: deletes every object of the document in one command. A hidden or -/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted. +/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted, +/// and so does an object on a locked artboard. fn items_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = items_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = top_items(&st.doc); let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().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::>().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::>()})))?; } @@ -1518,17 +1525,26 @@ fn item_z_order_position(h: &Host, a: &[Data]) -> Answer { } /// `remove()`: deletes the object. A hidden or locked object, one in a hidden or locked layer or -/// group, or a group holding one is refused, as [`items_remove_all`] refuses it. +/// group, a group holding one, or an object on a locked artboard is refused, as [`items_remove_all`] +/// refuses it. fn item_remove(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - let whole = with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable)); + let (whole, on_locked) = with_doc(h, item.doc, |_, st| { + (editable(&st.doc, item.id) && st.doc.node(item.id).is_some_and(all_editable), st.doc.on_locked_artboard(item.id)) + }); if !whole { return Err(HostError::Error(format!("cannot delete hidden or locked objects: {}", item.id.0))); } + if on_locked { + return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0))); + } edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0]}))?; Ok(Data::Undefined) } +/// The error of `remove()` and `removeAll()` for an object on a locked artboard. +const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; + /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 9d933378ea..26632b7055 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -973,6 +973,30 @@ fn remove_refuses_hidden_or_locked_art_as_remove_all_does() { assert!(s.active().unwrap().doc.node(b).is_none()); } +/// Art on a locked artboard stays: `remove()` and `removeAll()` throw and delete nothing. +#[test] +fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { + let (mut s, a, b) = doc(); + 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, "app.activeDocument.pageItems[1].remove();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", b.0)), "{e}"); + let e = failure(&mut s, "app.activeDocument.pageItems.removeAll();"); + assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&a.0.to_string()), "{e}"); + assert!(s.active().unwrap().doc.node(a).is_some() && s.active().unwrap().doc.node(b).is_some()); + assert_eq!(undo_steps(&s), steps); + lock(&mut s, false); + let out = log(&mut s, "var p = app.activeDocument.pageItems; p[1].remove(); p.removeAll(); vc.log(p.length);"); + assert_eq!(out, vec![json!(0)]); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/docs/mcp.md b/docs/mcp.md index a826f5b3b8..51cd09fdbb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2673,7 +2673,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot tab as it was. 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 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. Setting `width` or `height` scales the object along + `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` and delete nothing. Setting `width` or `height` scales the object along 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, From 71aaa752a03dd40e4cbc7faef551022c6dd2f9a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 19:52:56 -0800 Subject: [PATCH 5/5] New Document: a new layout keeps the columns a preset's rows showed A preset made with file.new's rows under gridByColumn shows the column count those rows give the current number of artboards. Changing the Layout field removed the rows and kept the preset's stored columns, so Create laid out a different number of columns than the dialog showed. The layout change now writes the shown count into columns, for rows stored as integers or floats. Under gridByRow the dialog shows the stored columns and file.new rejects rows, so a layout change from it keeps the stored columns, as it does for rows file.new would reject. --- crates/ui-egui/src/dialogs/new_document.rs | 41 +++++++++++++++++++--- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index d7c20c0137..cf10f0035e 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,16 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. fn set_layout(d: &mut Dialog, key: &str, v: Value) { + let (lay, shown, ..) = layout(d); let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); - if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) { - o.remove("rows"); + if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) + && key == "layout" + && lay == ArtboardLayout::GridByColumn + { + o.insert("columns".into(), json!(shown)); } l[key] = v; d.fields.insert("artboardLayout".into(), l); @@ -914,7 +919,35 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 3, "spacing": 5.0})); set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "rows": 4})); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow"})); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 1})); + } + + /// A new layout keeps the columns a preset's rows showed, so Create lays out what the dialog + /// showed. Under a grid by row the dialog shows the stored columns, and they stay. + #[test] + fn a_new_layout_keeps_the_columns_a_presets_rows_showed() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + let columns = |app: &VectorcraftApp| super::layout(app.ui.dialog.as_ref().unwrap()).1; + set(&mut app, "artboards", json!(9)); + for to in ["gridByRow", "gridByColumn", "row", "column"] { + for rows in [json!(4), json!(4.0), json!(3.6)] { + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); + assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + } + } + set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByColumn", "columns": 2})); + assert_eq!(columns(&app), 2); + // Rows file.new would reject leave the stored columns the dialog showed. + set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": 0})); + assert_eq!(columns(&app), 2); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByRow")); + assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } /// Columns shows what a preset's rows give the current number of artboards.