mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Scripts: text ranges take a number as contents, a new length and paragraph attributes
- `contents` on a text frame or text range takes a number and writes it as `String(number)` gives it; other values still throw. - Setting a text range's `length` moves its end and leaves the text as it is (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ lists it as read/write). A value that is not a whole number from 0 to the units left in the frame throws. Each read of a member that gives a range gives a new object, so setting one range's length leaves the others alone. - A text range has the paragraph attributes as well as the character attributes, so `range.justification` reads and sets the paragraphs the range touches. - `characters`, `words` and `paragraphs` have `add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)` (https://ai-scripting.docsforadobe.dev/jsobjref/Words/), which insert the text as one `text.editRange` and give its range. An added word is kept apart from its neighbors by a space and an added paragraph by a paragraph break; an empty string runs no command. - `app.textFonts.getByName` also finds a bundled face by its PostScript name. Docs: docs/mcp.md, docs/target-app-parity.md.
This commit is contained in:
1 parent
a7323e1e86
commit
1a21617e73
4 files changed
+280
-24
No files matched your search
@@ -24,11 +24,17 @@
|
||||
//! text.
|
||||
//! - The model keeps the frame's last [`MAX_EDITS`] edits; a range made before an edit that is no
|
||||
//! longer kept is stale.
|
||||
//! - Setting a range's `length` moves its end and leaves the text as it is; each read of a member
|
||||
//! that gives a range gives a new object.
|
||||
//! - `add` on `characters`, `words` or `paragraphs` inserts after the collection's last item, and
|
||||
//! `addBefore` before its first. An added word is kept apart from the characters next to it by a
|
||||
//! space, and an added paragraph by a paragraph break.
|
||||
//! - A character attribute read on a range whose characters differ gives the first character's
|
||||
//! value; set on an empty range it changes nothing. A paragraph attribute reads the first
|
||||
//! paragraph the range touches and sets every one of them.
|
||||
//! paragraph the range touches and sets every one of them. A text range has the members of
|
||||
//! both its `characterAttributes` and its `paragraphAttributes`.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
@@ -188,6 +194,10 @@ 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 number of text range objects made, which numbers the next one.
|
||||
made: Cell<u64>,
|
||||
/// The span of each range object, by its number, whose `length` the script set.
|
||||
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
|
||||
}
|
||||
|
||||
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
|
||||
@@ -320,20 +330,32 @@ fn usize_of(n: f64) -> Option<usize> {
|
||||
whole(n).and_then(|v| usize::try_from(v).ok())
|
||||
}
|
||||
|
||||
/// A new object of `class` for the span `s..e` of the frame `item` at generation `stamp`. Each
|
||||
/// object is numbered, so setting one range's `length` leaves every other range as it is.
|
||||
fn range_ref(h: &Host, item: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
|
||||
let made = &h.dom.text.made;
|
||||
made.set(made.get() + 1);
|
||||
host_ref(class, &[float(h.run), float(item.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp), float(made.get())])
|
||||
}
|
||||
|
||||
/// The span `d` names, when it is an object of one of `classes`.
|
||||
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<Span, HostError> {
|
||||
span_and_number(h, d, classes).map(|(span, _)| span)
|
||||
}
|
||||
|
||||
/// The span `d` names and the number of its object, when it is an object of one of `classes`.
|
||||
fn span_and_number(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<(Span, u64), HostError> {
|
||||
let handle = classes.iter().find_map(|c| handle_of(d, c));
|
||||
let Some(&[run, uid, high, low, s, e, stamp]) = handle.as_deref() else {
|
||||
let Some(&[run, uid, high, low, s, e, stamp, number]) = handle.as_deref() else {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
|
||||
};
|
||||
let frame = item_of(h, &host_ref("TextFrame", &[run, uid, high, low])).map_err(|_| HostError::Error(STALE_RANGE.into()))?;
|
||||
let (Some(start), Some(end), Some(stamp)) = (usize_of(s), usize_of(e), whole(stamp)) else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
Ok(Span { item: frame, start, end, stamp })
|
||||
let (Some(start), Some(end), Some(stamp), Some(number)) = (usize_of(s), usize_of(e), whole(stamp), whole(number)) else {
|
||||
return Err(HostError::Error(STALE_RANGE.into()));
|
||||
};
|
||||
let (start, end, stamp) = h.dom.text.resized.borrow().get(&number).copied().unwrap_or((start, end, stamp));
|
||||
Ok((Span { item: frame, start, end, stamp }, number))
|
||||
}
|
||||
|
||||
/// The text frame `this` names.
|
||||
@@ -401,10 +423,18 @@ fn read_contents(h: &Host, r: Span) -> Answer {
|
||||
Ok(text(to_script(&index.text[a..b])))
|
||||
}
|
||||
|
||||
/// The text a script gives as `contents`: a string, or a number as `String(number)` writes it.
|
||||
fn contents_of(value: &Data) -> std::result::Result<String, HostError> {
|
||||
match value {
|
||||
Data::String(v) => Ok(from_script(v)),
|
||||
Data::Number(n) => Ok(vectorcraft_js::number_to_string(*n)),
|
||||
_ => Err(HostError::Type("contents must be a string or a number".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the text of `r` with `value`, as one `text.editRange`.
|
||||
fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
|
||||
let Data::String(v) = value else { return Err(HostError::Type("contents must be a string".into())) };
|
||||
let insert = from_script(v);
|
||||
let insert = contents_of(value)?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let (a, b) = (index.byte(s, false), index.byte(e, true));
|
||||
if index.text[a..b] == insert {
|
||||
@@ -562,6 +592,21 @@ fn range_length(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(num(float((e - s) as u64)))
|
||||
}
|
||||
|
||||
/// Setting `length` moves the range's end to that many UTF-16 units after its start; the text
|
||||
/// does not change. A length that is not a whole number from 0 to the units left in the frame
|
||||
/// throws.
|
||||
fn range_set_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, number) = span_and_number(h, arg(a, 0), &["TextRange"])?;
|
||||
let (index, s, _, stamp) = resolve(h, r)?;
|
||||
let n = super::number(arg(a, 1), "length")?;
|
||||
let left = index.len() - s;
|
||||
let Some(n) = usize_of(n).filter(|n| *n <= left) else {
|
||||
return Err(HostError::Range(format!("length must be a whole number from 0 to {left}")));
|
||||
};
|
||||
h.dom.text.resized.borrow_mut().insert(number, (s, s + n, stamp));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `remove()`: deletes the range's text.
|
||||
fn range_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_range(h, a)?, &text(""))
|
||||
@@ -650,6 +695,85 @@ fn part_at(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(span.map_or(Data::Undefined, |(x, y)| range_ref(h, r.item, x, y, stamp, "TextRange")))
|
||||
}
|
||||
|
||||
/// Where `add` puts its text: before or after the relative object.
|
||||
fn text_placement(d: &Data) -> std::result::Result<bool, HostError> {
|
||||
match d {
|
||||
Data::Undefined => Ok(true),
|
||||
Data::String(s) if s == "ElementPlacement.PLACEBEFORE" || s == "ElementPlacement.PLACEATBEGINNING" => Ok(false),
|
||||
Data::String(s) if s == "ElementPlacement.PLACEAFTER" || s == "ElementPlacement.PLACEATEND" => Ok(true),
|
||||
_ => Err(HostError::Type("insertionLocation must be PLACEBEFORE, PLACEAFTER, PLACEATBEGINNING or PLACEATEND".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// `add(contents, relativeObject?, insertionLocation?)` and, with `before`, `addBefore(contents)`:
|
||||
/// inserts `contents` after the collection's last item (`addBefore`: before its first item), or
|
||||
/// before or after `relativeObject`, a text range or text frame of the same frame, as one
|
||||
/// `text.editRange`. A word gets a space on each side that touches another character that is not
|
||||
/// white space; a paragraph gets a paragraph break on each side that touches another paragraph.
|
||||
/// → the range of `contents`.
|
||||
fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let contents = contents_of(arg(a, 1))?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
let at = if before || matches!(arg(a, 2), Data::Undefined) {
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let span = |k: usize| match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
if before {
|
||||
items.clone().next().and_then(span).map_or(s, |(x, _)| x)
|
||||
} else {
|
||||
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
|
||||
}
|
||||
} else {
|
||||
let rel = arg(a, 2);
|
||||
let target = if handle_of(rel, "TextFrame").is_some() {
|
||||
whole_span(h, item_of(h, rel)?)?.1
|
||||
} else {
|
||||
span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))?
|
||||
};
|
||||
if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id {
|
||||
return Err(HostError::Error("relativeObject must be text of the same text frame".into()));
|
||||
}
|
||||
let (_, ts, te, _) = resolve(h, target)?;
|
||||
if text_placement(arg(a, 3))? { te } else { ts }
|
||||
};
|
||||
if contents.is_empty() {
|
||||
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
|
||||
return Ok(range_ref(h, r.item, at, at, stamp, "TextRange"));
|
||||
}
|
||||
let b = index.byte(at, false);
|
||||
let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next());
|
||||
let (lead, trail) = match part {
|
||||
Part::Characters => ("", ""),
|
||||
Part::Words => {
|
||||
let apart = |c: Option<char>| c.is_some_and(|c| !c.is_whitespace());
|
||||
let lead = if apart(prev) && !contents.starts_with(char::is_whitespace) { " " } else { "" };
|
||||
let trail = if apart(next) && !contents.ends_with(char::is_whitespace) { " " } else { "" };
|
||||
(lead, trail)
|
||||
}
|
||||
Part::Paragraphs => (
|
||||
if prev.is_some_and(|c| c != '\n') && !contents.starts_with('\n') { "\n" } else { "" },
|
||||
if next.is_some() && !contents.ends_with('\n') { "\n" } else { "" },
|
||||
),
|
||||
};
|
||||
let insert = format!("{lead}{contents}{trail}");
|
||||
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
|
||||
record(h, r.item, &index, at, 0, &insert)?;
|
||||
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
|
||||
let start = at + lead.encode_utf16().count();
|
||||
Ok(range_ref(h, r.item, start, start + contents.encode_utf16().count(), stamp, "TextRange"))
|
||||
}
|
||||
|
||||
fn part_add_after(h: &Host, a: &[Data]) -> Answer {
|
||||
part_add(h, a, false)
|
||||
}
|
||||
|
||||
fn part_add_before(h: &Host, a: &[Data]) -> Answer {
|
||||
part_add(h, a, true)
|
||||
}
|
||||
|
||||
// ---- character attributes ----
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -1280,19 +1404,24 @@ fn fonts_at(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(if found { host_ref("TextFont", &[float(h.run), float(i as u64)]) } else { Data::Undefined })
|
||||
}
|
||||
|
||||
/// `textFonts.getByName(name)`: the PostScript name, then the family and style with a space.
|
||||
/// `textFonts.getByName(name)`: the PostScript name of a bundled or installed face, then the family
|
||||
/// and style with a space.
|
||||
fn fonts_by_name(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
|
||||
if name.len() > super::MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the name is too long".into()));
|
||||
}
|
||||
let named = vectorcraft_text::FontDb::global().by_postscript_name(name);
|
||||
let named = vectorcraft_text::FontDb::global().find_postscript(name).map(|f| (f.family.clone(), f.style.clone()));
|
||||
let i = with_fonts(h, |l| {
|
||||
h.charge_call(l.len() as u64)?;
|
||||
let by_ps = named.as_ref().and_then(|(f, s)| l.iter().position(|(lf, ls)| lf.eq_ignore_ascii_case(f) && ls.eq_ignore_ascii_case(s)));
|
||||
Ok::<_, HostError>(by_ps.or_else(|| l.iter().position(|(f, s)| format!("{f} {s}").eq_ignore_ascii_case(name))))
|
||||
})?;
|
||||
i.map(|i| host_ref("TextFont", &[float(h.run), float(i as u64)])).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
match (i, named) {
|
||||
(Some(i), _) => Ok(host_ref("TextFont", &[float(h.run), float(i as u64)])),
|
||||
(None, Some((family, style))) => Ok(font_ref(h, &family, &style)),
|
||||
(None, None) => Err(HostError::Error(NOT_FOUND.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn fonts_index(h: &Host, a: &[Data]) -> Answer {
|
||||
@@ -1493,7 +1622,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("start", read_only(l, range_start, "TextRange", "start")),
|
||||
("end", read_only(l, range_end, "TextRange", "end")),
|
||||
("characterOffset", read_only(l, range_start, "TextRange", "characterOffset")),
|
||||
("length", read_only(l, range_length, "TextRange", "length")),
|
||||
("length", property(l, range_length, range_set_length)),
|
||||
("characters", get(l, characters)),
|
||||
("words", get(l, words)),
|
||||
("paragraphs", get(l, paragraphs)),
|
||||
@@ -1504,6 +1633,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, range_remove)),
|
||||
]);
|
||||
range.extend(attr_members(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
@@ -1529,7 +1659,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![("typename", get(l, part_typename)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]),
|
||||
named(vec![
|
||||
("typename", get(l, part_typename)),
|
||||
("length", get(l, part_length)),
|
||||
("parent", get(l, part_parent)),
|
||||
("add", method(l, part_add_after)),
|
||||
("addBefore", method(l, part_add_before)),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
)
|
||||
};
|
||||
|
||||
@@ -88,7 +88,19 @@ fn contents_reads_paragraph_breaks_as_r_and_accepts_every_break() {
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames[0]; t.contents = 'a\\rb\\r\\nc\\nd\\u0003e'; vc.log(t.contents);");
|
||||
assert_eq!(out, vec![json!("a\rb\rc\rd\u{3}e")]);
|
||||
assert_eq!(plain(&s, id), "a\nb\nc\nd\u{2028}e");
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = 5;").contains("contents must be a string"));
|
||||
assert!(failure(&mut s, "app.activeDocument.textFrames[0].contents = true;").contains("contents must be a string or a number"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contents_takes_a_number_as_its_text() {
|
||||
let (mut s, id) = doc_with("x");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0]; t.contents = 7; vc.log(t.contents);\
|
||||
t.textRange.characters[0].contents = 2.5; vc.log(t.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("7"), json!("2.5")]);
|
||||
assert_eq!(plain(&s, id), "2.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -189,7 +201,10 @@ fn bad_attribute_values_are_refused_without_a_change() {
|
||||
("r.textFont = 'Arial';", "textFont must be a TextFont"),
|
||||
("r.paragraphAttributes.justification = 'LEFT';", "Justification value"),
|
||||
("r.paragraphAttributes.leftIndent = 5000;", "leftIndent"),
|
||||
("r.length = 1;", "cannot be set yet"),
|
||||
("r.length = -1;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 1.5;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 4;", "length must be a whole number from 0 to 3"),
|
||||
("r.length = 'two';", "length must be a finite number"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}"));
|
||||
assert!(e.contains(want), "{src}: {e}");
|
||||
@@ -246,10 +261,10 @@ fn paragraph_attributes_set_the_paragraphs_a_range_touches() {
|
||||
&mut s,
|
||||
"var p = app.activeDocument.textFrames[0].paragraphs; p[0].paragraphAttributes.justification = Justification.RIGHT;\
|
||||
p[0].paragraphAttributes.spaceAfter = 4;\
|
||||
vc.log([p[0].justification === undefined, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\
|
||||
vc.log([p[0].justification, p[0].paragraphAttributes.justification, p[1].paragraphAttributes.justification]);\
|
||||
vc.log([p[0].paragraphAttributes.spaceAfter, p[1].paragraphAttributes.spaceAfter]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]);
|
||||
assert_eq!(out, vec![json!(["Justification.RIGHT", "Justification.RIGHT", "Justification.CENTER"]), json!([4, 0])]);
|
||||
// The empty paragraph after a final break belongs only to an empty range at the end.
|
||||
let (mut s, id) = doc_with("a\n");
|
||||
let out = log(
|
||||
@@ -431,6 +446,101 @@ fn text_fonts_list_and_assign_fonts_by_name() {
|
||||
assert_eq!(&set, &(family.clone(), style.clone()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() {
|
||||
let (mut s, id) = doc_with("hello world");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange, w = t.words[1]; r.length = 2;\
|
||||
vc.log([r.length, r.contents, r.start, r.end, t.textRange.length]);\
|
||||
w.length = 3; vc.log([w.contents, w.start]); r.length = 0; vc.log([r.length, r.contents]);\
|
||||
t.characters[0].contents = 'J'; r.length = 5; vc.log(r.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([2, "he", 0, 2, 11]), json!(["wor", 6]), json!([0, ""]), json!("Jello")]);
|
||||
assert_eq!(plain(&s, id), "Jello world");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
let cases = [
|
||||
("t.words.add('x')", "hello world", "hello world x", "x"),
|
||||
("t.words.addBefore('x')", "hello world", "x hello world", "x"),
|
||||
("t.words[0].words.add('x')", "hello world", "hello x world", "x"),
|
||||
("t.words.add('x', t.words[0], ElementPlacement.PLACEBEFORE)", "hello world", "x hello world", "x"),
|
||||
("t.words.add('x', t.words[1], ElementPlacement.PLACEATBEGINNING)", "hello world", "hello x world", "x"),
|
||||
("t.words.add('x', t, ElementPlacement.PLACEATEND)", "hello world", "hello world x", "x"),
|
||||
("t.words.add('x')", "hello world ", "hello world x ", "x"),
|
||||
("t.words.add('x')", "", "x", "x"),
|
||||
("t.words.add(7)", "a", "a 7", "7"),
|
||||
("t.characters.add('!')", "hi", "hi!", "!"),
|
||||
("t.characters[0].characters.add('x')", "hi", "hxi", "x"),
|
||||
("t.paragraphs.add('end')", "one\ntwo", "one\ntwo\nend", "end"),
|
||||
("t.paragraphs[0].paragraphs.add('mid')", "one\ntwo", "one\nmid\ntwo", "mid"),
|
||||
("t.paragraphs.addBefore('top')", "one", "top\none", "top"),
|
||||
];
|
||||
for (call, text, after, added) in cases {
|
||||
let (mut s, id) = doc_with(text);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, &format!("var t = app.activeDocument.textFrames[0], n = {call}; vc.log([n.typename, n.contents]);"));
|
||||
assert_eq!(out, vec![json!(["TextRange", added])], "{call} on {text:?}");
|
||||
assert_eq!(plain(&s, id), after, "{call} on {text:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1, "{call} on {text:?}");
|
||||
}
|
||||
// Empty contents add nothing; bad arguments throw before anything changes.
|
||||
let (mut s, id) = doc_with("ab");
|
||||
s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);");
|
||||
assert_eq!(out, vec![json!([0, 5])]);
|
||||
for (call, want) in [
|
||||
("t.words.add(null)", "contents must be a string or a number"),
|
||||
("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"),
|
||||
("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"),
|
||||
("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"),
|
||||
("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};"));
|
||||
assert!(e.contains(want), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
assert_eq!(plain(&s, id), "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_fonts_find_a_bundled_face_by_its_postscript_name() {
|
||||
let Some(face) = vectorcraft_text::FontDb::global().loaded_faces().into_iter().find(|f| f.family == "Source Sans 3") else {
|
||||
return; // Built without the bundled fonts.
|
||||
};
|
||||
let ps = face.postscript_name();
|
||||
let (mut s, _) = doc_with("abc");
|
||||
let out = log(&mut s, &format!("var f = app.textFonts.getByName('{ps}'); vc.log([f.family, f.style, f.name]);"));
|
||||
assert_eq!(out, vec![json!([face.family, face.style, ps])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_range_sets_the_paragraph_attributes_of_the_paragraphs_it_touches() {
|
||||
let (mut s, id) = doc_with("first\nsecond\nthird");
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames[0], r = t.textRange; r.justification = Justification.CENTER;\
|
||||
vc.log([r.justification, t.paragraphs[2].paragraphAttributes.justification]);\
|
||||
t.characters[7].leftIndent = 9; vc.log([t.paragraphs[0].leftIndent, t.paragraphs[1].leftIndent, t.paragraphs[2].leftIndent]);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Justification.CENTER", "Justification.CENTER"]), json!([0, 9, 0])]);
|
||||
let justify: Vec<Justify> = match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => (0..3).map(|i| t.para_at(i).justify).collect(),
|
||||
_ => panic!("not text"),
|
||||
};
|
||||
assert_eq!(justify, vec![Justify::Center; 3]);
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames[0].textRange.justification = 'CENTER';");
|
||||
assert!(e.contains("Justification value"), "{e}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_outline_and_conversions_return_the_new_objects() {
|
||||
let (mut s, id) = doc_with("Hi");
|
||||
|
||||
+16
-6
@@ -2701,7 +2701,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
`convertAreaObjectToPointObject()`. A `TextRange` (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) has
|
||||
`contents`, `start`, `end`, `characterOffset` (the same as `start`), `length`, `parent` (its frame), `characters`,
|
||||
`words`, `paragraphs`, `characterAttributes`, `paragraphAttributes`, `getParagraphLength()`, `getTextRunLength()` and
|
||||
`remove()`, and the character attributes themselves. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to
|
||||
`remove()`, and the character and paragraph attributes themselves. `contents` takes a string, or a number as
|
||||
`String(number)` writes it. Setting `length` to a whole number from 0 to the units left in the frame moves the range's
|
||||
end and leaves the text as it is. The `characters`, `words` and `paragraphs` collections
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Words/) have `length`, `parent`, `[i]`,
|
||||
`add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its
|
||||
range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to
|
||||
5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and
|
||||
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`,
|
||||
set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are
|
||||
@@ -2709,8 +2714,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`,
|
||||
`spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/) lists every style of every family in the font menu, with
|
||||
`length`, `[i]`, `index(key)` and `getByName(name)`, which takes a PostScript name or the family and style joined by a
|
||||
space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`,
|
||||
`length`, `[i]`, `index(key)` and `getByName(name)`, which takes the PostScript name of a bundled or installed font, or
|
||||
the family and style joined by a space; a `TextFont` has `name` (its PostScript name), `family` and `style`. The enumerations `TextType`,
|
||||
`TextOrientation` and `Justification` hold strings such as `"Justification.CENTER"`.
|
||||
VectorCraft's own rules: offsets and lengths count UTF-16 code units, as a JavaScript string does, and an offset
|
||||
inside a surrogate pair takes in its whole character; one item of `characters` is one code point. `contents` gives a
|
||||
@@ -2735,9 +2740,14 @@ app through the global object `vc`, and writes to the Script Console and runs ot
|
||||
the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws
|
||||
when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the
|
||||
font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws
|
||||
`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.
|
||||
`Stale text font`. Each read of a member that gives a range gives a new object, so setting one range's `length`
|
||||
leaves the others as they are. `add` without a relative object inserts after the collection's last item, and
|
||||
`addBefore` before its first; with one, a text range or the text frame of the same frame, `PLACEBEFORE` and
|
||||
`PLACEATBEGINNING` insert at its start and `PLACEAFTER`, `PLACEATEND` or no location at its end. An added word is
|
||||
kept apart from the characters next to it by a space, and an added paragraph by a paragraph break; adding an empty
|
||||
string runs no command. 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`,
|
||||
`characterOffset` and `orientation` cannot be set 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
|
||||
|
||||
@@ -1025,7 +1025,7 @@ 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 (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. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.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