mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Scripts: character and paragraph styles for scripts
document.characterStyles and document.paragraphStyles list a document's styles, the Normal style first, and add, find and remove them. Each CharacterStyle and ParagraphStyle has a name, its attributes, applyTo with clearingOverrides, and remove; setting an attribute redefines the style through charStyle.setAttrs or paraStyle.setAttrs. A text range's characterStyles and paragraphStyles list the styles its text is in. Style names are trimmed and must have 1 to 256 characters and no control characters, one run names at most 4,096 styles, and a style object throws Stale style once its style is removed or renamed by a command. ParagraphStyle.characterAttributes is not available yet. charStyle.load, paraStyle.load and textStyle.loadAll refuse a file larger than 64 MB without reading it in full.
This commit is contained in:
1 parent
1eba8d3ef5
commit
69448d0c23
10 files changed
+1121
-8
No files matched your search
@@ -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<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -1266,12 +1269,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result<Value> {
|
||||
_ => "textStyle.loadAll".to_string(),
|
||||
};
|
||||
let path = str_param(p, "path");
|
||||
let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20));
|
||||
let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) {
|
||||
(Some(path), ..) => super::fileio::read_file(path)?,
|
||||
(Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?,
|
||||
(None, Some(text), _) => text.as_bytes().to_vec(),
|
||||
(None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()),
|
||||
(None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?,
|
||||
_ => return Err(bad(c, "give `path`, `data` or `dataBase64`")),
|
||||
};
|
||||
if bytes.len() > MAX_LOAD_BYTES {
|
||||
return Err(too_large());
|
||||
}
|
||||
let file = str_param(p, "name").or(path).unwrap_or("Styles");
|
||||
let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?;
|
||||
if src.preview_only {
|
||||
|
||||
@@ -830,6 +830,24 @@ fn load_all_styles_loads_both_kinds_in_one_step() {
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit.
|
||||
#[test]
|
||||
fn loading_refuses_a_file_larger_than_64_mb() {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Big.vectorcraft");
|
||||
std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()}));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8);
|
||||
let r = s.execute("paraStyle.load", &json!({"dataBase64": b64}));
|
||||
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
}
|
||||
|
||||
/// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is
|
||||
/// out of the range `charStyle.new` takes is skipped.
|
||||
#[test]
|
||||
|
||||
@@ -581,6 +581,11 @@ fn on_doc<T>(
|
||||
Ok(v)
|
||||
}
|
||||
|
||||
/// Marks stale the style objects whose styles a command the run ran removed or renamed.
|
||||
pub(super) fn after_command(h: &Host) {
|
||||
text::styles::after_command(h);
|
||||
}
|
||||
|
||||
/// Runs `id` with `params` on the item's document, its selection kept.
|
||||
fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
|
||||
on_doc(h, item.doc.uid, true, |h| command(h, id, params))
|
||||
@@ -1868,6 +1873,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(),
|
||||
("textFrames", text::doc_text_frames(l)),
|
||||
("selection", property(l, doc_selection, doc_set_selection)),
|
||||
]);
|
||||
document.extend(text::styles::doc_members(l));
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
|
||||
@@ -44,6 +44,8 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod styles;
|
||||
|
||||
/// The error of a text range, or of a collection of one, whose frame's text changed other than
|
||||
/// through the object model.
|
||||
pub const STALE_RANGE: &str = "Stale text range";
|
||||
@@ -188,6 +190,8 @@ pub(in crate::script) struct TextState {
|
||||
/// The fonts `app.textFonts` lists, as family and style, read once a run; a font a character
|
||||
/// names that is not installed is added at the end.
|
||||
fonts: RefCell<Option<Vec<(String, String)>>>,
|
||||
/// The styles the run's style objects name.
|
||||
styles: styles::StyleState,
|
||||
}
|
||||
|
||||
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
|
||||
@@ -1504,6 +1508,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, range_remove)),
|
||||
]);
|
||||
range.extend(attr_members(l));
|
||||
range.extend(styles::range_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
@@ -1511,8 +1516,6 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
"textRanges",
|
||||
"story",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
@@ -1537,7 +1540,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
chars.extend(attr_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, para_attrs_typename))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
let mut out = vec![
|
||||
class("TextFrame", Some("PageItem"), frame, None),
|
||||
class("TextRange", None, range, None),
|
||||
part("Characters"),
|
||||
@@ -1586,7 +1589,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
]),
|
||||
None,
|
||||
),
|
||||
]
|
||||
];
|
||||
out.extend(styles::classes(l));
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,715 @@
|
||||
//! Character and paragraph styles in the script object model: `document.characterStyles` and
|
||||
//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text
|
||||
//! of a `TextRange` uses, as the help pages
|
||||
//! <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.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - A document's collection lists its Normal style first, then its other styles in the order the
|
||||
//! panel lists them.
|
||||
//! - A style object names its style for the rest of the run, also after the script renames it
|
||||
//! through `name`. Once the style is removed, or renamed or removed other than through the object
|
||||
//! model, or its document is closed, every member throws `Stale style`; a style added later under
|
||||
//! the same name is another style.
|
||||
//! - A style name is trimmed, and must then be 1 to 256 characters long with no control
|
||||
//! characters.
|
||||
//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the
|
||||
//! style does not set. Setting one redefines the style: text in the style takes the new value
|
||||
//! where it had the style's old one and keeps its other changes.
|
||||
//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words
|
||||
//! or paragraphs of one, in the style's document. A character style styles exactly that text and
|
||||
//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches.
|
||||
//! `clearingOverrides` left out is false; true resets the text to the Normal style first.
|
||||
//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or
|
||||
//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in
|
||||
//! no other style. They do not add or remove styles.
|
||||
//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its
|
||||
//! look and is in the Normal style after.
|
||||
//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`,
|
||||
//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef};
|
||||
use vectorcraft_geom::Point;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref};
|
||||
|
||||
use super::{
|
||||
ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref,
|
||||
function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text,
|
||||
text_of, this_range, typename_of, usize_of, whole_span, with_doc,
|
||||
};
|
||||
use crate::DocState;
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs};
|
||||
|
||||
/// The error of a style object whose style is gone.
|
||||
pub const STALE_STYLE: &str = "Stale style";
|
||||
/// The longest style name, in characters, after trimming.
|
||||
pub const MAX_STYLE_NAME: usize = 256;
|
||||
/// The most styles one run's style objects name.
|
||||
pub const MAX_HELD: usize = 4096;
|
||||
|
||||
/// A style that a run's style objects name: its document, its kind and its name now.
|
||||
struct Slot {
|
||||
uid: u64,
|
||||
para: bool,
|
||||
name: String,
|
||||
live: bool,
|
||||
}
|
||||
|
||||
/// A document's uid and its character and paragraph style lists when the slots were last checked.
|
||||
type Seen = (u64, Shared<Vec<TextStyleDef>>, Shared<Vec<TextStyleDef>>);
|
||||
|
||||
/// The styles a run's style objects name; an object holds its slot's number.
|
||||
#[derive(Default)]
|
||||
pub(super) struct StyleState {
|
||||
slots: RefCell<Vec<Slot>>,
|
||||
seen: RefCell<Vec<Seen>>,
|
||||
}
|
||||
|
||||
/// Marks stale each style object whose style the command just run removed or renamed, so a style
|
||||
/// removed and made again under its name by later commands is another style. A document whose
|
||||
/// style lists did not change is not checked again.
|
||||
pub(in crate::script) fn after_command(h: &Host) {
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
if !slots.iter().any(|s| s.live) {
|
||||
return;
|
||||
}
|
||||
let s = h.session.borrow();
|
||||
let mut seen = h.dom.text.styles.seen.borrow_mut();
|
||||
seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid));
|
||||
for st in s.documents() {
|
||||
let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles));
|
||||
if same {
|
||||
continue;
|
||||
}
|
||||
seen.retain(|(uid, ..)| *uid != st.uid);
|
||||
seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone()));
|
||||
for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) {
|
||||
slot.live = has_style(st, slot.para, &slot.name);
|
||||
}
|
||||
}
|
||||
for slot in slots.iter_mut().filter(|x| x.live) {
|
||||
if !s.documents().iter().any(|d| d.uid == slot.uid) {
|
||||
slot.live = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn normal(para: bool) -> &'static str {
|
||||
if para { NORMAL_PARA } else { NORMAL_CHAR }
|
||||
}
|
||||
|
||||
fn cmd(para: bool, verb: &str) -> String {
|
||||
format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" })
|
||||
}
|
||||
|
||||
fn style_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyle" } else { "CharacterStyle" }
|
||||
}
|
||||
|
||||
fn list_class(para: bool) -> &'static str {
|
||||
if para { "ParagraphStyles" } else { "CharacterStyles" }
|
||||
}
|
||||
|
||||
fn defs(st: &DocState, para: bool) -> &Vec<TextStyleDef> {
|
||||
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<String> {
|
||||
let mut out = vec![normal(para).to_string()];
|
||||
out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para)));
|
||||
out
|
||||
}
|
||||
|
||||
fn has_style(st: &DocState, para: bool, name: &str) -> bool {
|
||||
name == normal(para) || defs(st, para).iter().any(|d| d.name == name)
|
||||
}
|
||||
|
||||
fn stale() -> HostError {
|
||||
HostError::Error(STALE_STYLE.into())
|
||||
}
|
||||
|
||||
/// The style object for the style `name` of the document `uid`: the same slot as every other
|
||||
/// object naming it in this run.
|
||||
fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer {
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
if slots.len() >= MAX_HELD {
|
||||
return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")));
|
||||
}
|
||||
slots.push(Slot { uid, para, name: name.to_string(), live: true });
|
||||
slots.len() - 1
|
||||
}
|
||||
};
|
||||
Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)]))
|
||||
}
|
||||
|
||||
/// A style a style object names.
|
||||
struct Style {
|
||||
doc: Doc,
|
||||
para: bool,
|
||||
slot: usize,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The style `d` names, when it is an object of one of `classes` (with the kind each names).
|
||||
fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result<Style, HostError> {
|
||||
let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para)));
|
||||
let Some((handle, para)) = found else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0))));
|
||||
};
|
||||
let [run, uid, slot] = handle.as_slice() else { return Err(stale()) };
|
||||
let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?;
|
||||
let slot = usize_of(*slot).ok_or_else(stale)?;
|
||||
let mut slots = h.dom.text.styles.slots.borrow_mut();
|
||||
let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?;
|
||||
if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) {
|
||||
s.live = false;
|
||||
return Err(stale());
|
||||
}
|
||||
Ok(Style { doc, para, slot, name: s.name.clone() })
|
||||
}
|
||||
|
||||
fn this_style(h: &Host, a: &[Data]) -> std::result::Result<Style, HostError> {
|
||||
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<String, HostError> {
|
||||
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<Data, HostError> {
|
||||
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<Span, HostError> {
|
||||
if handle_of(d, "TextFrame").is_some() {
|
||||
return Ok(whole_span(h, item_of(h, d)?)?.1);
|
||||
}
|
||||
const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"];
|
||||
if !TEXT.iter().any(|c| handle_of(d, c).is_some()) {
|
||||
return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into()));
|
||||
}
|
||||
span_of(h, d, &TEXT)
|
||||
}
|
||||
|
||||
/// `applyTo(textItem, clearingOverrides?)`.
|
||||
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
|
||||
let style = this_style(h, a)?;
|
||||
let target = target_span(h, arg(a, 1))?;
|
||||
let clear = match arg(a, 2) {
|
||||
Data::Undefined => false,
|
||||
Data::Bool(b) => *b,
|
||||
_ => return Err(HostError::Type("clearingOverrides must be true or false".into())),
|
||||
};
|
||||
if target.item.doc.uid != style.doc.uid {
|
||||
return Err(HostError::Error("the text is in another document than the style".into()));
|
||||
}
|
||||
let (index, s, e, _) = resolve(h, target)?;
|
||||
h.charge_call(16 + (e - s) as u64)?;
|
||||
let (start, end) = if style.para {
|
||||
let (_, ba, bb) = para_range(&index, s, e);
|
||||
(ba, bb)
|
||||
} else {
|
||||
if s == e {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
(index.byte(s, false), index.byte(e, true))
|
||||
};
|
||||
let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end});
|
||||
run(h, style.doc, style.para, "apply", &p)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
// ---- the attributes of a style ----
|
||||
|
||||
/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets.
|
||||
const CHAR_KEYS: [(&str, &str); 11] = [
|
||||
("size", "size"),
|
||||
("leading", "leading"),
|
||||
("tracking", "tracking"),
|
||||
("baselineShift", "baseline_shift"),
|
||||
("hScale", "h_scale"),
|
||||
("vScale", "v_scale"),
|
||||
("rotation", "rotation"),
|
||||
("underline", "underline"),
|
||||
("strikethrough", "strikethrough"),
|
||||
("font", "font_family"),
|
||||
("style", "font_style"),
|
||||
];
|
||||
|
||||
/// The script's `Justification` members and the alignments a paragraph style stores.
|
||||
const JUSTIFY: [(&str, &str); 7] = [
|
||||
("LEFT", "Left"),
|
||||
("CENTER", "Center"),
|
||||
("RIGHT", "Right"),
|
||||
("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"),
|
||||
("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"),
|
||||
("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"),
|
||||
("FULLJUSTIFY", "JustifyAll"),
|
||||
];
|
||||
|
||||
/// The style an attributes object belongs to and the attributes it sets.
|
||||
fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map<String, Value>), 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<String, Value>) -> Data {
|
||||
let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num);
|
||||
let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool);
|
||||
match attr {
|
||||
Attr::Size => n("size"),
|
||||
Attr::Leading => n("leading"),
|
||||
Attr::AutoLeading => match m.get("leading") {
|
||||
Some(Value::Null) => Data::Bool(true),
|
||||
Some(v) if v.is_number() => Data::Bool(false),
|
||||
_ => Data::Undefined,
|
||||
},
|
||||
Attr::Tracking => n("tracking"),
|
||||
Attr::BaselineShift => n("baseline_shift"),
|
||||
Attr::HorizontalScale => n("h_scale"),
|
||||
Attr::VerticalScale => n("v_scale"),
|
||||
Attr::Rotation => n("rotation"),
|
||||
Attr::Underline => b("underline"),
|
||||
Attr::StrikeThrough => b("strikethrough"),
|
||||
Attr::TextFont => match m.get("font_family").and_then(Value::as_str) {
|
||||
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
|
||||
None => Data::Undefined,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer {
|
||||
let (_, m) = attrs_of(h, a, false)?;
|
||||
Ok(char_value(h, attr, &m))
|
||||
}
|
||||
|
||||
/// Redefines the style with `attrs`, unless they are what it has.
|
||||
fn redefine(h: &Host, style: &Style, old: &Map<String, Value>, attrs: Map<String, Value>) -> 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<dyn Fn(&Host, &[Data]) -> 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<Data>| {
|
||||
let h = super::super::current(&l)?;
|
||||
h.charge_call(16 + a.iter().map(super::super::data_size).sum::<u64>())?;
|
||||
f(&h, &a)
|
||||
})
|
||||
};
|
||||
HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) }
|
||||
}
|
||||
|
||||
fn char_members(link: &Link) -> Vec<(String, HostMember)> {
|
||||
ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn para_members(link: &Link) -> Vec<(String, HostMember)> {
|
||||
PARA_ATTRS
|
||||
.iter()
|
||||
.map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---- CharacterStyles and ParagraphStyles ----
|
||||
|
||||
/// What a collection of styles lists: a document's styles, or those a text range uses.
|
||||
enum Of {
|
||||
Doc(Doc),
|
||||
Range(Span),
|
||||
}
|
||||
|
||||
fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> {
|
||||
let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) {
|
||||
(Some(_), _) => false,
|
||||
(_, Some(_)) => true,
|
||||
_ => return Err(HostError::Type("this is not a CharacterStyles".into())),
|
||||
};
|
||||
let class = list_class(para);
|
||||
let len = handle_of(d, class).map_or(0, |v| v.len());
|
||||
Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para))
|
||||
}
|
||||
|
||||
/// The document and the names of the styles a collection lists.
|
||||
fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec<String>), 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<Option<String>> = if para {
|
||||
let (paras, _, _) = para_range(&index, s, e);
|
||||
paras.map(|i| t.para_at(i).style_name.clone()).collect()
|
||||
} else {
|
||||
styles_in(t, index.byte(s, false), index.byte(e, true))?.into_iter().map(|(c, _)| c.style_name).collect()
|
||||
};
|
||||
h.charge_call(used.len() as u64)?;
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for n in used {
|
||||
let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string());
|
||||
if !out.contains(&n) {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
if out.is_empty() {
|
||||
out.push(normal(para).to_string());
|
||||
}
|
||||
Ok::<_, HostError>(out)
|
||||
})?;
|
||||
Ok((r.item.doc, used))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
Ok(num(float(listed(h, &of, para)?.1.len() as u64)))
|
||||
}
|
||||
|
||||
fn list_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, _) = list_of(h, arg(a, 0))?;
|
||||
match of {
|
||||
Of::Doc(doc) => Ok(doc_ref(h, doc.uid)),
|
||||
Of::Range(r) => {
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, "TextRange"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn list_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let found = match &of {
|
||||
Of::Doc(doc) => with_doc(h, *doc, |_, st| match i {
|
||||
0 => Some(normal(para).to_string()),
|
||||
_ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(),
|
||||
})
|
||||
.map(|n| (*doc, n)),
|
||||
Of::Range(_) => {
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
names.get(i).cloned().map(|n| (doc, n))
|
||||
}
|
||||
};
|
||||
match found {
|
||||
Some((doc, name)) => style_ref(h, doc.uid, para, &name),
|
||||
None => Ok(Data::Undefined),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let (of, para) = list_of(h, arg(a, 0))?;
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let (doc, names) = listed(h, &of, para)?;
|
||||
match names.iter().find(|n| *n == name) {
|
||||
Some(n) => style_ref(h, doc.uid, para, n),
|
||||
None => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn list_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => list_by_name(h, a),
|
||||
Data::Number(_) => match list_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a document's collection; a range's collection cannot be changed.
|
||||
fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> {
|
||||
match list_of(h, arg(a, 0))? {
|
||||
(Of::Doc(doc), para) => Ok((doc, para)),
|
||||
(Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(name)`: a new style that sets no attributes.
|
||||
fn list_add(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let name = style_name(arg(a, 1))?;
|
||||
if with_doc(h, doc, |_, st| has_style(st, para, &name)) {
|
||||
return Err(HostError::Error(format!("a style named {name} already exists")));
|
||||
}
|
||||
run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?;
|
||||
// An object of a removed style of this name stays stale.
|
||||
forget(h, doc.uid, para, std::slice::from_ref(&name));
|
||||
style_ref(h, doc.uid, para, &name)
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every style but the Normal style, in one command.
|
||||
fn list_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, para) = changed_doc(h, a)?;
|
||||
let gone: Vec<String> = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect();
|
||||
if gone.is_empty() {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
run(h, doc, para, "delete", &json!({"names": gone}))?;
|
||||
forget(h, doc.uid, para, &gone);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn doc_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn doc_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer {
|
||||
let r = this_range(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(range_ref(h, r.item, s, e, stamp, list_class(para)))
|
||||
}
|
||||
|
||||
fn range_char_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, false)
|
||||
}
|
||||
|
||||
fn range_para_styles(h: &Host, a: &[Data]) -> Answer {
|
||||
range_styles(h, a, true)
|
||||
}
|
||||
|
||||
/// `document.characterStyles` and `document.paragraphStyles`.
|
||||
pub(in crate::script) fn doc_members(l: &Link) -> Vec<(String, HostMember)> {
|
||||
named(vec![("characterStyles", get(l, doc_char_styles)), ("paragraphStyles", get(l, doc_para_styles))])
|
||||
}
|
||||
|
||||
/// `TextRange.characterStyles` and `TextRange.paragraphStyles`.
|
||||
pub(super) fn range_members(l: &Link) -> Vec<(String, HostMember)> {
|
||||
named(vec![("characterStyles", get(l, range_char_styles)), ("paragraphStyles", get(l, range_para_styles))])
|
||||
}
|
||||
|
||||
/// The style classes.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let style = |para: bool| {
|
||||
let mut members = named(vec![
|
||||
("typename", get(l, style_typename)),
|
||||
("name", property(l, style_name_get, style_name_set)),
|
||||
("parent", get(l, style_parent)),
|
||||
("applyTo", method(l, style_apply_to)),
|
||||
("remove", method(l, style_remove)),
|
||||
]);
|
||||
if para {
|
||||
members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes)));
|
||||
members.push(super::super::later(l, "ParagraphStyle", "characterAttributes"));
|
||||
} else {
|
||||
members.push(("characterAttributes".into(), get(l, style_character_attributes)));
|
||||
}
|
||||
class(style_class(para), None, members, None)
|
||||
};
|
||||
let list = |para: bool| {
|
||||
let name = list_class(para);
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", typename_of(name)),
|
||||
("length", get(l, list_length)),
|
||||
("parent", get(l, list_parent)),
|
||||
("index", method(l, list_index)),
|
||||
("getByName", method(l, list_by_name)),
|
||||
("add", method(l, list_add)),
|
||||
("removeAll", method(l, list_remove_all)),
|
||||
]),
|
||||
Some(function(l, list_at)),
|
||||
)
|
||||
};
|
||||
let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]);
|
||||
chars.extend(char_members(l));
|
||||
let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
style(false),
|
||||
style(true),
|
||||
list(false),
|
||||
list(true),
|
||||
class("CharacterStyleAttributes", None, chars, None),
|
||||
class("ParagraphStyleAttributes", None, paras, None),
|
||||
]
|
||||
}
|
||||
@@ -1317,6 +1317,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<(
|
||||
let mut s = session.borrow_mut();
|
||||
step(&mut s, host, &id, ¶ms)
|
||||
};
|
||||
if r.is_ok() {
|
||||
dom::after_command(host);
|
||||
}
|
||||
// Only commands that exist are timed, so the table holds at most one row per command.
|
||||
if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) {
|
||||
let nanos = started.elapsed().as_nanos();
|
||||
|
||||
@@ -178,6 +178,7 @@ mod script_folder;
|
||||
mod script_include;
|
||||
mod script_io;
|
||||
mod script_run;
|
||||
mod script_styles;
|
||||
mod script_text;
|
||||
mod scripts;
|
||||
mod select_effects;
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
//! Character and paragraph styles in the script object model.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{TextObject, TextStyleDef};
|
||||
|
||||
use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA};
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
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<String>, 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<String> {
|
||||
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::<String>::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::<usize>()
|
||||
};
|
||||
assert_eq!(attrs(&s), 0);
|
||||
}
|
||||
|
||||
/// A style object follows its style through a rename made with it; after the style is removed,
|
||||
/// with the object or with a command, every member throws, and a new style of that name does not
|
||||
/// bring it back.
|
||||
#[test]
|
||||
fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\
|
||||
a.name = 'B'; vc.log(cs.length);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!(["B", "B", true]), json!(2)]);
|
||||
assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B"));
|
||||
for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] {
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{remove}: {e}");
|
||||
}
|
||||
// A style removed and made again by commands is another style.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;"
|
||||
),
|
||||
);
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
// A style renamed by a command is stale too, and its text keeps its look after a removal.
|
||||
let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let e =
|
||||
failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;"));
|
||||
assert!(e.contains("Stale style"), "{e}");
|
||||
let size = runs(&s, id)[0].2;
|
||||
log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();"));
|
||||
assert_eq!(runs(&s, id)[0].1, None);
|
||||
assert_ne!(runs(&s, id)[0].2, size);
|
||||
assert_eq!(runs(&s, id)[0].2, 40.0);
|
||||
}
|
||||
|
||||
/// A character style styles exactly the range; without clearing overrides the range keeps its
|
||||
/// own underline, and with them it goes back to the Normal style first.
|
||||
#[test]
|
||||
fn apply_to_styles_a_range_and_clearing_overrides_resets_it() {
|
||||
let (mut s, id) = doc_with("Hello world");
|
||||
let before = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
&format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"),
|
||||
);
|
||||
assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);"));
|
||||
assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false));
|
||||
// A whole frame, and an empty range, which changes nothing.
|
||||
log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);"));
|
||||
assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]);
|
||||
}
|
||||
|
||||
/// A paragraph style styles every paragraph the text touches, and only those.
|
||||
#[test]
|
||||
fn a_paragraph_style_styles_the_paragraphs_the_text_touches() {
|
||||
let (mut s, id) = doc_with("one\ntwo\nthree");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\
|
||||
vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\
|
||||
a.justification = Justification.CENTER; a.spaceBefore = 6;\
|
||||
vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\
|
||||
vc.log(tf.paragraphs[1].paragraphAttributes.justification);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]);
|
||||
let t = text_of(&s, id);
|
||||
let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect();
|
||||
assert_eq!(names, [None, Some("Centered".to_string()), None]);
|
||||
assert_eq!(t.para_at(1).space_before, 6.0);
|
||||
assert_eq!(t.para_at(2).space_before, 0.0);
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';"));
|
||||
assert!(e.contains("Justification"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;"));
|
||||
assert!(e.contains("1296"), "{e}");
|
||||
}
|
||||
|
||||
/// A style's character attributes read `undefined` until set; setting one restyles the text in
|
||||
/// the style but not a value the text changed itself.
|
||||
#[test]
|
||||
fn style_attributes_redefine_the_text_in_the_style() {
|
||||
let (mut s, id) = doc_with("ab cd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), a = x.characterAttributes;\
|
||||
vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\
|
||||
a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\
|
||||
vc.log([a.size, a.autoLeading, a.underline]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]);
|
||||
assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]);
|
||||
// Turning auto leading off keeps the leading auto leading gave the style's size.
|
||||
let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"));
|
||||
assert_eq!(out, [json!([false, 288])]);
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;"));
|
||||
assert!(e.contains("0.1 to 1296"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';"));
|
||||
assert!(e.contains("TextFont"), "{e}");
|
||||
let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;"));
|
||||
assert!(e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
/// A range lists each style its text uses once, in order, with the Normal style for unstyled
|
||||
/// text, and its lists cannot add or remove styles.
|
||||
#[test]
|
||||
fn a_range_lists_the_styles_its_text_uses() {
|
||||
let (mut s, _) = doc_with("aa bb cc\ndd");
|
||||
let out = log(
|
||||
&mut s,
|
||||
&format!(
|
||||
"{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\
|
||||
ps.add('P').applyTo(tf.paragraphs[1]);\
|
||||
function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\
|
||||
vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\
|
||||
vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\
|
||||
vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\
|
||||
tf.textRange.characterStyles.parent.typename]);"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"]));
|
||||
assert_eq!(out[1], json!(["X"]));
|
||||
assert_eq!(out[2], json!([NORMAL_PARA, "P"]));
|
||||
assert_eq!(out[3], json!([NORMAL_PARA]));
|
||||
assert_eq!(out[4], json!([true, "X", "TextRange"]));
|
||||
for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another
|
||||
/// document, and a range whose text changed, with nothing changed.
|
||||
#[test]
|
||||
fn apply_to_refuses_bad_arguments_with_nothing_changed() {
|
||||
let (mut s, id) = doc_with("Hello");
|
||||
log(&mut s, &format!("{DOC} cs.add('X');"));
|
||||
let runs_before = runs(&s, id);
|
||||
for (src, says) in [
|
||||
("cs[1].applyTo(5);".to_string(), "TextRange"),
|
||||
("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"),
|
||||
("cs[1].applyTo(cs);".to_string(), "TextRange"),
|
||||
(format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"),
|
||||
(
|
||||
"var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(),
|
||||
"another document",
|
||||
),
|
||||
] {
|
||||
assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}");
|
||||
}
|
||||
assert_eq!(runs(&s, id), runs_before);
|
||||
}
|
||||
|
||||
/// A run names at most 4,096 styles; reading past that throws instead of growing without bound.
|
||||
#[test]
|
||||
fn a_run_names_at_most_4096_styles() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let mut d = (*s.active().unwrap().doc).clone();
|
||||
let defs: Vec<TextStyleDef> = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect();
|
||||
d.char_styles = defs.into();
|
||||
s.doc_mut().unwrap().doc = std::sync::Arc::new(d);
|
||||
let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);"));
|
||||
assert_eq!(out, [json!(false), json!(4101)]);
|
||||
let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;"));
|
||||
assert!(e.contains("4096 styles"), "{e}");
|
||||
}
|
||||
|
||||
/// A script loads styles from a file only where it may read files; a file outside that is refused.
|
||||
#[test]
|
||||
fn a_script_loads_styles_only_from_a_file_it_may_read() {
|
||||
let (mut s, _) = doc_with("Hello");
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("Other.vectorcraft");
|
||||
let mut other = Session::new();
|
||||
other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap();
|
||||
std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap();
|
||||
let p = path.to_string_lossy().replace('\\', "/");
|
||||
let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});"));
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
assert!(e.contains("access denied"), "{e}");
|
||||
assert!(char_names(&s).is_empty());
|
||||
}
|
||||
+26
-1
@@ -2738,6 +2738,31 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
`Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and
|
||||
`TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and
|
||||
`orientation` cannot be set yet.
|
||||
- `Document.characterStyles` and `Document.paragraphStyles`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`,
|
||||
`index(key)`, `getByName(name)`, `add(name)` (`charStyle.new` or `paraStyle.new` with no attributes) and
|
||||
`removeAll()` (`charStyle.delete` or `paraStyle.delete` of every style but the Normal style). A `CharacterStyle`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/) has `name` (`charStyle.rename`), `parent`,
|
||||
`characterAttributes`, `applyTo(text, clearingOverrides?)` (`charStyle.apply`) and `remove()` (`charStyle.delete`);
|
||||
a `ParagraphStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/) has the same members with
|
||||
`paragraphAttributes` and the `paraStyle` commands. A style's attributes are those of a text range's
|
||||
`characterAttributes` and `paragraphAttributes`, with the same ranges, and setting one runs `charStyle.setAttrs` or
|
||||
`paraStyle.setAttrs`. `TextRange.characterStyles` and `TextRange.paragraphStyles`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) list the styles the range's text is in, with `length`,
|
||||
`[i]`, `index(key)` and `getByName(name)`. A script loads styles from another document with `vc.run` and
|
||||
`charStyle.load`, `paraStyle.load` or `textStyle.loadAll`, from a file the script may read.
|
||||
VectorCraft's own rules: a document's list starts with `[Normal Character Style]` or `[Normal Paragraph Style]`,
|
||||
followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters.
|
||||
An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the
|
||||
style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the
|
||||
style's document; a character style on an empty range changes nothing, and a paragraph style styles every
|
||||
paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order
|
||||
its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove
|
||||
styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made
|
||||
through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`.
|
||||
One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not
|
||||
available yet.
|
||||
- `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
|
||||
@@ -13086,7 +13111,7 @@ uses, in panel order and never the Normal style, and the panel highlights them;
|
||||
(Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and
|
||||
`ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data`
|
||||
or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo
|
||||
step. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of
|
||||
step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of
|
||||
either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color
|
||||
is the document's. A loaded style that is the same as the style of
|
||||
its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The
|
||||
|
||||
@@ -1025,7 +1025,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
|
||||
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
|
||||
Reference in new issue
Block a user