diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d9c575eeae..47eccccba9 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!( @@ -1222,12 +1225,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, - (None, Some(text), _) => text.as_bytes().to_vec(), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); + 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"))?.into(), _ => 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 2939657c55..fffd80f2c5 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -896,6 +896,27 @@ 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:?}"); + 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); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap, stroke width or /// miter limit, tracking, kerning or rotation is out of the range `charStyle.new` takes is skipped. #[test] diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 46e6c04343..2cdb0f6239 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -373,6 +373,9 @@ pub struct Session { pub(crate) startup_failures: Vec<(String, String)>, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// 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, /// The desktop app supplies each window by (document uid, runtime window identity) while a diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 168f033166..7c50925bf0 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -196,19 +196,24 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_kept_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)) @@ -2318,7 +2328,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"; @@ -2746,6 +2756,7 @@ fn classes(link: &Link) -> Vec { ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); + document.extend(text::styles::doc_members(l)); document.extend( ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 8d15f1b19e..998652b81c 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -50,6 +50,7 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod styles; pub(super) mod threads; /// The error of a text range, or of a collection of one, whose frame's text changed other than @@ -201,6 +202,8 @@ pub(in crate::script) struct TextState { made: Cell, /// The span of each range object, by its number, whose `length` the script set. resized: RefCell>, + /// The styles the run's style objects name. + styles: styles::StyleState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1680,14 +1683,13 @@ pub(super) fn classes(l: &Link) -> Vec { range.extend(attr_members(l)); range.push(threads::range_member(l)); range.extend(para_members(l)); + range.extend(styles::range_members(l)); range.extend( [ "lines", "insertionPoints", "textRanges", "kerning", - "characterStyles", - "paragraphStyles", "textSelection", "changeCaseTo", "select", @@ -1786,6 +1788,7 @@ pub(super) fn classes(l: &Link) -> Vec { None, ), ]; + out.extend(styles::classes(l)); out.extend(stories); out } 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..8317e1ae04 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,802 @@ +//! 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 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 +//! 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, MemberInfo, 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}; +use crate::script::dom::{Described, returns, typed}; + +/// 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 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, +} + +/// 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, or by later steps of the same batch, +/// 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 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(); + 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 = slot.reverts == st.reverts && 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; + } + } +} + +/// The style objects' state when a savepoint was taken: each slot's name and whether it was +/// live, and the style lists last checked. +pub(in crate::script) struct Mark { + slots: Vec<(String, bool)>, + 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 && st.reverts == slot.reverts && 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 } +} + +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()) +} + +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 { + 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.reverts == reverts && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(held_too_many()); + } + slots.push(Slot { uid, reverts, 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| st.reverts == s.reverts && 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 { + // 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)) + }; + 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, + }, + } +} + +/// 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)) +} + +/// 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 { + ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = match attr { + Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean", + Attr::TextFont => "TextFont", + _ => "number", + }; + (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)), typed(data_type)) + }) + .collect() +} + +fn para_members(link: &Link) -> Vec { + PARA_ATTRS + .iter() + .map(|&(name, attr)| { + let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" }; + (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)), typed(data_type)) + }) + .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), false)?.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"))); + } + // 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)); + 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 { + named(vec![ + ("characterStyles", get(l, doc_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, doc_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec { + named(vec![ + ("characterStyles", get(l, range_char_styles), MemberInfo { collection: true, ..typed("CharacterStyles") }), + ("paragraphStyles", get(l, range_para_styles), MemberInfo { collection: true, ..typed("ParagraphStyles") }), + ]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename), typed("string")), + ("name", property(l, style_name_get, style_name_set), typed("string")), + ("parent", get(l, style_parent), typed("Document")), + ("applyTo", method(l, style_apply_to), returns("undefined", &[("textItem", "*"), ("clearingOverrides", "boolean")])), + ("remove", method(l, style_remove), returns("undefined", &[])), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes), typed("ParagraphStyleAttributes"))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes), typed("CharacterStyleAttributes"))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + let item = style_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name), typed("string")), + ("length", get(l, list_length), typed("number")), + ("parent", get(l, list_parent), typed("*")), + ("index", method(l, list_index), returns(item, &[("itemKey", "*")])), + ("getByName", method(l, list_by_name), returns(item, &[("name", "string")])), + ("add", method(l, list_add), returns(item, &[("name", "string")])), + ("removeAll", method(l, list_remove_all), returns("undefined", &[])), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", get(l, attrs_typename_char), typed("string"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", get(l, attrs_typename_para), typed("string"))]); + 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 19ee454c87..5fd8e0b88b 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1295,6 +1295,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 = 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)); @@ -1342,6 +1343,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) { @@ -1420,9 +1422,76 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( } } dom::after_command(host, before); + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_kept_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); + } 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>); + +/// 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_kept_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 258468641d..9c65271161 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -189,6 +189,7 @@ impl Session { startup_loading: None, startup_failures: vec![], script_high_water: Default::default(), + script_style_trail: Default::default(), script_in_run: false, window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 8b8bef8679..eec49be0c7 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -129,6 +129,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.rs b/crates/engine/src/tests.rs index 4b9cf973a9..cd5a7634e9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -186,6 +186,7 @@ mod script_include; mod script_io; mod script_run; mod script_scriptui; +mod script_styles; mod script_tags; mod script_text; mod script_threads; diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 330b3f4d4d..94886530c1 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -1767,6 +1767,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 move_and_duplicate_refuse_art_on_a_locked_artboard() { let (mut s, a, b) = doc(); diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..df96906aec --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,434 @@ +//! 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::script::TEST_RESULT_BYTES; +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}"); + // 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}"); + // 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;")); + 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); +} + +/// 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] +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] +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 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() { + 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 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"); + 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}"); + // `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. +#[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/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 0eeae87282..d7f60e5b2c 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -106,10 +106,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= stories swatches swatches= symbols symbols= tags textFrames toString \ - typename 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= stories swatches swatches= \ + symbols symbols= tags textFrames toString typename views width", ), ("Views.", "prototype"), ("Views.prototype.", "constructor index length parent toString typename"), @@ -155,8 +155,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"), @@ -174,11 +175,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= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \ getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \ horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \ - leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \ + leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \ paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \ spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \ textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \ @@ -203,6 +204,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/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 6e6a6edccc..8bf8783adf 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -591,15 +591,7 @@ fn object_value_of(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> Js fn has_own_property(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || is_host_member_pk(interp, o, &k)?)) -} - -/// [`Interp::is_host_member`] for either kind of key: a Symbol never names a host member. -fn is_host_member_pk(interp: &Interp, o: ObjId, k: &crate::symbol::PropKey) -> JsResult { - match k { - crate::symbol::PropKey::Str(name) => interp.is_host_member(o, name), - crate::symbol::PropKey::Sym(_) => Ok(false), - } + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some() || interp.is_host_member_pk(o, &k)?)) } fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -618,7 +610,7 @@ fn is_prototype_of(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> fn property_is_enumerable(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let k = interp.to_prop_key(&arg(args, 0))?; let o = interp.to_object(&this)?; - Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || is_host_member_pk(interp, o, &k)?)) + Ok(Value::Bool(interp.get_own_pk(o, &k)?.is_some_and(|p| p.enumerable()) || interp.is_host_member_pk(o, &k)?)) } // ---- Function ---- diff --git a/crates/js/src/host_classes.rs b/crates/js/src/host_classes.rs index b9411e8e3a..d8b81fdcec 100644 --- a/crates/js/src/host_classes.rs +++ b/crates/js/src/host_classes.rs @@ -40,6 +40,7 @@ use std::rc::Rc; use crate::heap::{CONFIGURABLE, Class, ENUMERABLE, Func, Key, ObjId, Object, Prop, key}; use crate::host::ArgRead; use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; +use crate::symbol::PropKey; use crate::value::Value; use crate::{Data, HostError, HostFunction}; @@ -245,6 +246,22 @@ impl Interp { Ok(false) } + /// [`Self::is_host_member`] for a property key. A Symbol names no host member. + pub(crate) fn is_host_member_pk(&self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.is_host_member(id, name), + PropKey::Sym(_) => Ok(false), + } + } + + /// [`Self::has_property_indexed`] for a property key. A Symbol does not go to the indexer. + pub(crate) fn has_pk_indexed(&mut self, id: ObjId, k: &PropKey) -> JsResult { + match k { + PropKey::Str(name) => self.has_property_indexed(id, name), + PropKey::Sym(_) => self.has_pk(id, k), + } + } + /// The [`Data`] for the object of a host class `id`, or `None` when it is not one. pub(crate) fn host_ref_of(&self, id: ObjId) -> JsResult> { let Class::Host(h) = &self.object(id)?.class else { return Ok(None) }; diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index ffc58e64da..d39847789f 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -4191,11 +4191,7 @@ impl Interp { } let Value::Object(o) = b else { return Err(self.type_error("the right side of 'in' is not an object")) }; let k = self.to_prop_key(a)?; - match &k { - PropKey::Str(name) => self.has_property_indexed(*o, name), - PropKey::Sym(_) => self.has_pk(*o, &k), - } - .map(Value::Bool) + self.has_pk_indexed(*o, &k).map(Value::Bool) } } } diff --git a/docs/gaps.md b/docs/gaps.md index 51775cc460..1acbfa6149 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -849,8 +849,9 @@ 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 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, their links to each other and the stories they form, the installed fonts, and - each document's variables, data sets and variable libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + character and paragraph attributes, their links to each other and the stories they form, its character and + paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries. + 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 5e9523396d..45025fd452 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3061,6 +3061,33 @@ other files through `$`: string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `characterOffset` 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 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 + `Stale style`. + One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not + available yet. - Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a `TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end), @@ -14711,7 +14738,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. 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 158326df56..964050ddc1 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -206,7 +206,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) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 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, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles 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, the installed fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 | | M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; 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), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 81eaaa5b01..359d5cce6b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1115,8 +1115,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - 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: `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 (which can add text), 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. 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: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.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 (which can add text), 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. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.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`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/). `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.