diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index cf21c25e46..7e6028b045 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -105,8 +105,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 aa2538331f..8fd613830c 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/layer.rs b/crates/engine/src/cmd/layer.rs index 73c92877e9..d2258f4e4a 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -66,7 +66,7 @@ pub fn specs() -> Vec { "Set Current Layer", [], None, - "{id} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. Not an undo step → {id, layer}", + "{id, keepRows?: bool} click a row: it alone is highlighted, and the layer it is (or the layer it is in) becomes the current layer, where new art goes. `keepRows` true leaves the highlighted rows as they are. Not an undo step → {id, layer}", has_doc, set_current ), @@ -633,10 +633,13 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result { fn set_current(s: &mut Session, p: &Value) -> Result { const C: &str = "layer.setCurrent"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; + let keep_rows = switch_or(p, "keepRows", false, C)?; let st = s.doc_mut()?; let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?; st.active_layer = Some(layer); - st.layer_rows = vec![id]; + if !keep_rows { + st.layer_rows = vec![id]; + } st.revision += 1; Ok(json!({ "id": id.0, "layer": layer.0 })) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 60ff69ee05..ff6fb9a6a1 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 ecf01ed693..ea76e59fdf 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; @@ -86,13 +87,15 @@ 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, and the settings of each `DocumentPreset` the run made. +/// 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. #[derive(Default)] pub(super) struct State { coords: Cell, - items: RefCell>, + items: RefCell>, + locked: RefCell>, saving: Cell, presets: RefCell>>, } @@ -127,6 +130,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. @@ -334,31 +388,30 @@ 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 { match &n.kind { NodeKind::Layer { children, .. } => walk(children, out), NodeKind::RulerGuide { .. } => {} - NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + _ => { out.push(n.id); - walk(children, out); + if let Some(children) = n.children() { + walk(children, out); + } } - _ => out.push(n.id), } } } 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 } @@ -533,6 +586,31 @@ fn done_unless_refused(r: std::result::Result) -> std::result:: } } +/// Makes `layer` the current layer of the active document `uid` again, with `rows` the highlighted +/// Layers panel rows, after selecting objects made the layer of the last of them current and +/// cleared the rows. Nothing runs when `layer` is gone. `layer.highlight` puts the rows back when +/// they changed, and then `layer.setCurrent` with `keepRows` makes `layer` current when it is not. +fn restore_layer(h: &Host, uid: u64, layer: Option, rows: &[NodeId]) -> std::result::Result<(), HostError> { + let Some(layer) = layer else { return Ok(()) }; + let rows = { + let s = h.session.borrow(); + let Some(st) = s.active().filter(|st| st.uid == uid) else { return Ok(()) }; + if st.doc.node(layer).is_none() { + return Ok(()); + } + let rows: Vec = rows.iter().copied().filter(|r| st.doc.node(*r).is_some()).collect(); + (st.highlighted_rows() != rows).then(|| rows.iter().map(|r| r.0).collect::>()) + }; + if let Some(rows) = rows { + command(h, "layer.highlight", &json!({"ids": rows, "mode": "set"}))?; + } + let current = h.session.borrow().active().is_some_and(|st| st.active_layer == Some(layer)); + if !current { + command(h, "layer.setCurrent", &json!({"id": layer.0, "keepRows": true}))?; + } + Ok(()) +} + /// Runs `f` with the document `uid` active, and makes the document that was active before active /// again after. With `keep_selection`, the document's selection is put back as it was when `f`'s /// commands changed it (commands given ids select them first), direct-selected anchors, segments, @@ -545,10 +623,11 @@ fn on_doc( keep_selection: bool, f: impl FnOnce(&Host) -> std::result::Result, ) -> std::result::Result { - let (index, active, before) = { + let (index, active, before, layer) = { let s = h.session.borrow(); let index = s.documents().iter().position(|d| d.uid == uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; - (index, s.active_index(), s.documents()[index].selection.clone()) + let st = &s.documents()[index]; + (index, s.active_index(), st.selection.clone(), (st.active_layer, st.highlighted_rows())) }; let switch = active != Some(index); if switch { @@ -564,6 +643,9 @@ fn on_doc( if let Some(doc) = doc { restored = restore_selection(h, &doc, &before); } + if restored.is_ok() { + restored = restore_layer(h, uid, layer.0, &layer.1); + } } // The document that was active is active again before any error is given: `f`'s error first, // then the selection's, then the switch back's. @@ -804,7 +886,10 @@ impl NewDoc<'_> { if let Some(d) = self.preview { let mode = match d { Data::String(s) if s == "DocumentPreviewMode.DefaultPreview" => "default", - Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => "pixel", + // Pixel Preview is a setting of the app's view, which a script cannot turn on. + Data::String(s) if s == "DocumentPreviewMode.PixelPreview" => { + return Err(HostError::Error("DocumentPreviewMode.PixelPreview is not available yet".into())); + } Data::String(s) if s == "DocumentPreviewMode.OverprintPreview" => "overprint", _ => return Err(HostError::Type("previewMode must be a DocumentPreviewMode value".into())), }; @@ -881,6 +966,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() } }; @@ -928,6 +1016,10 @@ fn docs_add_document(h: &Host, a: &[Data]) -> Answer { let reason = e["reason"].as_str().unwrap_or_default(); return Err(HostError::Error(format!("the New Document profile {profile} could not be read: {reason}"))); } + // Each warning from reading the profile's file goes to the console. + for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) { + super::each_line(&format!("addDocument: {w}"), |line, cut| h.line(super::console::Entry::Log(line), cut)); + } let s = h.session.borrow(); let st = s.active().ok_or_else(|| HostError::Error(NO_ACTIVE_DOCUMENT.into()))?; Ok(doc_ref(h, st.uid)) @@ -994,8 +1086,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())) }); @@ -1147,10 +1242,16 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result vec![d], }; let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; + // The document is read once for every object: nothing changes it while the list is checked. + let (d, isolation, guides_locked) = with_doc(h, doc, |s, st| (st.doc.clone(), st.isolation, s.guides_locked())); + let locks = d.locked_artboards(); + for v in list { + let item = item_of(h, v)?; + // A path made into a guide is not selected while Lock Guides is on, as the selection + // commands leave it out. let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); + && crate::cmd::select::is_selectable(&d, isolation, &locks, item.id) + && !(guides_locked && crate::is_guide_path(&d, item.id)); if !ok { let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); @@ -1376,7 +1477,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 { @@ -1514,9 +1621,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. @@ -1625,7 +1734,8 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s if !editable(d, parent) { return Err(HostError::Error("the layer or group is hidden or locked".into())); } - if !editable(d, item.id) { + // An object on a locked artboard is not moved, as `editable` reads false for it. + if !editable(d, item.id) || on_locked_artboard(h, st, item.id) { let name = d.node(item.id).and_then(typename).unwrap_or("page item"); return Err(HostError::Error(format!("Cannot move {name} {}", item.id.0))); } @@ -1666,14 +1776,30 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul } /// `move(relativeObject, insertionLocation?)`: moves the item into or beside `relativeObject`, a -/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). +/// page item or a layer of its document (`insertionLocation` defaults to `PLACEATBEGINNING`). An +/// object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard +/// is refused. fn item_move(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; if matches!(arg(a, 1), Data::Undefined) { return Err(HostError::Type("move needs a relative object".into())); } let to = destination(h, item, arg(a, 1), arg(a, 2), false)?; - place(h, item.doc, item.id, &to)?; + // When the last path leaves a compound path, the compound path is deleted in the same step + // rather than left empty. + let emptied = with_doc(h, item.doc, |_, st| { + let parent = st.doc.parent_of(item.id).and_then(|p| st.doc.node(p))?; + (matches!(parent.kind, NodeKind::Compound { .. }) && parent.children().is_some_and(|c| c.len() == 1) && parent.id != to.parent) + .then_some(parent.id) + }); + match emptied { + None => place(h, item.doc, item.id, &to)?, + Some(compound) => atomically(h, |h| { + place(h, item.doc, item.id, &to)?; + on_doc(h, item.doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": [compound.0]})))?; + Ok(()) + })?, + } Ok(arg(a, 0).clone()) } @@ -1697,6 +1823,13 @@ fn item_duplicate(h: &Host, a: &[Data]) -> Answer { if in_compound(h, item) { return Err(HostError::Error(COMPOUND_MEMBER.into())); } + // `edit.duplicate` copies only what it can select. + let refused = with_doc(h, item.doc, |_, st| { + (!editable(&st.doc, item.id) || on_locked_artboard(h, st, item.id)).then(|| st.doc.node(item.id).and_then(typename).unwrap_or("page item")) + }); + if let Some(name) = refused { + return Err(HostError::Error(format!("Cannot duplicate {name} {}", item.id.0))); + } let to = match arg(a, 1) { Data::Undefined => { if !matches!(arg(a, 2), Data::Undefined) { @@ -1948,4 +2081,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 dd5e03185f..1e32d78ed0 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1075,7 +1075,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; @@ -2563,6 +2563,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)] @@ -2580,6 +2589,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/layers.rs b/crates/engine/src/tests/layers.rs index 22edfec458..f49637c768 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -157,6 +157,13 @@ fn clicking_rows_at_any_depth_highlights_them_and_sets_the_current_layer() { let n = rect(&mut s, 50.0); assert_eq!(parent(&s, n), Some(sub)); assert!(s.execute("layer.setCurrent", &json!({"id": 9999})).is_err()); + // `keepRows` makes the layer current and leaves the highlighted rows. + run(&mut s, "layer.setCurrent", json!({"id": b.0})); + run(&mut s, "layer.setCurrent", json!({"id": c.0, "keepRows": true})); + let st = s.doc().unwrap(); + assert_eq!((st.highlighted_rows(), st.current_layer()), (vec![b], Some(layer))); + assert!(s.execute("layer.setCurrent", &json!({"id": a.0, "keepRows": 1})).is_err()); + assert_eq!(s.doc().unwrap().current_layer(), Some(layer), "a bad keepRows changes nothing"); // Shift/Ctrl: several rows. run(&mut s, "layer.highlight", json!({"ids": [a.0, g.0], "mode": "set"})); run(&mut s, "layer.highlight", json!({"ids": [c.0], "mode": "add"})); 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..60e3a71521 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -100,6 +100,21 @@ fn page_items_are_live_and_typed_for_all_node_kinds() { ); } +#[test] +fn page_items_list_the_art_inside_a_blend() { + let (mut s, a, b) = doc(); + log(&mut s, "app.activeDocument.pageItems[0].name = 'first';"); + s.execute("object.blend.make", &json!({"ids": [a.0, b.0], "steps": 2})).unwrap(); + let out = log( + &mut s, + "var p = app.activeDocument.pageItems, t = [];\ + for (var i = 0; i < p.length; i++) t.push(p[i].typename);\ + vc.log(t.join(','));\ + vc.log(p.getByName('first').parent.typename); vc.log(p.index('first').typename);", + ); + assert_eq!(out, vec![json!("BlendItem,PathItem,PathItem"), json!("BlendItem"), json!("PathItem")]); +} + #[test] fn page_item_geometry_uses_document_coordinates_with_y_up() { let (mut s, _, _) = doc(); @@ -206,6 +221,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(); @@ -229,6 +280,25 @@ fn selection_assignment_is_atomic_across_invalid_items() { assert!(e.contains("Cannot select"), "{e}"); } +#[test] +fn a_guide_path_is_not_selected_while_guides_are_locked() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + // The assignment and `selected` refuse the guide path, and the selection stays as it was. + for source in ["app.activeDocument.selection = app.activeDocument.pageItems[0];", "app.activeDocument.pageItems[0].selected = true;"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot select PathItem {}", a.0)), "{source}: {e}"); + assert_eq!(s.active().unwrap().selection.objects, vec![b], "{source}"); + } + // With the guides unlocked, the guide path is selected. + s.execute("view.guides.lock", &json!({"locked": false})).unwrap(); + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + #[test] fn an_inactive_document_changes_without_switching_tabs() { let (mut s, a, _) = doc(); @@ -418,6 +488,30 @@ fn a_path_inside_a_compound_path_is_not_reordered() { assert_eq!(out, vec![json!([1, 2])]); } +#[test] +fn moving_the_last_path_out_of_a_compound_path_deletes_the_compound_path() { + let (mut s, a, b) = doc(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("object.compoundPath.make", &json!({})).unwrap(); + let compound = layer_order(&s)[0]; + let layer = s.active().unwrap().doc.layers[0].id; + let steps = undo_steps(&s); + let out = log( + &mut s, + "var d = app.activeDocument, c = d.pageItems[0], m = [d.pageItems[1], d.pageItems[2]];\ + m[0].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + m[1].move(c, ElementPlacement.PLACEBEFORE); vc.log(d.pageItems.length);\ + try { c.name; } catch (e) { vc.log(e.message); }", + ); + assert_eq!(out, vec![json!(3), json!(2), json!("Stale page item")]); + let doc = &s.active().unwrap().doc; + assert!(doc.node(compound).is_none(), "the empty compound path is deleted"); + // Each path went directly above the compound path, the second above the first. + assert_eq!(layer_order(&s), [b, a]); + assert!([a, b].iter().all(|id| doc.parent_of(*id) == Some(layer))); + assert_eq!(undo_steps(&s), steps + 1, "the run is one undo step"); +} + #[test] fn a_copy_of_an_object_with_a_large_id_is_the_copy() { let mut s = Session::new(); @@ -574,6 +668,37 @@ fn an_edit_keeps_a_layers_panel_target() { assert_eq!((sel.target, sel.objects.len(), sel.objects.contains(&b)), (Some(layer), 4, true)); } +#[test] +fn an_edit_keeps_the_current_layer() { + let (mut s, a, b) = doc(); + let first = s.active().unwrap().doc.layers[0].id; + let back = NodeId(s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap()); + let layer = |s: &Session| (s.active().unwrap().active_layer, s.active().unwrap().highlighted_rows()); + assert_eq!(layer(&s), (Some(back), vec![back])); + // Moving an object of the first layer selects it for the command; the new layer stays current. + log(&mut s, "app.activeDocument.pageItems[0].left = 50;"); + assert_eq!(layer(&s), (Some(back), vec![back])); + assert_eq!(s.active().unwrap().selection.objects, vec![b]); + // With nothing selected and no row highlighted, the layer stays current and no row is highlighted. + s.execute("select.none", &json!({})).unwrap(); + s.execute("layer.setCurrent", &json!({"id": back.0})).unwrap(); + s.execute("layer.highlight", &json!({"ids": [], "mode": "set"})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![])); + log(&mut s, "app.activeDocument.pageItems[1].left = 120;"); + assert_eq!(layer(&s), (Some(back), vec![])); + assert!(s.active().unwrap().selection.objects.is_empty()); + // Targeting a layer makes it current and leaves another layer's row highlighted; both stay. + s.execute("layer.highlight", &json!({"ids": [first.0], "mode": "set"})).unwrap(); + s.execute("layer.target", &json!({"id": back.0})).unwrap(); + assert_eq!(layer(&s), (Some(back), vec![first])); + log(&mut s, "app.activeDocument.pageItems[0].left = 70;"); + assert_eq!(layer(&s), (Some(back), vec![first])); + // Assigning the selection makes the layer of the selected object current, as a click does. + log(&mut s, "app.activeDocument.selection = app.activeDocument.pageItems[0];"); + assert_eq!(s.active().unwrap().active_layer, Some(first)); + assert_eq!(s.active().unwrap().selection.objects, vec![a]); +} + /// A document with a rectangle at the bottom of the stack, then a dynamic symbol instance of two /// rectangles and an Objects on Path group of one rectangle: (session, instance, group, the /// group's rectangle). @@ -913,6 +1038,60 @@ fn add_document_applies_the_profile_file_and_throws_when_it_cannot_be_read() { let _ = std::fs::remove_dir_all(&dir); } +#[test] +fn add_document_names_a_color_profile_of_the_profile_file_that_cannot_be_used() { + let dir = std::env::temp_dir().join(format!("vc-script-add-document-warning-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let mut s = Session::new(); + s.attach_new_doc_profiles(dir.clone()); + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + while !s.documents().is_empty() { + s.execute("file.close", &json!({})).unwrap(); + } + let file = dir.join("Print.vectorcraft"); + let mut v: Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + let broken = format!("Script profile broken {}", std::process::id()); + v["profiles"] = json!({ &broken: {"mime": "application/vnd.iccprofile", "data": "AAAA"} }); + std::fs::write(&file, serde_json::to_vec(&v).unwrap()).unwrap(); + let r = run(&mut s, "vc.log(app.documents.addDocument('Print').typename);").unwrap(); + assert_eq!(r["log"], json!(["Document"])); + let lines = r["console"]["lines"].as_array().cloned().unwrap_or_default(); + let named = lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("addDocument: ") && l.contains(&broken)); + assert!(named, "{lines:?}"); + assert_eq!(s.documents().len(), 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn add_document_refuses_pixel_preview() { + let mut s = Session::new(); + let e = failure(&mut s, "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.PixelPreview; app.documents.addDocument('Web', p);"); + assert!(e.contains("DocumentPreviewMode.PixelPreview is not available yet"), "{e}"); + assert!(s.documents().is_empty()); + let out = log( + &mut s, + "var p = new DocumentPreset(); p.previewMode = DocumentPreviewMode.DefaultPreview; vc.log(app.documents.addDocument('Web', p).typename);", + ); + assert_eq!(out, vec![json!("Document")]); +} + +#[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 +1164,97 @@ 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)]); } +#[test] +fn move_and_duplicate_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 (order, steps) = (layer_order(&s), undo_steps(&s)); + let e = failure(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert!(e.contains(&format!("Cannot move PathItem {}", a.0)), "{e}"); + assert_eq!((layer_order(&s), undo_steps(&s)), (order.clone(), steps)); + // `duplicate` refuses it too, with or without a relative object. + for source in ["app.activeDocument.pageItems[0].duplicate();", "var p = app.activeDocument.pageItems; p[0].duplicate(p[1]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", a.0)), "{source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps)); + lock(&mut s, false); + log(&mut s, "var p = app.activeDocument.pageItems; p[0].move(p[1], ElementPlacement.PLACEBEFORE);"); + assert_eq!(layer_order(&s), [b, a]); +} + +#[test] +fn duplicate_refuses_hidden_or_locked_art() { + let (mut s, a, b) = doc(); + for (on, off) in [ + (json!({"ids": [b.0], "locked": true}), json!({"ids": [b.0], "locked": false})), + (json!({"ids": [b.0], "visible": false}), json!({"ids": [b.0], "visible": true})), + ] { + s.execute("object.setProps", &on).unwrap(); + let (order, steps) = (layer_order(&s), undo_steps(&s)); + // With no argument and with a relative object. + for source in ["app.activeDocument.pageItems[1].duplicate();", "var p = app.activeDocument.pageItems; p[1].duplicate(p[0]);"] { + let e = failure(&mut s, source); + assert!(e.contains(&format!("Cannot duplicate PathItem {}", b.0)), "{on} {source}: {e}"); + } + assert_eq!((layer_order(&s), undo_steps(&s)), (order, steps), "{on}"); + s.execute("object.setProps", &off).unwrap(); + } + log(&mut s, "app.activeDocument.pageItems[1].duplicate();"); + let order = layer_order(&s); + assert_eq!(order.len(), 3); + assert!(order.contains(&a) && order.contains(&b)); +} + +/// 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 c220970703..8b9fce1d8c 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -511,8 +511,12 @@ fn shown_columns(s: &DocSettings) -> u32 { } /// Picks the artboard layout. A preset's rows are dropped, and a grid by column made with them -/// keeps the column count Columns showed. +/// keeps the column count Columns showed. Choosing the layout that is already selected keeps the +/// rows. fn set_layout(s: &mut DocSettings, l: ArtboardLayout) { + if l == s.layout { + return; + } if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { s.columns = shown_columns(s); } @@ -884,7 +888,7 @@ mod tests { /// 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() { - for to in ArtboardLayout::ALL.iter() { + for to in ArtboardLayout::ALL.iter().filter(|l| **l != ArtboardLayout::GridByColumn) { for rows in [json!(4), json!(4.0), json!(3.6)] { let mut s = settings(json!({"artboards": 9, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": rows}})); assert_eq!(super::shown_columns(&s), 3, "9 artboards in rows {rows}"); @@ -897,6 +901,23 @@ mod tests { assert_eq!((s.rows, s.columns, super::shown_columns(&s)), (0, 2, 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 s = settings(json!({"artboards": 5, "artboardLayout": {"layout": "gridByColumn", "columns": 2, "rows": 4, "spacing": 10}})); + let before = s.to_json(); + super::set_layout(&mut s, ArtboardLayout::GridByColumn); + assert_eq!(s.to_json(), before); + assert_eq!((s.rows, super::shown_columns(&s)), (4, 2)); + let mut app = app(); + app.run("file.new", s.to_json()).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, also after /// `ui.dialog.set` changes the artboards. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 7d592e4635..125480847f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2667,18 +2667,23 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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. + profile and the reason, and makes no document. Each warning from reading the profile's file (a color profile in it + that cannot be used, for example) goes to the Script Console as a line `addDocument: `. A `previewMode` of + `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. `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/) - has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each + lists every object in the document's layers, the objects inside groups, compound paths, blends, envelopes, repeats + and intertwines included, and 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` (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?)`, + 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 @@ -2686,7 +2691,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER` directly below it. An object of another document throws `Cross-document placement is not available`, and when `node.move` refuses the place of a copy, `duplicate` throws that error and leaves the documents, the selection and - the undo history as they were before the call. `duplicate` on a path inside a compound path throws + the undo history as they were before the call. `move` on an object that is hidden or locked, inside a hidden or + locked layer or group, or on a locked artboard throws `Cannot move` and moves nothing. `duplicate` on such an + object, with or without a relative object, throws `Cannot duplicate` and makes no copy. When `move` takes the last + path out of a compound path, the empty compound path is deleted in the same undo step. `duplicate` on a path inside a compound path throws `Duplicating a path inside a compound path is not available yet`, and `zOrder` on one throws `Reordering a path inside a compound path is not available yet` and leaves the document unchanged. A script that holds a placed image keeps the same object when the image is embedded: the next read gives that object, now a `RasterItem`. The @@ -2700,7 +2708,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem` 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 bad value throws an error and changes nothing. An object that was deleted, or that a named engine + 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 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()` @@ -2709,7 +2718,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Not found`; and `app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item, a list of at most 10,000, `null` or `[]`, and an object that cannot be selected throws `Cannot select` with - nothing changed. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, + nothing changed. While View › Guides › Lock Guides is on, a path made into a guide cannot be selected this way or + with `selected`. `getIsFileOpen` compares the path with the open documents' files as text (in a Windows path, letter case is ignored and `\` matches `/`) and does not resolve the path it is given. A document counts only when the automation read roots allow its file, and that check can look the document's file up on disk. A path with `..`, a network path, a NUL character or more than 4,096 bytes throws an error. Some members the Application, @@ -6495,8 +6505,9 @@ itself, and each sublayer has its own colour for the selection highlight. `docum report `color`, `template`, `printable`, `preview`, `dimImages` and `clip`), the `currentLayer` (where new art goes) and `layerRows`, the rows highlighted in the panel. -- **Clicking rows** (not undo steps): `layer.setCurrent {id}` is a plain click on any row: it alone is highlighted - and its layer (the row itself when it is a layer or sublayer) becomes current. `layer.highlight {ids, mode?: +- **Clicking rows** (not undo steps): `layer.setCurrent {id, keepRows?}` is a plain click on any row: it alone is + highlighted and its layer (the row itself when it is a layer or sublayer) becomes current; with `keepRows` true the + highlighted rows stay as they are. `layer.highlight {ids, mode?: set|add|toggle}` is Shift-click (a range) and Ctrl/Cmd-click (toggle). Selecting art makes its layer current. Without `ids`, the panel commands below act on the highlighted rows, else on the current layer. - **Selection column**: `layer.selectAll {id, add?}` selects a row's visible, unlocked art (a layer's sublayers' @@ -9250,8 +9261,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