diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 075211dc1a..460893a7c8 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -104,8 +104,9 @@ proptest = { workspace = true } vectorcraft-text = { workspace = true, features = ["test-fonts"] } # How many times an open reads a PDF. vectorcraft-pdf = { workspace = true, features = ["read-count"] } -# How many times the symbol list is read to find symbols by name. -vectorcraft-doc = { workspace = true, features = ["symbol-read-count"] } +# How many times the symbol list is read to find symbols by name, and how many objects are +# measured against locked artboards. +vectorcraft-doc = { workspace = true, features = ["symbol-read-count", "locked-artboard-count"] } wat = { workspace = true } # Zstandard streams for the Illustrator editing data fuzz tests. ruzstd = { workspace = true } diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ccee814d90..6136ac6de3 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (default: all in one row), rows?: n (gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index fb26b13c68..073de104cc 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -977,8 +977,9 @@ impl Session { /// Profile `name`'s document, its file's path and a warning for each color profile the file /// carries that can't be used: `None` when it has no file (the shipped profile, the defaults), - /// the reason when the request being served may not read it, or its file can't be read, is - /// larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft reads. + /// the reason when the request being served may not read it, or its file is a link or a folder, + /// can't be read, is larger than [`MAX_PROFILE_BYTES`] or isn't a native document VectorCraft + /// reads. fn read_profile(&self, name: &str) -> std::result::Result, String> { let Some(path) = self.profile_path(name) else { return Ok(None) }; let file = path.to_string_lossy().to_string(); @@ -989,8 +990,11 @@ impl Session { let denied = |_| PROFILE_DENIED.to_string(); 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); + 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()), + _ => {} } crate::file_access::check_read(&file).map_err(denied)?; crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index fb18dd55ef..f365ecd4e9 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -28,6 +28,7 @@ //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; +use std::collections::{HashMap, HashSet}; use std::rc::Rc; use std::sync::Arc; @@ -99,14 +100,16 @@ pub(super) enum Coords { 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, whether a call's own savepoint -/// ([`atomically`]) is open, the settings of each `DocumentPreset` the run made, and the -/// `Variable` and `Dataset` objects it gave out. +/// 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, the settings of each `DocumentPreset` the run made, and the `Variable` and `Dataset` +/// objects it gave out. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + items: RefCell>, + locked: RefCell>, saving: Cell, presets: RefCell>>, vars: variables::Handles, @@ -142,6 +145,57 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, Rc>); +/// A document's uid, the document and its new art ([`Document::new_art`]) as they were, and for +/// each object of a layer or sublayer asked about then, whether it was on a locked artboard. +type LockedList = (u64, Arc, Arc>, HashMap); + +/// How many documents' lists [`State`] keeps at once, of each kind. +const ITEM_LISTS: usize = 4; + +/// The kept list of the document `uid` as `doc` is, if there is one. +fn kept_items(lists: &[ItemList], uid: u64, doc: &Arc) -> Option>> { + lists.iter().find(|(u, d, _)| *u == uid && Arc::ptr_eq(d, doc)).map(|(_, _, ids)| ids.clone()) +} + +/// Keeps `list` in place of any earlier list of the same document, dropping the least recently +/// kept list beyond [`ITEM_LISTS`]. +fn keep_items(lists: &mut Vec, list: ItemList) { + lists.retain(|(u, _, _)| *u != list.0); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push(list); +} + +/// Whether node `id` of `st` is on a locked artboard ([`Document::on_locked_artboard`]). Each +/// object of a layer or sublayer is measured once while the document and its new art stay as they +/// are, so the members of a group are answered with one measurement of the group. +fn on_locked_artboard(h: &Host, st: &DocState, id: NodeId) -> bool { + if !st.doc.artboards.iter().any(|a| a.locked) { + return false; + } + let Some(object) = st.doc.layer_object(id).map(|n| n.id) else { + return false; + }; + let new_art = st.doc.new_art.get(); + let mut lists = h.dom.locked.borrow_mut(); + let at = match lists.iter().position(|(u, d, n, _)| *u == st.uid && Arc::ptr_eq(d, &st.doc) && Arc::ptr_eq(n, &new_art)) { + Some(at) => at, + None => { + lists.retain(|(u, ..)| *u != st.uid); + if lists.len() >= ITEM_LISTS { + lists.remove(0); + } + lists.push((st.uid, st.doc.clone(), new_art, HashMap::new())); + lists.len() - 1 + } + }; + match lists.get_mut(at) { + Some((.., held)) => *held.entry(object).or_insert_with(|| st.doc.on_locked_artboard(object)), + None => st.doc.on_locked_artboard(object), + } +} + type Answer = std::result::Result; /// A member function: the run's host and the call's arguments, `this` first. @@ -349,13 +403,11 @@ fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { } } -/// The ids of a document's page items in paint order ([`State`] keeps the last list). +/// The ids of a document's page items in paint order ([`State`] keeps the lists of the last +/// documents read). fn page_items(h: &Host, st: &DocState) -> Rc> { - if let Some((uid, doc, ids)) = &*h.dom.items.borrow() - && *uid == st.uid - && Arc::ptr_eq(doc, &st.doc) - { - return ids.clone(); + if let Some(ids) = kept_items(&h.dom.items.borrow(), st.uid, &st.doc) { + return ids; } fn walk(nodes: &[Arc], out: &mut Vec) { for n in nodes { @@ -373,7 +425,7 @@ fn page_items(h: &Host, st: &DocState) -> Rc> { let mut ids = Vec::new(); walk(&st.doc.layers, &mut ids); let ids = Rc::new(ids); - *h.dom.items.borrow_mut() = Some((st.uid, st.doc.clone(), ids.clone())); + keep_items(&mut h.dom.items.borrow_mut(), (st.uid, st.doc.clone(), ids.clone())); ids } @@ -896,6 +948,9 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { None | Some(Data::Null) => Vec::new(), Some(d) => { let i = preset_of(h, d).ok_or_else(|| HostError::Type("presetSettings must be a DocumentPreset".into()))?; + // The settings are charged as data passed to the call before they are copied. + let bytes = h.dom.presets.borrow()[i].iter().map(|(k, v)| k.len() as u64 + 2 + data_size(v)).sum::(); + h.charge_call(bytes)?; h.dom.presets.borrow()[i].clone() } }; @@ -1009,8 +1064,11 @@ fn preset_field(link: &Link, key: &'static str) -> HostMember { 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)?; + // The value handed back is charged as the setter charges it, before it is copied. + let i = preset_of(&h, arg(&a, 0)); + let bytes = i.map_or(0, |i| h.dom.presets.borrow()[i].iter().find(|(k, _)| k == key).map_or(0, |(_, v)| data_size(v))); + h.charge_call(16 + bytes)?; + let i = i.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())) }); @@ -1391,7 +1449,13 @@ 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())); } - set_props(h, a, |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v})) + // 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. + let item = this_item(h, a)?; + let now = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map(|n| f64::from(n.opacity) * 100.0)); + let v = now.filter(|now| (now - v).abs() < 1e-4).unwrap_or(v); + set_props(h, a, |_| false, json!({"opacity": v})) } fn item_selected(h: &Host, a: &[Data]) -> Answer { @@ -1529,9 +1593,11 @@ fn item_set_height(h: &Host, a: &[Data]) -> Answer { resize(h, a, false) } +/// `editable`: false for an object that is hidden or locked, in a hidden or locked layer or group, +/// or on a locked artboard. fn item_editable(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; - Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id)))) + Ok(Data::Bool(with_doc(h, item.doc, |_, st| editable(&st.doc, item.id) && !on_locked_artboard(h, st, item.id)))) } /// The item's place in its parent's stacking order, from 1 at the bottom. @@ -1964,4 +2030,29 @@ mod tests { assert_eq!(done_unless_refused(Err(HostError::Abort("canceled".into()))), Err(HostError::Abort("canceled".into()))); assert_eq!(done_unless_refused(Err(HostError::Range("too large".into()))), Err(HostError::Range("too large".into()))); } + + #[test] + fn page_item_lists_are_kept_for_several_documents() { + let docs: Vec> = (0..=ITEM_LISTS).map(|_| Arc::new(Document::new(100.0, 100.0))).collect(); + let ids = |n: u64| Rc::new(vec![NodeId(n)]); + let mut lists = Vec::new(); + keep_items(&mut lists, (1, docs[0].clone(), ids(1))); + keep_items(&mut lists, (2, docs[1].clone(), ids(2))); + // Reading two documents in turn keeps both lists. + assert_eq!(kept_items(&lists, 1, &docs[0]), Some(ids(1))); + assert_eq!(kept_items(&lists, 2, &docs[1]), Some(ids(2))); + // A changed document has no kept list, and its new list replaces the old one. + let changed = Arc::new(Document::new(100.0, 100.0)); + assert_eq!(kept_items(&lists, 1, &changed), None); + keep_items(&mut lists, (1, changed.clone(), ids(3))); + assert_eq!(lists.len(), 2); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + // Past the limit, the list kept longest ago goes. + for (uid, d) in (10..).zip(&docs[2..]) { + keep_items(&mut lists, (uid, d.clone(), ids(uid))); + } + assert_eq!(lists.len(), ITEM_LISTS); + assert_eq!(kept_items(&lists, 2, &docs[1]), None); + assert_eq!(kept_items(&lists, 1, &changed), Some(ids(3))); + } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 39acd9897b..005d729a8c 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1046,7 +1046,7 @@ impl Host { } let bridge = self.bridge.get().saturating_add(bytes); self.bridge.set(bridge); - if bridge > MAX_BRIDGE_BYTES { + if bridge > bridge_bytes() { return Err(self.over(OVER_BRIDGE)); } let n = self.calls_this_slice.get() + 1; @@ -2511,6 +2511,15 @@ fn growth_objects() -> u64 { GROWTH_OBJECTS } +/// The data a run may pass to and from commands. +fn bridge_bytes() -> u64 { + #[cfg(test)] + if let Some(n) = TEST_BRIDGE_BYTES.with(Cell::get) { + return n; + } + MAX_BRIDGE_BYTES +} + /// The limits of a command's result on its way to the script. fn result_limits() -> DataLimits { #[cfg(test)] @@ -2528,6 +2537,8 @@ thread_local! { pub(crate) static PANIC_IN_SLICE: Cell = const { Cell::new(false) }; /// Tests: the objects a run may add in place of [`GROWTH_OBJECTS`]. pub(crate) static TEST_GROWTH: Cell> = const { Cell::new(None) }; + /// Tests: the data a run may pass to and from commands in place of [`MAX_BRIDGE_BYTES`]. + pub(crate) static TEST_BRIDGE_BYTES: Cell> = const { Cell::new(None) }; /// Tests: the heap of a named engine in place of [`ENGINE_HEAP_BYTES`]. pub(crate) static TEST_ENGINE_HEAP: Cell> = const { Cell::new(None) }; /// Tests: the bytes of source maps a named engine keeps, in place of [`KEPT_MAP_BYTES`]. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index edf27aaf2a..11330bac10 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -906,6 +906,22 @@ fn a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported() { let _ = std::fs::remove_dir_all(&dir); } +#[cfg(unix)] +#[test] +fn a_profile_that_is_a_link_is_not_followed() { + let (mut s, dir) = with_profiles("link"); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + // A profile the folder held, moved out and linked back in. + let outside = std::env::temp_dir().join(format!("vc-newdoc-profile-outside-{}.vectorcraft", std::process::id())); + std::fs::rename(dir.join("Print.vectorcraft"), &outside).unwrap(); + std::os::unix::fs::symlink(&outside, dir.join("Print.vectorcraft")).unwrap(); + let r = s.execute("file.new", &json!({"preset": "Letter"})).unwrap(); + assert_eq!(r["profileError"]["reason"], "not a plain file", "{r}"); + assert!(r.get("profile").is_none(), "{r}"); + let _ = std::fs::remove_file(&outside); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_names_are_checked_and_editing_needs_the_folder() { let mut s = Session::new(); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..f517312983 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -206,6 +206,42 @@ fn page_item_properties_join_one_undo_step() { } } +/// An opacity a graph mark already has still replaces the opacity another mark of its series left on +/// the graph, as `object.setProps` does. +#[test] +fn an_opacity_a_graph_mark_already_has_replaces_the_one_its_series_keeps() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let csv = ",2024,2025\nQ1,3,2\nQ2,5,4"; + let r = s.execute("graph.create", &json!({"type": "column", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + let kept = + |s: &Session| s.active().unwrap().doc.node(id).unwrap().extras().graph.as_deref().unwrap().series_paints.first().and_then(|p| p.opacity); + let series = |s: &Session| { + let n = s.active().unwrap().doc.node(id).unwrap().clone(); + let group = n.children().unwrap().iter().find(|c| c.extras().series_index == Some(0)).unwrap().clone(); + group.children().unwrap().iter().map(|m| m.id).collect::>() + }; + let marks = series(&s); + s.execute("object.setProps", &json!({"id": marks[0].0, "opacity": 50})).unwrap(); + assert_eq!(kept(&s), Some(0.5)); + s.execute("object.setProps", &json!({"id": series(&s)[1].0, "name": "mark"})).unwrap(); + log(&mut s, "app.activeDocument.pageItems.getByName('mark').opacity = 100;"); + assert_eq!(kept(&s), None); +} + +/// Assigning an item the opacity it reports, rounded to four decimals, changes nothing. +#[test] +fn assigning_the_reported_opacity_changes_nothing() { + let (mut s, a, _) = doc(); + s.execute("object.setProps", &json!({"id": a.0, "opacity": 100.0 / 3.0})).unwrap(); + let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s)); + let out = log(&mut s, "var i = app.activeDocument.pageItems[0]; vc.log(i.opacity); i.opacity = i.opacity;"); + assert_eq!(out, vec![json!(33.3333)]); + assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn selection_assignment_is_atomic_across_invalid_items() { let (mut s, a, b) = doc(); @@ -913,6 +949,23 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn document_preset_values_count_toward_the_data_a_run_passes() { + // A 64 KiB title, set once, then read or handed to addDocument 32 times: 2 MiB, over a 1 MiB limit. + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 20))); + let mut s = Session::new(); + let set = "var p = new DocumentPreset(); p.title = new Array(65537).join('t');"; + let read = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) p.title;")); + let added = failure(&mut s, &format!("{set} for (var i = 0; i < 32; i++) try {{ app.documents.addDocument('Print', p, 5); }} catch (e) {{}}")); + let within = run(&mut s, &format!("{set} for (var i = 0; i < 8; i++) p.title;")); + crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None)); + for e in [read, added] { + assert!(e.contains("passed more data"), "{e}"); + } + within.unwrap(); + assert!(s.documents().is_empty()); +} + #[test] fn wrappers_go_stale_after_delete_and_undo() { let (mut s, _, _) = doc(); @@ -985,18 +1038,48 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { .unwrap(); }; lock(&mut s, true); + // An object on a second, unlocked artboard is not deleted either. + s.execute("artboard.new", &json!({"x": 1000, "y": 0, "width": 400, "height": 300})).unwrap(); + let c = rect(&mut s, 1100.0, 100.0, 50.0, 50.0); 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()); + let out = + log(&mut s, "try { app.activeDocument.pageItems.removeAll(); } catch (e) { vc.log(e.name); } vc.log(app.activeDocument.pageItems.length);"); + assert_eq!(out, vec![json!("Error"), json!(3)]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(a).is_some() && doc.node(b).is_some() && doc.node(c).is_some()); assert_eq!(undo_steps(&s), steps); + // `editable` is false for art on the locked artboard and true for art on the unlocked one. + let editable = "var p = app.activeDocument.pageItems; vc.log([p[0].editable, p[1].editable, p[2].editable]);"; + assert_eq!(log(&mut s, editable), vec![json!([false, false, true])]); lock(&mut s, false); + assert_eq!(log(&mut s, editable), vec![json!([true, true, true])]); 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)]); } +/// Reading `editable` on every member of a group on a locked artboard measures the group once. +#[test] +fn editable_measures_a_group_on_a_locked_artboard_once() { + let (mut s, a, b) = doc(); + let mut ids = vec![a.0, b.0]; + ids.extend((0..20).map(|i| rect(&mut s, 10.0 + f64::from(i), 200.0, 5.0, 5.0).0)); + s.execute("select.set", &json!({"ids": ids})).unwrap(); + s.execute("object.group", &json!({})).unwrap(); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let before = vectorcraft_doc::locked_artboard_measures(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, n = 0; for (var i = 0; i < p.length; i++) if (!p[i].editable) n++; vc.log(n);"); + assert_eq!(out, vec![json!(23)], "the group and its 22 members are on the locked artboard"); + assert_eq!(vectorcraft_doc::locked_artboard_measures() - before, 1); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..a36c1fb589 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,11 +253,14 @@ 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`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. Choosing +/// the layout that is already selected keeps the rows. 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!({})); + let same = key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) + && !same && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) && key == "layout" && lay == ArtboardLayout::GridByColumn @@ -930,7 +933,7 @@ mod tests { 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 to in ["gridByRow", "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}"); @@ -950,6 +953,24 @@ mod tests { assert_eq!(field(&app, "artboardLayout"), json!({"layout": "gridByRow", "columns": 2})); } + /// Choosing the grid by column that is already selected keeps a preset's rows, so Create puts + /// as many artboards in each column as before. + #[test] + fn choosing_the_selected_layout_keeps_a_presets_rows() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.newDialog", json!({})).unwrap(); + set(&mut app, "artboards", json!(5)); + let preset = json!({"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}); + set(&mut app, "artboardLayout", preset.clone()); + super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!("gridByColumn")); + assert_eq!(field(&app, "artboardLayout"), preset); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.artboards.len(), 5); + let first: Vec<_> = st.doc.artboards.iter().filter(|a| a.rect.x0 == 0.0).map(|a| a.rect.y0).collect(); + assert_eq!(first.len(), 4, "four artboards in the first column: {first:?}"); + } + /// Columns shows what a preset's rows give the current number of artboards. #[test] fn columns_follow_a_presets_rows_as_artboards_change() { diff --git a/docs/mcp.md b/docs/mcp.md index c2c703d9ca..b89202bf8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2652,7 +2652,8 @@ 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`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds), `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 `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same @@ -9145,8 +9146,8 @@ with the defaults. The profile is read on every `file.new`, so a replayed journal or a recorded action uses the profile as it is when it 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 +When the file is a link or a folder, 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, 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