From 69448d0c2387ca69d22019ef8cee6eeb8591c5e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:16:56 -0800 Subject: [PATCH 1/9] Scripts: character and paragraph styles for scripts document.characterStyles and document.paragraphStyles list a document's styles, the Normal style first, and add, find and remove them. Each CharacterStyle and ParagraphStyle has a name, its attributes, applyTo with clearingOverrides, and remove; setting an attribute redefines the style through charStyle.setAttrs or paraStyle.setAttrs. A text range's characterStyles and paragraphStyles list the styles its text is in. Style names are trimmed and must have 1 to 256 characters and no control characters, one run names at most 4,096 styles, and a style object throws Stale style once its style is removed or renamed by a command. ParagraphStyle.characterAttributes is not available yet. charStyle.load, paraStyle.load and textStyle.loadAll refuse a file larger than 64 MB without reading it in full. --- crates/engine/src/cmd/textstyles.rs | 12 +- crates/engine/src/cmd/textstyles/tests.rs | 18 + crates/engine/src/script/dom.rs | 6 + crates/engine/src/script/dom/text.rs | 13 +- crates/engine/src/script/dom/text/styles.rs | 715 ++++++++++++++++++++ crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_styles.rs | 331 +++++++++ docs/mcp.md | 27 +- docs/target-app-parity.md | 3 +- 10 files changed, 1121 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/text/styles.rs create mode 100644 crates/engine/src/tests/script_styles.rs diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..3b57c2e067 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -148,8 +148,11 @@ macro_rules! style_cmds { }; } +/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes. +pub const MAX_LOAD_BYTES: usize = 64 << 20; + /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec { let mut v = style_cmds!( @@ -1266,12 +1269,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, (None, Some(text), _) => text.as_bytes().to_vec(), + (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; + if bytes.len() > MAX_LOAD_BYTES { + return Err(too_large()); + } let file = str_param(p, "name").or(path).unwrap_or("Styles"); let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?; if src.preview_only { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..1f8511d7ac 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -830,6 +830,24 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } +/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit. +#[test] +fn loading_refuses_a_file_larger_than_64_mb() { + let (mut s, _) = session_with_text("Title"); + let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Big.vectorcraft"); + std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); + let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + assert_eq!(s.doc().unwrap().doc, before); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is /// out of the range `charStyle.new` takes is skipped. #[test] diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bef4c60707..87a6310ec3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -581,6 +581,11 @@ fn on_doc( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_command(h: &Host) { + text::styles::after_command(h); +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -1868,6 +1873,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("textFrames", text::doc_text_frames(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); + document.extend(text::styles::doc_members(l)); document.extend( ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..0366dec5dd 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -44,6 +44,8 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod styles; + /// The error of a text range, or of a collection of one, whose frame's text changed other than /// through the object model. pub const STALE_RANGE: &str = "Stale text range"; @@ -188,6 +190,8 @@ pub(in crate::script) struct TextState { /// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character /// names that is not installed is added at the end. fonts: RefCell>>, + /// The styles the run's style objects name. + styles: styles::StyleState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1504,6 +1508,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.extend(styles::range_members(l)); range.extend( [ "lines", @@ -1511,8 +1516,6 @@ pub(super) fn classes(l: &Link) -> Vec { "textRanges", "story", "kerning", - "characterStyles", - "paragraphStyles", "textSelection", "changeCaseTo", "select", @@ -1537,7 +1540,7 @@ pub(super) fn classes(l: &Link) -> Vec { chars.extend(attr_members(l)); let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); - vec![ + let mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1589,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(styles::classes(l)); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs new file mode 100644 index 0000000000..f2e140bd45 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,715 @@ +//! Character and paragraph styles in the script object model: `document.characterStyles` and +//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text +//! of a `TextRange` uses, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A document's collection lists its Normal style first, then its other styles in the order the +//! panel lists them. +//! - A style object names its style for the rest of the run, also after the script renames it +//! through `name`. Once the style is removed, or renamed or removed other than through the object +//! model, or its document is closed, every member throws `Stale style`; a style added later under +//! the same name is another style. +//! - A style name is trimmed, and must then be 1 to 256 characters long with no control +//! characters. +//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the +//! style does not set. Setting one redefines the style: text in the style takes the new value +//! where it had the style's old one and keeps its other changes. +//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words +//! or paragraphs of one, in the style's document. A character style styles exactly that text and +//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches. +//! `clearingOverrides` left out is false; true resets the text to the Normal style first. +//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or +//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in +//! no other style. They do not add or remove styles. +//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its +//! look and is in the Normal style after. +//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`, +//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef}; +use vectorcraft_geom::Point; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref}; + +use super::{ + ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref, + function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text, + text_of, this_range, typename_of, usize_of, whole_span, with_doc, +}; +use crate::DocState; +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs}; + +/// The error of a style object whose style is gone. +pub const STALE_STYLE: &str = "Stale style"; +/// The longest style name, in characters, after trimming. +pub const MAX_STYLE_NAME: usize = 256; +/// The most styles one run's style objects name. +pub const MAX_HELD: usize = 4096; + +/// A style that a run's style objects name: its document, its kind and its name now. +struct Slot { + uid: u64, + para: bool, + name: String, + live: bool, +} + +/// A document's uid and its character and paragraph style lists when the slots were last checked. +type Seen = (u64, Shared>, Shared>); + +/// The styles a run's style objects name; an object holds its slot's number. +#[derive(Default)] +pub(super) struct StyleState { + slots: RefCell>, + seen: RefCell>, +} + +/// Marks stale each style object whose style the command just run removed or renamed, so a style +/// removed and made again under its name by later commands is another style. A document whose +/// style lists did not change is not checked again. +pub(in crate::script) fn after_command(h: &Host) { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + if !slots.iter().any(|s| s.live) { + return; + } + let s = h.session.borrow(); + let mut seen = h.dom.text.styles.seen.borrow_mut(); + seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); + for st in s.documents() { + let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles)); + if same { + continue; + } + seen.retain(|(uid, ..)| *uid != st.uid); + seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { + slot.live = has_style(st, slot.para, &slot.name); + } + } + for slot in slots.iter_mut().filter(|x| x.live) { + if !s.documents().iter().any(|d| d.uid == slot.uid) { + slot.live = false; + } + } +} + +fn normal(para: bool) -> &'static str { + if para { NORMAL_PARA } else { NORMAL_CHAR } +} + +fn cmd(para: bool, verb: &str) -> String { + format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" }) +} + +fn style_class(para: bool) -> &'static str { + if para { "ParagraphStyle" } else { "CharacterStyle" } +} + +fn list_class(para: bool) -> &'static str { + if para { "ParagraphStyles" } else { "CharacterStyles" } +} + +fn defs(st: &DocState, para: bool) -> &Vec { + if para { &st.doc.para_styles } else { &st.doc.char_styles } +} + +/// The document's style names of a kind, the Normal style first. +fn names(st: &DocState, para: bool) -> Vec { + let mut out = vec![normal(para).to_string()]; + out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para))); + out +} + +fn has_style(st: &DocState, para: bool, name: &str) -> bool { + name == normal(para) || defs(st, para).iter().any(|d| d.name == name) +} + +fn stale() -> HostError { + HostError::Error(STALE_STYLE.into()) +} + +/// The style object for the style `name` of the document `uid`: the same slot as every other +/// object naming it in this run. +fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + } + slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.len() - 1 + } + }; + Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)])) +} + +/// A style a style object names. +struct Style { + doc: Doc, + para: bool, + slot: usize, + name: String, +} + +/// The style `d` names, when it is an object of one of `classes` (with the kind each names). +fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result { + let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para))); + let Some((handle, para)) = found else { + return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0)))); + }; + let [run, uid, slot] = handle.as_slice() else { return Err(stale()) }; + let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?; + let slot = usize_of(*slot).ok_or_else(stale)?; + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; + if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + s.live = false; + return Err(stale()); + } + Ok(Style { doc, para, slot, name: s.name.clone() }) +} + +fn this_style(h: &Host, a: &[Data]) -> std::result::Result { + style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)]) +} + +/// Marks the slots of the styles `names` of the document `uid` as removed. +fn forget(h: &Host, uid: u64, para: bool, names: &[String]) { + for s in h.dom.text.styles.slots.borrow_mut().iter_mut() { + if s.uid == uid && s.para == para && names.contains(&s.name) { + s.live = false; + } + } +} + +/// A style name a script gave, trimmed. +fn style_name(v: &Data) -> std::result::Result { + let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) }; + if s.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + let t = s.trim(); + if t.is_empty() { + return Err(HostError::Range("a style name must not be empty".into())); + } + if t.chars().count() > MAX_STYLE_NAME { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + if t.chars().any(char::is_control) { + return Err(HostError::Range("a style name must not hold control characters".into())); + } + Ok(t.to_string()) +} + +/// Runs the style command `verb` of the kind on the document of `doc`. +fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result { + on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params)) +} + +// ---- CharacterStyle and ParagraphStyle ---- + +fn style_name_get(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_style(h, a)?.name)) +} + +/// `name = …`: renames the style; the Normal style keeps its name. +fn style_name_set(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let to = style_name(arg(a, 1))?; + if to == style.name { + return Ok(Data::Undefined); + } + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be renamed", style.name))); + } + if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) { + return Err(HostError::Error(format!("a style named {to} already exists"))); + } + run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?; + forget(h, style.doc.uid, style.para, std::slice::from_ref(&to)); + if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) { + s.name = to; + s.live = true; + } + Ok(Data::Undefined) +} + +fn style_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, this_style(h, a)?.doc.uid)) +} + +fn style_typename(h: &Host, a: &[Data]) -> Answer { + Ok(text(style_class(this_style(h, a)?.para))) +} + +fn attributes(h: &Host, a: &[Data], class: &str) -> Answer { + let style = this_style(h, a)?; + Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)])) +} + +fn style_character_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "CharacterStyleAttributes") +} + +fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "ParagraphStyleAttributes") +} + +/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after. +fn style_remove(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be removed", style.name))); + } + run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?; + forget(h, style.doc.uid, style.para, &[style.name]); + Ok(Data::Undefined) +} + +/// The text a style is applied to: a text range, a text frame, or the characters, words or +/// paragraphs of one. +fn target_span(h: &Host, d: &Data) -> std::result::Result { + if handle_of(d, "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, d)?)?.1); + } + const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"]; + if !TEXT.iter().any(|c| handle_of(d, c).is_some()) { + return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into())); + } + span_of(h, d, &TEXT) +} + +/// `applyTo(textItem, clearingOverrides?)`. +fn style_apply_to(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let target = target_span(h, arg(a, 1))?; + let clear = match arg(a, 2) { + Data::Undefined => false, + Data::Bool(b) => *b, + _ => return Err(HostError::Type("clearingOverrides must be true or false".into())), + }; + if target.item.doc.uid != style.doc.uid { + return Err(HostError::Error("the text is in another document than the style".into())); + } + let (index, s, e, _) = resolve(h, target)?; + h.charge_call(16 + (e - s) as u64)?; + let (start, end) = if style.para { + let (_, ba, bb) = para_range(&index, s, e); + (ba, bb) + } else { + if s == e { + return Ok(Data::Undefined); + } + (index.byte(s, false), index.byte(e, true)) + }; + let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end}); + run(h, style.doc, style.para, "apply", &p)?; + Ok(Data::Undefined) +} + +// ---- the attributes of a style ---- + +/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets. +const CHAR_KEYS: [(&str, &str); 11] = [ + ("size", "size"), + ("leading", "leading"), + ("tracking", "tracking"), + ("baselineShift", "baseline_shift"), + ("hScale", "h_scale"), + ("vScale", "v_scale"), + ("rotation", "rotation"), + ("underline", "underline"), + ("strikethrough", "strikethrough"), + ("font", "font_family"), + ("style", "font_style"), +]; + +/// The script's `Justification` members and the alignments a paragraph style stores. +const JUSTIFY: [(&str, &str); 7] = [ + ("LEFT", "Left"), + ("CENTER", "Center"), + ("RIGHT", "Right"), + ("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"), + ("FULLJUSTIFY", "JustifyAll"), +]; + +/// The style an attributes object belongs to and the attributes it sets. +fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map), HostError> { + let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" }; + let style = style_of(h, arg(a, 0), &[(class, para)])?; + let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?; + Ok((style, attrs)) +} + +fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { + let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num); + let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool); + match attr { + Attr::Size => n("size"), + Attr::Leading => n("leading"), + Attr::AutoLeading => match m.get("leading") { + Some(Value::Null) => Data::Bool(true), + Some(v) if v.is_number() => Data::Bool(false), + _ => Data::Undefined, + }, + Attr::Tracking => n("tracking"), + Attr::BaselineShift => n("baseline_shift"), + Attr::HorizontalScale => n("h_scale"), + Attr::VerticalScale => n("v_scale"), + Attr::Rotation => n("rotation"), + Attr::Underline => b("underline"), + Attr::StrikeThrough => b("strikethrough"), + Attr::TextFont => match m.get("font_family").and_then(Value::as_str) { + Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), + None => Data::Undefined, + }, + } +} + +fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { + let (_, m) = attrs_of(h, a, false)?; + Ok(char_value(h, attr, &m)) +} + +/// Redefines the style with `attrs`, unless they are what it has. +fn redefine(h: &Host, style: &Style, old: &Map, attrs: Map) -> Answer { + if attrs == *old { + return Ok(Data::Undefined); + } + run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?; + Ok(Data::Undefined) +} + +fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, false)?; + // `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph + // with the default justification. + let base = CharStyle::default(); + let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size); + let leading = old.get("leading").and_then(Value::as_f64); + let sample = CharStyle { size, leading, ..base }; + let t = TextObject::point(Point::default(), "", sample.clone()); + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let mut attrs = old.clone(); + for (k, v) in param.as_object().into_iter().flatten() { + let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; + let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() }; + attrs.insert((*key).to_string(), v); + } + redefine(h, &style, &old, attrs) +} + +fn para_key(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "justify", + ParaAttr::FirstLineIndent => "first_line_indent", + ParaAttr::LeftIndent => "left_indent", + ParaAttr::RightIndent => "right_indent", + ParaAttr::SpaceBefore => "space_before", + ParaAttr::SpaceAfter => "space_after", + } +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let (_, m) = attrs_of(h, a, true)?; + let v = m.get(para_key(attr)); + Ok(match attr { + ParaAttr::Justification => match v.and_then(Value::as_str) { + Some("Auto") => text("Justification.LEFT"), + Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))), + None => Data::Undefined, + }, + _ => v.and_then(Value::as_f64).map_or(Data::Undefined, num), + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, true)?; + let (_, _, wants) = para_param(attr, name, arg(a, 1))?; + let value = match (&wants, attr) { + (Data::String(s), ParaAttr::Justification) => { + let m = s.strip_prefix("Justification.").unwrap_or(s); + let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j); + json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?) + } + (Data::Number(n), _) => json!(n), + _ => return Err(HostError::Type(format!("{name} must be a finite number"))), + }; + let mut attrs = old.clone(); + attrs.insert(para_key(attr).to_string(), value); + redefine(h, &style, &old, attrs) +} + +/// The body of a member that captures what it reads or sets. +type Body = Rc Answer>; + +/// Members whose getter and setter each charge the call, as [`function`] does. +fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember { + let wrap = |f: Body| -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = super::super::current(&l)?; + h.charge_call(16 + a.iter().map(super::super::data_size).sum::())?; + f(&h, &a) + }) + }; + HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) } +} + +fn char_members(link: &Link) -> Vec<(String, HostMember)> { + ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)))) + .collect() +} + +fn para_members(link: &Link) -> Vec<(String, HostMember)> { + PARA_ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)))) + .collect() +} + +// ---- CharacterStyles and ParagraphStyles ---- + +/// What a collection of styles lists: a document's styles, or those a text range uses. +enum Of { + Doc(Doc), + Range(Span), +} + +fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> { + let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) { + (Some(_), _) => false, + (_, Some(_)) => true, + _ => return Err(HostError::Type("this is not a CharacterStyles".into())), + }; + let class = list_class(para); + let len = handle_of(d, class).map_or(0, |v| v.len()); + Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para)) +} + +/// The document and the names of the styles a collection lists. +fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec), HostError> { + match of { + Of::Doc(doc) => { + let names = with_doc(h, *doc, |_, st| names(st, para)); + h.charge_call(names.len() as u64)?; + Ok((*doc, names)) + } + Of::Range(r) => { + let (index, s, e, _) = resolve(h, *r)?; + let used = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let used: Vec> = if para { + let (paras, _, _) = para_range(&index, s, e); + paras.map(|i| t.para_at(i).style_name.clone()).collect() + } else { + styles_in(t, index.byte(s, false), index.byte(e, true))?.into_iter().map(|(c, _)| c.style_name).collect() + }; + h.charge_call(used.len() as u64)?; + let mut out: Vec = Vec::new(); + for n in used { + let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string()); + if !out.contains(&n) { + out.push(n); + } + } + if out.is_empty() { + out.push(normal(para).to_string()); + } + Ok::<_, HostError>(out) + })?; + Ok((r.item.doc, used)) + } + } +} + +fn list_length(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + Ok(num(float(listed(h, &of, para)?.1.len() as u64))) +} + +fn list_parent(h: &Host, a: &[Data]) -> Answer { + let (of, _) = list_of(h, arg(a, 0))?; + match of { + Of::Doc(doc) => Ok(doc_ref(h, doc.uid)), + Of::Range(r) => { + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) + } + } +} + +fn list_at(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = match &of { + Of::Doc(doc) => with_doc(h, *doc, |_, st| match i { + 0 => Some(normal(para).to_string()), + _ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(), + }) + .map(|n| (*doc, n)), + Of::Range(_) => { + let (doc, names) = listed(h, &of, para)?; + names.get(i).cloned().map(|n| (doc, n)) + } + }; + match found { + Some((doc, name)) => style_ref(h, doc.uid, para, &name), + None => Ok(Data::Undefined), + } +} + +fn list_by_name(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let (doc, names) = listed(h, &of, para)?; + match names.iter().find(|n| *n == name) { + Some(n) => style_ref(h, doc.uid, para, n), + None => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn list_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a), + Data::Number(_) => match list_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a document's collection; a range's collection cannot be changed. +fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> { + match list_of(h, arg(a, 0))? { + (Of::Doc(doc), para) => Ok((doc, para)), + (Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())), + } +} + +/// `add(name)`: a new style that sets no attributes. +fn list_add(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let name = style_name(arg(a, 1))?; + if with_doc(h, doc, |_, st| has_style(st, para, &name)) { + return Err(HostError::Error(format!("a style named {name} already exists"))); + } + run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; + // An object of a removed style of this name stays stale. + forget(h, doc.uid, para, std::slice::from_ref(&name)); + style_ref(h, doc.uid, para, &name) +} + +/// `removeAll()`: deletes every style but the Normal style, in one command. +fn list_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let gone: Vec = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect(); + if gone.is_empty() { + return Ok(Data::Undefined); + } + run(h, doc, para, "delete", &json!({"names": gone}))?; + forget(h, doc.uid, para, &gone); + Ok(Data::Undefined) +} + +fn doc_char_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)])) +} + +fn doc_para_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)])) +} + +fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer { + let r = this_range(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, list_class(para))) +} + +fn range_char_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, false) +} + +fn range_para_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, true) +} + +/// `document.characterStyles` and `document.paragraphStyles`. +pub(in crate::script) fn doc_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, doc_char_styles)), ("paragraphStyles", get(l, doc_para_styles))]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, range_char_styles)), ("paragraphStyles", get(l, range_para_styles))]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename)), + ("name", property(l, style_name_get, style_name_set)), + ("parent", get(l, style_parent)), + ("applyTo", method(l, style_apply_to)), + ("remove", method(l, style_remove)), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name)), + ("length", get(l, list_length)), + ("parent", get(l, list_parent)), + ("index", method(l, list_index)), + ("getByName", method(l, list_by_name)), + ("add", method(l, list_add)), + ("removeAll", method(l, list_remove_all)), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + paras.extend(para_members(l)); + vec![ + style(false), + style(true), + list(false), + list(true), + class("CharacterStyleAttributes", None, chars, None), + class("ParagraphStyleAttributes", None, paras, None), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..00d2c50167 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,6 +1317,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; + if r.is_ok() { + dom::after_command(host); + } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..572caa8cf2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_styles; mod script_text; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..085ecfbbb9 --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,331 @@ +//! Character and paragraph styles in the script object model. + +use serde_json::{Value, json}; +use vectorcraft_doc::{TextObject, TextStyleDef}; + +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::*; + +fn run(s: &mut Session, source: &str) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn text_of(s: &Session, id: NodeId) -> TextObject { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each run's text, style name, size and underline. +fn runs(s: &Session, id: NodeId) -> Vec<(String, Option, f64, bool)> { + text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect() +} + +fn char_names(s: &Session) -> Vec { + s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect() +} + +const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];"; + +#[test] +fn style_collections_list_the_normal_style_first_and_add_find_and_remove() { + let (mut s, _) = doc_with("Hello"); + let before = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\ + var b = cs.add('Body'); var p = ps.add('Lead');\ + vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\ + vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\ + cs.add('Other'); cs.removeAll(); ps.removeAll();\ + vc.log([cs.length, ps.length, cs[0].name]);" + ), + ); + assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"])); + assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"])); + assert_eq!(out[2], json!([2, "Lead", true])); + assert_eq!(out[3], json!([1, 1, NORMAL_CHAR])); + assert_eq!(undo_steps(&s), before + 1); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs.getByName('Nope');", "Not found"), + ("cs.index(4);", "Not found"), + ("cs.add('Body'); cs.add('Body');", "already exists"), + ("cs[0].remove();", "cannot be removed"), + ("ps[0].name = 'Mine';", "cannot be renamed"), + ("cs.getByName(5);", "string"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::::new())); +} + +/// Names are trimmed; an empty name, one past 256 characters and one with a control character +/// are refused with nothing changed. +#[test] +fn style_names_are_trimmed_and_checked() { + let (mut s, _) = doc_with("Hello"); + let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256))); + assert_eq!(out, [json!("Lead"), json!(256)]); + let undo = undo_steps(&s); + let long = "x".repeat(257); + for (src, says) in [ + ("cs.add(' ');".to_string(), "empty"), + (format!("cs.add('{long}');"), "256 characters"), + ("cs.add('a\\u0007b');".to_string(), "control characters"), + ("ps.add('tab\\there');".to_string(), "control characters"), + ("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"), + ("cs.add(5);".to_string(), "string"), + (format!("cs.getByName('{}');", "y".repeat(5000)), "too long"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + assert_eq!(char_names(&s).len(), 2); + // Path characters are kept as part of the name; a style name never names a file. + let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);")); + assert_eq!(out, [json!("../a/b\\c:*?")]); + assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?")); +} + +/// A style attribute that is not a finite number in range is refused with nothing changed. +#[test] +fn style_attributes_refuse_values_that_are_not_finite_or_in_range() { + let (mut s, _) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');")); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs[1].characterAttributes.size = NaN;", "finite number"), + ("cs[1].characterAttributes.size = Infinity;", "finite number"), + ("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"), + ("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"), + ("cs[1].characterAttributes.tracking = -1e9;", "tracking"), + ("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"), + ("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + let attrs = |s: &Session| { + s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::() + }; + assert_eq!(attrs(&s), 0); +} + +/// A style object follows its style through a rename made with it; after the style is removed, +/// with the object or with a command, every member throws, and a new style of that name does not +/// bring it back. +#[test] +fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { + let (mut s, id) = doc_with("Hello"); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\ + a.name = 'B'; vc.log(cs.length);" + ), + ); + assert_eq!(out, [json!(["B", "B", true]), json!(2)]); + assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B")); + for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] { + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;")); + assert!(e.contains("Stale style"), "{remove}: {e}"); + } + // A style removed and made again by commands is another style. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // A style renamed by a command is stale too, and its text keeps its look after a removal. + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); + assert!(e.contains("Stale style"), "{e}"); + let e = + failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;")); + assert!(e.contains("Stale style"), "{e}"); + let size = runs(&s, id)[0].2; + log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();")); + assert_eq!(runs(&s, id)[0].1, None); + assert_ne!(runs(&s, id)[0].2, size); + assert_eq!(runs(&s, id)[0].2, 40.0); +} + +/// A character style styles exactly the range; without clearing overrides the range keeps its +/// own underline, and with them it goes back to the Normal style first. +#[test] +fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { + let (mut s, id) = doc_with("Hello world"); + let before = undo_steps(&s); + log( + &mut s, + &format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"), + ); + assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);")); + assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false)); + // A whole frame, and an empty range, which changes nothing. + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);")); + assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); +} + +/// A paragraph style styles every paragraph the text touches, and only those. +#[test] +fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { + let (mut s, id) = doc_with("one\ntwo\nthree"); + let out = log( + &mut s, + &format!( + "{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\ + vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\ + a.justification = Justification.CENTER; a.spaceBefore = 6;\ + vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\ + vc.log(tf.paragraphs[1].paragraphAttributes.justification);" + ), + ); + assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]); + let t = text_of(&s, id); + let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect(); + assert_eq!(names, [None, Some("Centered".to_string()), None]); + assert_eq!(t.para_at(1).space_before, 6.0); + assert_eq!(t.para_at(2).space_before, 0.0); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';")); + assert!(e.contains("Justification"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;")); + assert!(e.contains("1296"), "{e}"); +} + +/// A style's character attributes read `undefined` until set; setting one restyles the text in +/// the style but not a value the text changed itself. +#[test] +fn style_attributes_redefine_the_text_in_the_style() { + let (mut s, id) = doc_with("ab cd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), a = x.characterAttributes;\ + vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\ + a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\ + vc.log([a.size, a.autoLeading, a.underline]);" + ), + ); + assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); + assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); + // Turning auto leading off keeps the leading auto leading gave the style's size. + let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + assert_eq!(out, [json!([false, 288])]); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); + assert!(e.contains("0.1 to 1296"), "{e}"); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';")); + assert!(e.contains("TextFont"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;")); + assert!(e.contains("not available yet"), "{e}"); +} + +/// A range lists each style its text uses once, in order, with the Normal style for unstyled +/// text, and its lists cannot add or remove styles. +#[test] +fn a_range_lists_the_styles_its_text_uses() { + let (mut s, _) = doc_with("aa bb cc\ndd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\ + ps.add('P').applyTo(tf.paragraphs[1]);\ + function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\ + vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\ + vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\ + vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\ + tf.textRange.characterStyles.parent.typename]);" + ), + ); + assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"])); + assert_eq!(out[1], json!(["X"])); + assert_eq!(out[2], json!([NORMAL_PARA, "P"])); + assert_eq!(out[3], json!([NORMAL_PARA])); + assert_eq!(out[4], json!([true, "X", "TextRange"])); + for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}"); + } +} + +/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another +/// document, and a range whose text changed, with nothing changed. +#[test] +fn apply_to_refuses_bad_arguments_with_nothing_changed() { + let (mut s, id) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X');")); + let runs_before = runs(&s, id); + for (src, says) in [ + ("cs[1].applyTo(5);".to_string(), "TextRange"), + ("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"), + ("cs[1].applyTo(cs);".to_string(), "TextRange"), + (format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"), + ( + "var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(), + "another document", + ), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(runs(&s, id), runs_before); +} + +/// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn a_run_names_at_most_4096_styles() { + let (mut s, _) = doc_with("Hello"); + let mut d = (*s.active().unwrap().doc).clone(); + let defs: Vec = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect(); + d.char_styles = defs.into(); + s.doc_mut().unwrap().doc = std::sync::Arc::new(d); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);")); + assert_eq!(out, [json!(false), json!(4101)]); + let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); + assert!(e.contains("4096 styles"), "{e}"); +} + +/// A script loads styles from a file only where it may read files; a file outside that is refused. +#[test] +fn a_script_loads_styles_only_from_a_file_it_may_read() { + let (mut s, _) = doc_with("Hello"); + let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Other.vectorcraft"); + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap(); + std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap(); + let p = path.to_string_lossy().replace('\\', "/"); + let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});")); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("access denied"), "{e}"); + assert!(char_names(&s).is_empty()); +} diff --git a/docs/mcp.md b/docs/mcp.md index b875fee563..801933b011 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2738,6 +2738,31 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and `orientation` cannot be set yet. +- `Document.characterStyles` and `Document.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, + https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`, + `index(key)`, `getByName(name)`, `add(name)` (`charStyle.new` or `paraStyle.new` with no attributes) and + `removeAll()` (`charStyle.delete` or `paraStyle.delete` of every style but the Normal style). A `CharacterStyle` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/) has `name` (`charStyle.rename`), `parent`, + `characterAttributes`, `applyTo(text, clearingOverrides?)` (`charStyle.apply`) and `remove()` (`charStyle.delete`); + a `ParagraphStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/) has the same members with + `paragraphAttributes` and the `paraStyle` commands. A style's attributes are those of a text range's + `characterAttributes` and `paragraphAttributes`, with the same ranges, and setting one runs `charStyle.setAttrs` or + `paraStyle.setAttrs`. `TextRange.characterStyles` and `TextRange.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) list the styles the range's text is in, with `length`, + `[i]`, `index(key)` and `getByName(name)`. A script loads styles from another document with `vc.run` and + `charStyle.load`, `paraStyle.load` or `textStyle.loadAll`, from a file the script may read. + VectorCraft's own rules: a document's list starts with `[Normal Character Style]` or `[Normal Paragraph Style]`, + followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. + An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the + style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the + style's document; a character style on an empty range changes nothing, and a paragraph style styles every + paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove + styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made + through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not + available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -13086,7 +13111,7 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..eedc6224f8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From a2063cea756b84dbefd454384ac569f4643785eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:55:21 -0800 Subject: [PATCH 2/9] Scripts: a style change that is put back keeps its style object A removal or rename whose result cannot reach the script is put back, and style objects now follow a command only once it is kept. A failed atomic object-model call puts style objects back with the documents. --- crates/engine/src/script/dom.rs | 17 +++++++--- crates/engine/src/script/dom/text/styles.rs | 35 +++++++++++++++++++++ crates/engine/src/script/mod.rs | 7 +++-- crates/engine/src/tests/script_styles.rs | 29 ++++++++++++++++- 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87a6310ec3..c02d65dfbd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -113,15 +113,22 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, + seen: Vec, +} + +/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored. +pub(in crate::script) fn mark(h: &Host) -> Mark { + let styles = &h.dom.text.styles; + let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect(); + Mark { slots, seen: styles.seen.borrow().clone() } +} + +/// Puts the style objects back as they were at `mark`, after the documents were put back to the +/// savepoint taken with it. A slot added since then stays live only while its document has the +/// style and no older live slot names it. +pub(in crate::script) fn put_back(h: &Host, mark: Mark) { + let styles = &h.dom.text.styles; + let mut slots = styles.slots.borrow_mut(); + let kept = mark.slots.len(); + for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) { + slot.name = name; + slot.live = live; + } + let s = h.session.borrow(); + for i in kept..slots.len() { + let (older, newer) = slots.split_at_mut(i); + let Some(slot) = newer.first_mut() else { break }; + let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + } + *styles.seen.borrow_mut() = mark.seen; +} + fn normal(para: bool) -> &'static str { if para { NORMAL_PARA } else { NORMAL_CHAR } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 00d2c50167..e537ab8ef7 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,9 +1317,6 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; - if r.is_ok() { - dom::after_command(host); - } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); @@ -1349,6 +1346,10 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_command(host); + } crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 085ecfbbb9..f30e66a7e6 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{TextObject, TextStyleDef}; use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::script::TEST_RESULT_BYTES; use crate::*; fn run(s: &mut Session, source: &str) -> Result { @@ -177,6 +178,29 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// A removal or rename whose result cannot cross to the script is put back, and the style's object +/// still names the style after it. +#[test] +fn a_style_change_that_is_put_back_keeps_the_style_object() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap(); + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\ + try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\ + try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\ + vc.log([a.name, a === cs.getByName('B'), cs.length]);" + ), + ); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}"); + assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s)); +} + /// A character style styles exactly the range; without clearing overrides the range keeps its /// own underline, and with them it goes back to the Normal style first. #[test] @@ -239,7 +263,10 @@ fn style_attributes_redefine_the_text_in_the_style() { assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); // Turning auto leading off keeps the leading auto leading gave the style's size. - let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + let out = log( + &mut s, + &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"), + ); assert_eq!(out, [json!([false, 288])]); let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); assert!(e.contains("0.1 to 1296"), "{e}"); From de11e1e7555d02e6cd2dc513ae6bbc8b6b2a46b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:47:00 -0800 Subject: [PATCH 3/9] Scripts: style objects made before File > Revert go stale A style object kept working after file.revert when the file read back held a style with the same name. Each style object now keeps the document's revert count, as text ranges do, and one made before a revert throws Stale style. The range style lists follow the per-paragraph entries of the text model, and the host name table lists the style classes. --- crates/engine/src/script/dom/text/styles.rs | 21 ++++++---- crates/engine/src/tests/script_styles.rs | 22 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 41 +++++++++++++++---- docs/mcp.md | 3 +- 4 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index adb71dd6cf..841d006ac6 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -12,8 +12,8 @@ //! panel lists them. //! - A style object names its style for the rest of the run, also after the script renames it //! through `name`. Once the style is removed, or renamed or removed other than through the object -//! model, or its document is closed, every member throws `Stale style`; a style added later under -//! the same name is another style. +//! model, or its document is closed or reverted with File › Revert, every member throws +//! `Stale style`; a style added later under the same name is another style. //! - A style name is trimmed, and must then be 1 to 256 characters long with no control //! characters. //! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the @@ -54,9 +54,11 @@ pub const MAX_STYLE_NAME: usize = 256; /// The most styles one run's style objects name. pub const MAX_HELD: usize = 4096; -/// A style that a run's style objects name: its document, its kind and its name now. +/// A style that a run's style objects name: its document and the document's revert count then, its +/// kind and its name now. struct Slot { uid: u64, + reverts: u64, para: bool, name: String, live: bool, @@ -91,7 +93,7 @@ pub(in crate::script) fn after_command(h: &Host) { seen.retain(|(uid, ..)| *uid != st.uid); seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { - slot.live = has_style(st, slot.para, &slot.name); + slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name); } } for slot in slots.iter_mut().filter(|x| x.live) { @@ -131,7 +133,7 @@ pub(in crate::script) fn put_back(h: &Host, mark: Mark) { let (older, newer) = slots.split_at_mut(i); let Some(slot) = newer.first_mut() else { break }; let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); - slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name)); } *styles.seen.borrow_mut() = mark.seen; } @@ -174,14 +176,15 @@ fn stale() -> HostError { /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); let mut slots = h.dom.text.styles.slots.borrow_mut(); - let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) { Some(i) => i, None => { if slots.len() >= MAX_HELD { return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); } - slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 } }; @@ -207,7 +210,7 @@ fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result let slot = usize_of(*slot).ok_or_else(stale)?; let mut slots = h.dom.text.styles.slots.borrow_mut(); let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; - if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) { s.live = false; return Err(stale()); } @@ -552,7 +555,7 @@ fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec = Vec::new(); diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index f30e66a7e6..759e41eae1 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -326,6 +326,28 @@ fn apply_to_refuses_bad_arguments_with_nothing_changed() { } /// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap(); + let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\ + var cs2 = app.activeDocument.characterStyles;\ + try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\ + vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);" + ), + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}"); + assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style"); + assert_eq!(out[2], json!(false)); +} + #[test] fn a_run_names_at_most_4096_styles() { let (mut s, _) = doc_with("Hello"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b23788236e..4e066e4831 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -96,10 +96,10 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "Document.prototype.", - "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ - groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ - rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= textFrames typename \ - views views= width", + "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols \ + symbols= textFrames typename views views= width", ), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name typename"), @@ -131,8 +131,9 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ( "", - "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ - TextOrientation TextRange TextType Words", + "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ + ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \ + TextFrames TextOrientation TextRange TextType Words", ), ("TextFrames.", "prototype"), ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), @@ -150,11 +151,11 @@ const INSIDE: &[(&str, &str)] = &[ ( "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ - characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ - paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ + paragraphStyles paragraphs parent remove rotation rotation= select select= size size= start start= \ story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), @@ -177,6 +178,30 @@ const INSIDE: &[(&str, &str)] = &[ "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", ), + ("CharacterStyles.", "prototype"), + ("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("CharacterStyle.", "prototype"), + ("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"), + ("CharacterStyleAttributes.", "prototype"), + ( + "CharacterStyleAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphStyles.", "prototype"), + ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("ParagraphStyle.", "prototype"), + ( + "ParagraphStyle.prototype.", + "applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename", + ), + ("ParagraphStyleAttributes.", "prototype"), + ( + "ParagraphStyleAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), ("TextFonts.", "prototype"), ("TextFonts.prototype.", "constructor getByName index length parent typename"), ("TextFont.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 801933b011..411ef4ba07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2760,7 +2760,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made - through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws + `Stale style`. One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From c7671c615b5df2ad0f607368fd36d06b8b36a6f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:02:47 -0800 Subject: [PATCH 4/9] Scripts: style objects see a style a batch removes and adds again - A style object goes stale when the steps of one `command.batch` remove its style and add another under the same name, as it does when separate `vc.run` calls do. The session notes each batch step's style lists while a script runs, and the style objects check each of them. - `add(name)` with all 4,096 style slots of the run taken throws before it adds the style; with one slot left it adds it. - `typename` of a removed style's `characterAttributes` or `paragraphAttributes` throws `Stale style`, as its other members do. - The style load commands refuse `data` over 64 MB without copying it. - docs/mcp.md states the 64 MB limit for `data` and decoded `dataBase64`; docs/gaps.md G6 and the docs/roadmap.md M13 row list the script text and style members. --- crates/engine/src/cmd/textstyles.rs | 8 ++--- crates/engine/src/cmd/textstyles/tests.rs | 3 ++ crates/engine/src/lib.rs | 4 +++ crates/engine/src/script/dom/text/styles.rs | 37 ++++++++++++++++++--- crates/engine/src/script/mod.rs | 22 ++++++++++++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/execute.rs | 3 ++ crates/engine/src/tests/script_styles.rs | 21 ++++++++++++ docs/gaps.md | 2 +- docs/mcp.md | 3 +- docs/roadmap.md | 2 +- 11 files changed, 94 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 3b57c2e067..3b64929cc2 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -1270,11 +1270,11 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { }; let path = str_param(p, "path"); let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, - (None, Some(text), _) => text.as_bytes().to_vec(), + let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(), + (None, Some(text), _) => text.as_bytes().into(), (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(), _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; if bytes.len() > MAX_LOAD_BYTES { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 1f8511d7ac..f2d2354000 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -845,6 +845,9 @@ fn loading_refuses_a_file_larger_than_64_mb() { let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let text = " ".repeat(MAX_LOAD_BYTES + 1); + let r = s.execute("textStyle.loadAll", &json!({"data": text})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); assert_eq!(s.doc().unwrap().doc, before); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..335c83eebb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,6 +309,10 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// The style lists each step of a batch a script runs left in a document whose lists it + /// changed: its uid, revert count, and character and paragraph style lists + /// ([`script::note_style_lists`]). + pub(crate) script_style_trail: Vec, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 841d006ac6..2b40d92bcd 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -75,13 +75,20 @@ pub(super) struct StyleState { } /// Marks stale each style object whose style the command just run removed or renamed, so a style -/// removed and made again under its name by later commands is another style. A document whose -/// style lists did not change is not checked again. +/// removed and made again under its name by later commands, or by later steps of the same batch, +/// is another style. A document whose style lists did not change is not checked again. pub(in crate::script) fn after_command(h: &Host) { + let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } + for (uid, reverts, c, p) in &trail { + for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { + let list = if slot.para { p } else { c }; + slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + } + } let s = h.session.borrow(); let mut seen = h.dom.text.styles.seen.borrow_mut(); seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); @@ -173,6 +180,10 @@ fn stale() -> HostError { HostError::Error(STALE_STYLE.into()) } +fn held_too_many() -> HostError { + HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")) +} + /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { @@ -182,7 +193,7 @@ fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { Some(i) => i, None => { if slots.len() >= MAX_HELD { - return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + return Err(held_too_many()); } slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 @@ -416,6 +427,18 @@ fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { } } +/// The `typename` of a style's `characterAttributes`, which throws once the style is gone. +fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, false)?; + Ok(text("CharacterAttributes")) +} + +/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone. +fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, true)?; + Ok(text("ParagraphAttributes")) +} + fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { let (_, m) = attrs_of(h, a, false)?; Ok(char_value(h, attr, &m)) @@ -651,6 +674,10 @@ fn list_add(h: &Host, a: &[Data]) -> Answer { if with_doc(h, doc, |_, st| has_style(st, para, &name)) { return Err(HostError::Error(format!("a style named {name} already exists"))); } + // The new style needs a slot of its own: a run that names as many styles as it may adds none. + if h.dom.text.styles.slots.borrow().len() >= MAX_HELD { + return Err(held_too_many()); + } run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; // An object of a removed style of this name stays stale. forget(h, doc.uid, para, std::slice::from_ref(&name)); @@ -738,9 +765,9 @@ pub(super) fn classes(l: &Link) -> Vec { Some(function(l, list_at)), ) }; - let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + let mut chars = named(vec![("typename", get(l, attrs_typename_char))]); chars.extend(char_members(l)); - let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + let mut paras = named(vec![("typename", get(l, attrs_typename_para))]); paras.extend(para_members(l)); vec![ style(false), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e537ab8ef7..18e24f1c36 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,6 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); + s.script_style_trail.clear(); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1353,6 +1354,27 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( crossed.map(|data| (data, value)) } +/// A document's uid, revert count, and character and paragraph style lists. +pub(crate) type StyleLists = + (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); + +/// After a step of a batch a script runs: notes the style lists of each document whose lists or +/// revert count the step changed, so the style objects see a style the batch removed and made +/// again under its name as another style ([`dom::after_command`]). +pub(crate) fn note_style_lists(s: &mut Session) { + for st in &s.docs { + let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); + let same = last.is_some_and(|(_, reverts, c, p)| { + *reverts == st.reverts + && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) + && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) + }); + if !same { + s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + } + } +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..52852308e3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,6 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), + script_style_trail: Vec::new(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..f0eabe06dd 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -84,6 +84,9 @@ impl Session { self.execute_spec(spec, id, params) }; self.reading = outer; + if self.script_in_run && self.depth > 0 && r.is_ok() { + crate::script::note_style_lists(self); + } r } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 759e41eae1..860aecfa81 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -165,6 +165,19 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // So is a style removed and made again by the steps of one batch. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \ + {{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // The attributes object of a removed style throws for its typename too. + let e = + failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); + assert!(e.contains("Stale style"), "{e}"); // A style renamed by a command is stale too, and its text keeps its look after a removal. let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); assert!(e.contains("Stale style"), "{e}"); @@ -359,6 +372,14 @@ fn a_run_names_at_most_4096_styles() { assert_eq!(out, [json!(false), json!(4101)]); let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); assert!(e.contains("4096 styles"), "{e}"); + // `add` with every slot taken adds no style; with one slot left it adds the style. + let out = log( + &mut s, + &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"), + ); + assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);")); + assert_eq!(out, [json!("New"), json!(4102)]); } /// A script loads styles from a file only where it may read files; a file outside that is refused. diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..561946b6d0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames with their text ranges and - character and paragraph attributes, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, its character and paragraph styles, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 411ef4ba07..0495483d8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13112,7 +13112,8 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The 64 MB limit also applies to `data` and to the +decoded bytes of `dataBase64`; a `dataBase64` string too long to decode to 64 MB or less is refused before it is decoded. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..99e740189c 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -196,7 +196,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | | M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | -| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 | +| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, and the installed fonts; the rest of the script document model (layers, artboards, paths, stories and threads of type, and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | From 997375be0d2190f956d304d8452f7ea4b9e2daf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:27:14 -0800 Subject: [PATCH 5/9] Scripts: a batch keeps one copy of the style lists for its style objects While a script runs a `command.batch`, the session kept the style lists of every step that changed them, so each such step also made the next edit copy the whole list. The session now keeps one copy of each open document's lists, as the last step left them, and records the names of the styles a step removed or renamed and the documents a step reverted. The style objects check those names, so a style that a batch removes and makes again, or renames and names back, is still a different style. --- crates/engine/src/lib.rs | 7 +- crates/engine/src/script/dom/text/styles.rs | 13 ++-- crates/engine/src/script/mod.rs | 73 ++++++++++++++++----- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/tests/script_styles.rs | 23 +++++++ 5 files changed, 93 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 335c83eebb..0cffcac358 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,10 +309,9 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, - /// The style lists each step of a batch a script runs left in a document whose lists it - /// changed: its uid, revert count, and character and paragraph style lists - /// ([`script::note_style_lists`]). - pub(crate) script_style_trail: Vec, + /// The styles the steps of a batch a script runs removed or renamed and the documents they + /// reverted ([`script::note_style_lists`]). + pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 2b40d92bcd..fd896918a9 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -76,17 +76,20 @@ pub(super) struct StyleState { /// Marks stale each style object whose style the command just run removed or renamed, so a style /// removed and made again under its name by later commands, or by later steps of the same batch, -/// is another style. A document whose style lists did not change is not checked again. +/// is another style. A document whose style lists did not change is not checked again. A live +/// slot's style was in its document's list when the command started, so a step that removed or +/// renamed it is in the trail's removed names. pub(in crate::script) fn after_command(h: &Host) { let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } - for (uid, reverts, c, p) in &trail { - for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { - let list = if slot.para { p } else { c }; - slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + for slot in slots.iter_mut().filter(|x| x.live) { + if trail.reverted.contains(&slot.uid) + || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone()))) + { + slot.live = false; } } let s = h.session.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 18e24f1c36..e89bf94c06 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,7 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); - s.script_style_trail.clear(); + s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1274,6 +1274,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { + s.script_style_trail = StyleTrail::default(); if let Some(save) = save && !save.restore(s) { @@ -1350,6 +1351,8 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( // Style objects follow only a command that is kept. if crossed.is_ok() { dom::after_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); } crossed.map(|data| (data, value)) } @@ -1358,23 +1361,63 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( pub(crate) type StyleLists = (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); -/// After a step of a batch a script runs: notes the style lists of each document whose lists or -/// revert count the step changed, so the style objects see a style the batch removed and made -/// again under its name as another style ([`dom::after_command`]). -pub(crate) fn note_style_lists(s: &mut Session) { - for st in &s.docs { - let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); - let same = last.is_some_and(|(_, reverts, c, p)| { - *reverts == st.reverts - && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) - && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) - }); - if !same { - s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); - } +/// What the steps of a command a script runs did to the documents' style lists +/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step +/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the +/// documents a step reverted. +#[derive(Default)] +pub(crate) struct StyleTrail { + lists: Vec, + pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, + pub(crate) reverted: Vec, +} + +impl StyleTrail { + /// A trail that starts from the documents' style lists now. + fn start(s: &Session) -> Self { + let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); + StyleTrail { lists, ..Default::default() } } } +/// After a step of a batch a script runs: notes the styles the step removed or renamed and the +/// documents it reverted, so the style objects see a style the batch removed and made again under +/// its name as another style ([`dom::after_command`]). The trail keeps one copy of each open +/// document's lists, however many steps change them. +pub(crate) fn note_style_lists(s: &mut Session) { + let trail = &mut s.script_style_trail; + trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); + let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else { + trail.lists.push((st.uid, st.reverts, c.clone(), p.clone())); + continue; + }; + if last.1 != st.reverts { + if !trail.reverted.contains(&st.uid) { + trail.reverted.push(st.uid); + } + } else { + for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] { + if vectorcraft_doc::Shared::ptr_eq(old, new) { + continue; + } + let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect(); + for d in old.iter().filter(|d| !names.contains(d.name.as_str())) { + trail.gone.insert((st.uid, para, d.name.clone())); + } + } + } + *last = (st.uid, st.reverts, c.clone(), p.clone()); + } +} + +/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). +#[cfg(test)] +pub(crate) fn retained_style_lists(s: &Session) -> usize { + s.script_style_trail.lists.len() +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 52852308e3..c448541a23 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,7 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), - script_style_trail: Vec::new(), + script_style_trail: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 860aecfa81..12bded346f 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -174,6 +174,15 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // And a style a batch renames and then names back. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \ + {{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); // The attributes object of a removed style throws for its typename too. let e = failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); @@ -191,6 +200,20 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// The steps of one batch a script runs keep one copy of a document's style lists, however many of +/// them change the lists. +#[test] +fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() { + let (mut s, _) = doc_with("Hello"); + let commands: Vec = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect(); + s.script_in_run = true; + let r = s.execute("command.batch", &json!({"commands": commands})); + s.script_in_run = false; + r.unwrap(); + assert_eq!(char_names(&s).len(), 20); + assert_eq!(crate::script::retained_style_lists(&s), 1); +} + /// A removal or rename whose result cannot cross to the script is put back, and the style's object /// still names the style after it. #[test] From 8e23d74985eb178d8a43f79c3fe73f252580e54b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:20 -0800 Subject: [PATCH 6/9] Scripts: textFrames.removeAll() refuses type on a locked artboard textFrames.removeAll() now stops with the same error as pageItems.removeAll() and PageItem.remove() when a type object sits on a locked artboard, and deletes nothing. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/text.rs | 13 ++++++++++--- crates/engine/src/tests/script_dom.rs | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c02d65dfbd..b1dab0816e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1561,7 +1561,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// 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"; +pub(super) 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/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0366dec5dd..e1386310d3 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1215,19 +1215,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(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 type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..35baf42e88 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}"); + assert!(s.active().unwrap().doc.node(t).is_some()); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From 9c636b9036c2b9cce38da4a0d96d37a763776d92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 7/9] Scripts: a character style applied to an empty frame styles text set later CharacterStyle.applyTo returned early on any empty range, so on an empty text frame it never reached charStyle.apply, which restyles the stored runs of empty text. It now passes an empty frame through and keeps the no-op only for an empty range inside text. --- crates/engine/src/script/dom/text/styles.rs | 3 ++- crates/engine/src/tests/script_styles.rs | 10 ++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index fd896918a9..87bfde4f27 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -359,7 +359,8 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let (_, ba, bb) = para_range(&index, s, e); (ba, bb) } else { - if s == e { + // An empty range inside text changes nothing; empty text takes the style on its runs. + if s == e && index.len() > 0 { return Ok(Data::Undefined); } (index.byte(s, false), index.byte(e, true)) diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 12bded346f..df96906aec 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -256,6 +256,16 @@ fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); } +/// A character style applied to an empty frame styles the text set in it later. +#[test] +fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() { + for target in ["tf", "tf.textRange"] { + let (mut s, id) = doc_with(""); + log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';")); + assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}"); + } +} + /// A paragraph style styles every paragraph the text touches, and only those. #[test] fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { diff --git a/docs/mcp.md b/docs/mcp.md index 0495483d8e..b302b7ee18 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,8 +2756,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the - style's document; a character style on an empty range changes nothing, and a paragraph style styles every - paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + style's document; a character style on an empty range inside text changes nothing, on empty text it styles the + text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left + out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws From d261130741b46e71eed594bb95eb23edbac6fb14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 8/9] i18n: translate the 64 MB style file limit in every complete catalog The error for a styles file over the load limit reads "the file is larger than 64 MB". Most complete catalogs translate it through their `the file is larger than {_1} MB` row; ca, el, fi, id and vi have no such row, so each gets an exact row next to its 1 MB one. A test checks the message in every complete-message language. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 1 + 6 files changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..635746fe75 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7549,6 +7549,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg the file holds no preferences el fitxer no conté cap preferència @msg `{key}` names a folder, which preferences files leave out `{key}` indica una carpeta, i els fitxers de preferències no inclouen carpetes @msg the file is larger than 1 MB el fitxer ocupa més d’1 MB +@msg the file is larger than 64 MB el fitxer ocupa més de 64 MB @msg give `path` or `data` indiqueu `path` o `data` @msg `{key}` must be an object `{key}` ha de ser un objecte @msg `prefs.import` runs on its own, not as a batch step `prefs.import` s’executa sol, no com a pas d’un lot diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e2f3ebce06 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5729,6 +5729,7 @@ digits Malayalam Μαλαγιάλαμ @msg the file holds no preferences το αρχείο δεν περιέχει προτιμήσεις @msg `{key}` names a folder, which preferences files leave out το `{key}` ορίζει φάκελο, και τα αρχεία προτιμήσεων δεν περιέχουν φακέλους @msg the file is larger than 1 MB το αρχείο είναι μεγαλύτερο από 1 MB +@msg the file is larger than 64 MB το αρχείο είναι μεγαλύτερο από 64 MB @msg give `path` or `data` δώστε `path` ή `data` @msg `{key}` must be an object το `{key}` πρέπει να είναι αντικείμενο @msg `prefs.import` runs on its own, not as a batch step το `prefs.import` εκτελείται μόνο του, όχι ως βήμα δέσμης diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d791677d24 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6012,6 +6012,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the file holds no preferences tiedostossa ei ole asetuksia @msg `{key}` names a folder, which preferences files leave out `{key}` nimeää kansion, eikä asetustiedostoissa ole kansioita @msg the file is larger than 1 MB tiedosto on suurempi kuin 1 Mt +@msg the file is larger than 64 MB tiedosto on suurempi kuin 64 Mt @msg give `path` or `data` anna `path` tai `data` @msg `{key}` must be an object `{key}` on oltava objekti @msg `prefs.import` runs on its own, not as a batch step `prefs.import` ajetaan yksinään, ei erän vaiheena diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ed4341007e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6090,6 +6090,7 @@ imageTrace Outline Kontur @msg the file holds no preferences file tidak berisi preferensi @msg `{key}` names a folder, which preferences files leave out `{key}` menunjuk folder, dan file preferensi tidak menyertakan folder @msg the file is larger than 1 MB file lebih besar dari 1 MB +@msg the file is larger than 64 MB berkas lebih besar dari 64 MB @msg give `path` or `data` berikan `path` atau `data` @msg `{key}` must be an object `{key}` harus berupa objek @msg `prefs.import` runs on its own, not as a batch step `prefs.import` dijalankan sendiri, bukan sebagai langkah batch diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..fb428adbd9 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3860,6 +3860,20 @@ fn warped_type_note_is_translated() { } } +/// The error for a character or paragraph styles file over the 64 MB load limit is translated in +/// every complete catalog, through an exact row or the `the file is larger than {_1} MB` template. +#[test] +fn styles_file_size_limit_is_translated() { + assert_eq!(vectorcraft_engine::cmd::textstyles::MAX_LOAD_BYTES, 64 << 20); + let error = "the file is larger than 64 MB"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// The notes a CDR import adds to its warnings are translated in every complete catalog. /// They are constants, which the scan of message literals doesn't see. #[test] diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..d58bfa4bc4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6461,6 +6461,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg the file holds no preferences tệp không chứa tùy chọn nào @msg `{key}` names a folder, which preferences files leave out `{key}` chỉ định một thư mục, và tệp tùy chọn không chứa thư mục @msg the file is larger than 1 MB tệp lớn hơn 1 MB +@msg the file is larger than 64 MB tệp lớn hơn 64 MB @msg give `path` or `data` hãy cung cấp `path` hoặc `data` @msg `{key}` must be an object `{key}` phải là một đối tượng @msg `prefs.import` runs on its own, not as a batch step `prefs.import` chạy riêng, không phải là một bước trong lô From ecc4d9cd7489ee58078dafe310bbb264148943ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:04:35 -0800 Subject: [PATCH 9/9] Tests: text frame tests index page items topmost first pageItems and textFrames now list the topmost object first, so the tests pick the rectangle and the open path by their new indices. --- crates/engine/src/tests/script_text.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 36dff46fa0..f22853d4e7 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,8 +56,8 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ @@ -67,7 +67,7 @@ fn text_frames_add_point_area_and_path_type() { ); assert_eq!(out[0], json!(4)); assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); - assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("Area"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); assert_eq!(undo_steps(&s), before + 1); // A path of another kind, or no path, is refused. assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); @@ -476,7 +476,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}");