mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-30 02:07:10 +01:00
Merge pull request #9064 from dotCooCoo/feat/scripts-api-d4c-threads-stories
Scripts: nextFrame, previousFrame, story and document.stories for threaded type
This commit is contained in:
13 files changed
+1778
-49
No files matched your search
@@ -682,6 +682,7 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"text.thread.info",
|
||||
"text.thread.releaseSelection",
|
||||
"text.thread.remove",
|
||||
"text.thread.setNeighbor",
|
||||
"text.touchType",
|
||||
"threeD.addGraphic",
|
||||
"threeD.mapArt",
|
||||
|
||||
@@ -59,6 +59,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.setNeighbor",
|
||||
"Thread Text",
|
||||
[],
|
||||
None,
|
||||
"{id, side: \"next\"|\"previous\", neighbor: id|null} link area type or type on a path `id` to the frame that follows it (`next`) or comes before it (`previous`) in its story, or with null break that one link, as a script's `nextFrame` and `previousFrame` assignments do. Linking joins two stories: `id` must be the last frame of its story for `next` (the first for `previous`) and `neighbor` the first (the last) of another one, and the second story's text flows on after the first's. Breaking a link makes each side of it a story of its own: no text moves across the break, and the frames after it flow their own text again from their first frame, which now starts a paragraph. An error, with nothing changed, for point type or other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a frame of either story that is hidden or locked; a link that is already there, or a break where there is no link, changes nothing and records no undo step; the selection is kept → {changed: bool, threads: [[id…]] (the stories of the frames involved, after the change, a one-frame story as [id])}",
|
||||
has_doc,
|
||||
set_neighbor
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order: its thread's area type and type on
|
||||
/// a path, each once, or `id` alone when it is in no thread.
|
||||
fn chain_of(d: &Document, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(d, id);
|
||||
let mut seen = Ids::default();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
fn chain_ids(chains: &[&[NodeId]]) -> Value {
|
||||
json!(chains.iter().filter(|c| !c.is_empty()).map(|c| c.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// `text.thread.setNeighbor`: link a frame to the frame after or before it, or break that link.
|
||||
fn set_neighbor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.setNeighbor";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let next = match p.get("side").and_then(Value::as_str) {
|
||||
Some("next") => true,
|
||||
Some("previous") => false,
|
||||
_ => return Err(bad(C, "`side` must be \"next\" or \"previous\"")),
|
||||
};
|
||||
let neighbor = match p.get("neighbor") {
|
||||
None => return Err(bad(C, "missing `neighbor` (an id, or null to break the link)")),
|
||||
Some(Value::Null) => None,
|
||||
Some(v) => Some(checked_id(s, v, C)?),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
if text_of(d, id).is_none() {
|
||||
return Err(bad(C, "`id` must be area type or type on a path"));
|
||||
}
|
||||
let locked = |frames: &[NodeId]| {
|
||||
let editable = d.editable();
|
||||
frames.iter().any(|f| !editable(*f))
|
||||
};
|
||||
let chain = chain_of(d, id);
|
||||
let Some(n) = neighbor else {
|
||||
// Break the link on that side: the frames before it and the frames after it.
|
||||
let i = chain.iter().position(|f| *f == id).unwrap_or(0);
|
||||
let at = if next { i + 1 } else { i };
|
||||
if at == 0 || at >= chain.len() {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&chain])}));
|
||||
}
|
||||
if locked(&chain) {
|
||||
return Err(bad(C, "a frame of the story is hidden or locked"));
|
||||
}
|
||||
let (head, tail) = (chain[..at].to_vec(), chain[at..].to_vec());
|
||||
let cut: Ids = chain.iter().copied().collect();
|
||||
s.edit("Break Thread", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| cut.contains(f)));
|
||||
for part in [&head, &tail] {
|
||||
if part.len() >= 2 {
|
||||
d.text_threads.push(part.clone());
|
||||
}
|
||||
}
|
||||
// The first frame after the break starts its story, which flows again on this edit so
|
||||
// that its numbered paragraphs count from 1.
|
||||
if let Some(f) = tail.first() {
|
||||
touch(d, *f);
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = tail.first().and_then(|f| d.node_mut(*f)).map(|n| &mut n.kind)
|
||||
&& t.first_para_continues
|
||||
{
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({"changed": true, "threads": chain_ids(&[&head, &tail])}));
|
||||
};
|
||||
if n == id {
|
||||
return Err(bad(C, "a frame cannot be linked to itself"));
|
||||
}
|
||||
if text_of(d, n).is_none() {
|
||||
return Err(bad(C, "`neighbor` must be area type or type on a path"));
|
||||
}
|
||||
// `first` is to flow into `second`.
|
||||
let (first, second) = if next { (id, n) } else { (n, id) };
|
||||
let (a, b) = if next { (chain, chain_of(d, n)) } else { (chain_of(d, n), chain) };
|
||||
if a.contains(&second) {
|
||||
if a.windows(2).any(|w| w == [first, second]) {
|
||||
return Ok(json!({"changed": false, "threads": chain_ids(&[&a])}));
|
||||
}
|
||||
return Err(bad(C, "the two frames are already in one story: the link would make a loop or reorder it"));
|
||||
}
|
||||
if a.last() != Some(&first) {
|
||||
return Err(bad(C, format!("frame {} already has a next frame: break that link first", first.0)));
|
||||
}
|
||||
if b.first() != Some(&second) {
|
||||
return Err(bad(C, format!("frame {} already has a previous frame: break that link first", second.0)));
|
||||
}
|
||||
if locked(&a) || locked(&b) {
|
||||
return Err(bad(C, "a frame of either story is hidden or locked"));
|
||||
}
|
||||
let joined: Vec<NodeId> = a.iter().chain(&b).copied().collect();
|
||||
let affected: Ids = joined.iter().copied().collect();
|
||||
s.edit("Thread Text", |d, _| {
|
||||
d.text_threads.retain(|t| !t.iter().any(|f| affected.contains(f)));
|
||||
d.text_threads.push(joined.clone());
|
||||
// Force a re-flow of the joined story on this edit.
|
||||
touch(d, first);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({"changed": true, "threads": chain_ids(&[&joined])}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -2740,6 +2740,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("textFrames", text::doc_text_frames(l), MemberInfo { collection: true, ..typed("TextFrames") }),
|
||||
("stories", text::threads::doc_stories(l), MemberInfo { collection: true, ..typed("Stories") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
|
||||
@@ -50,6 +50,8 @@ use super::{
|
||||
};
|
||||
use crate::{DocState, Document, NodeId, NodeKind};
|
||||
|
||||
pub(super) mod threads;
|
||||
|
||||
/// 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";
|
||||
@@ -194,6 +196,7 @@ 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)>>>,
|
||||
stories: threads::StoryState,
|
||||
/// 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.
|
||||
@@ -609,7 +612,10 @@ fn range_set_length(h: &Host, a: &[Data]) -> Answer {
|
||||
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));
|
||||
// An end inside a surrogate pair moves out to the end of its character.
|
||||
let end = s + n;
|
||||
let end = index.chars.get(index.chars.partition_point(|&c| c < end)).copied().unwrap_or(end);
|
||||
h.dom.text.resized.borrow_mut().insert(number, (s, end, stamp));
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
@@ -1322,39 +1328,54 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
|
||||
return Err(HostError::Error(super::CROSS_DOCUMENT.into()));
|
||||
}
|
||||
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
|
||||
return Err(HostError::Error("TextFrames: threading and path positions are not available yet".into()));
|
||||
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
|
||||
}
|
||||
let orientation = if on_path { 4 } else { 2 };
|
||||
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
|
||||
let vertical = vertical_of(arg(a, orientation))?;
|
||||
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
|
||||
if base.is_some() {
|
||||
threads::check_base_path(h, path)?;
|
||||
}
|
||||
let mode = if on_path { "onPath" } else { "area" };
|
||||
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
|
||||
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", ¶ms))?;
|
||||
new_ref(h, doc, result_id(&r))
|
||||
let id = result_id(&r);
|
||||
if let (Some((base, postfix)), Some(id)) = (base, id) {
|
||||
threads::thread_new(h, base, id, postfix)?;
|
||||
}
|
||||
new_ref(h, doc, id)
|
||||
}
|
||||
|
||||
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
|
||||
fn frames_area_text(h: &Host, a: &[Data]) -> Answer {
|
||||
in_path(h, a, false, &[3, 4])
|
||||
in_path(h, a, false, &[])
|
||||
}
|
||||
|
||||
/// `pathText(textPath, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)`.
|
||||
fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
|
||||
in_path(h, a, true, &[2, 3, 5, 6])
|
||||
in_path(h, a, true, &[2, 3])
|
||||
}
|
||||
|
||||
/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first.
|
||||
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
|
||||
/// locked artboard, stops it first, as `PageItems.removeAll()` does.
|
||||
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = frames_doc(h, a)?;
|
||||
let (ids, refused) = with_doc(h, doc, |_, st| {
|
||||
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
|
||||
let ids = frame_ids(h, st);
|
||||
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
|
||||
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused)
|
||||
let locks = st.doc.locked_artboards();
|
||||
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
|
||||
(ids, refused, on_locked)
|
||||
});
|
||||
if !refused.is_empty() {
|
||||
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}")));
|
||||
}
|
||||
if !on_locked.is_empty() {
|
||||
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
|
||||
}
|
||||
if !ids.is_empty() {
|
||||
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
|
||||
}
|
||||
@@ -1525,6 +1546,23 @@ fn read_only(link: &Link, g: super::Member, class: &'static str, name: &'static
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for character attribute `attr`.
|
||||
fn attr_type(attr: Attr) -> &'static str {
|
||||
match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
/// The type `reflect` gives for paragraph attribute `attr`.
|
||||
fn para_type(attr: ParaAttr) -> &'static str {
|
||||
match attr {
|
||||
ParaAttr::Justification => "Justification",
|
||||
_ => "number",
|
||||
}
|
||||
}
|
||||
|
||||
fn attr_members(link: &Link) -> Vec<Described> {
|
||||
let mut out = Vec::new();
|
||||
for (name, attr) in ATTRS {
|
||||
@@ -1540,12 +1578,7 @@ fn attr_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_attr(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = match attr {
|
||||
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
|
||||
Attr::TextFont => "TextFont",
|
||||
_ => "number",
|
||||
};
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(attr_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1565,8 +1598,7 @@ fn para_members(link: &Link) -> Vec<Described> {
|
||||
h.charge_call(16 + a.iter().map(super::data_size).sum::<u64>())?;
|
||||
write_para(&h, &a, attr, name)
|
||||
});
|
||||
let data_type = if matches!(attr, ParaAttr::Justification) { "Justification" } else { "number" };
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(data_type)));
|
||||
out.push((name.to_string(), HostMember::Property { get: g, set: s }, typed(para_type(attr))));
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1592,27 +1624,26 @@ pub(super) fn install_enums(realm: &mut Realm) -> std::result::Result<(), RunErr
|
||||
|
||||
/// The classes of type, `TextFrame` among them, which inherits from `PageItem`.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut frame = named(vec![
|
||||
("kind", get(l, frame_kind), typed("TextType")),
|
||||
("contents", property(l, frame_contents, frame_set_contents), typed("string")),
|
||||
("textRange", get(l, frame_range), typed("TextRange")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("orientation", read_only(l, frame_orientation, "TextFrame", "orientation"), typed("TextOrientation")),
|
||||
("createOutline", method(l, frame_outline), returns("GroupItem", &[])),
|
||||
("convertAreaObjectToPointObject", method(l, frame_to_point), returns("TextFrame", &[])),
|
||||
("convertPointObjectToAreaObject", method(l, frame_to_area), returns("TextFrame", &[])),
|
||||
]);
|
||||
frame.extend(super::variables::item_members(l, "TextFrame"));
|
||||
frame.extend(threads::frame_members(l));
|
||||
frame.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"nextFrame",
|
||||
"previousFrame",
|
||||
"textPath",
|
||||
"anchor",
|
||||
"antialias",
|
||||
@@ -1637,9 +1668,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("end", read_only(l, range_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, range_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", property(l, range_length, range_set_length), typed("number")),
|
||||
("characters", get(l, characters), MemberInfo { collection: true, ..typed("Characters") }),
|
||||
("words", get(l, words), MemberInfo { collection: true, ..typed("Words") }),
|
||||
("paragraphs", get(l, paragraphs), MemberInfo { collection: true, ..typed("Paragraphs") }),
|
||||
("characters", get(l, characters), collection("Characters")),
|
||||
("words", get(l, words), collection("Words")),
|
||||
("paragraphs", get(l, paragraphs), collection("Paragraphs")),
|
||||
("characterAttributes", get(l, character_attributes), typed("CharacterAttributes")),
|
||||
("paragraphAttributes", get(l, paragraph_attributes), typed("ParagraphAttributes")),
|
||||
("getParagraphLength", method(l, range_paragraph_length), returns("number", &[("charIndex", "number")])),
|
||||
@@ -1647,13 +1678,13 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, range_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(attr_members(l));
|
||||
range.push(threads::range_member(l));
|
||||
range.extend(para_members(l));
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"story",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
@@ -1676,8 +1707,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("*")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string")])),
|
||||
("parent", get(l, part_parent), typed("TextRange")),
|
||||
("add", method(l, part_add_after), returns("TextRange", &[("contents", "string"), ("relativeObject", "TextRange")])),
|
||||
("addBefore", method(l, part_add_before), returns("TextRange", &[("contents", "string")])),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
@@ -1687,7 +1718,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
chars.extend(attr_members(l));
|
||||
let mut paras = named(vec![("typename", get(l, para_attrs_typename), typed("string"))]);
|
||||
paras.extend(para_members(l));
|
||||
vec![
|
||||
let stories = threads::classes(l);
|
||||
let mut out = vec![
|
||||
class("TextFrame", Some("PageItem"), frame, None),
|
||||
class("TextRange", None, range, None),
|
||||
part("Characters"),
|
||||
@@ -1702,12 +1734,29 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", get(l, frames_typename), typed("string")),
|
||||
("length", get(l, frames_length), typed("number")),
|
||||
("parent", get(l, frames_parent), typed("Document")),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "TextFrame")])),
|
||||
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
|
||||
("add", method(l, frames_add), returns("TextFrame", &[])),
|
||||
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
|
||||
("areaText", method(l, frames_area_text), returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation")])),
|
||||
("pathText", method(l, frames_path_text), returns("TextFrame", &[("textPath", "PathItem"), ("startTValue", "number")])),
|
||||
(
|
||||
"areaText",
|
||||
method(l, frames_area_text),
|
||||
returns("TextFrame", &[("textPath", "PathItem"), ("orientation", "TextOrientation"), ("baseFrame", "TextFrame")]),
|
||||
),
|
||||
(
|
||||
"pathText",
|
||||
method(l, frames_path_text),
|
||||
returns(
|
||||
"TextFrame",
|
||||
&[
|
||||
("textPath", "PathItem"),
|
||||
("startTValue", "number"),
|
||||
("endTValue", "number"),
|
||||
("orientation", "TextOrientation"),
|
||||
("baseFrame", "TextFrame"),
|
||||
],
|
||||
),
|
||||
),
|
||||
("removeAll", method(l, frames_remove_all), returns("undefined", &[])),
|
||||
]),
|
||||
Some(function(l, frames_at)),
|
||||
@@ -1719,7 +1768,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
("typename", typename_of("TextFonts"), typed("string")),
|
||||
("length", get(l, fonts_length), typed("number")),
|
||||
("parent", get(l, app_ref), typed("Application")),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "TextFont")])),
|
||||
("index", method(l, fonts_index), returns("number", &[("itemKey", "*")])),
|
||||
("getByName", method(l, fonts_by_name), returns("TextFont", &[("name", "string")])),
|
||||
]),
|
||||
Some(function(l, fonts_at)),
|
||||
@@ -1736,7 +1785,9 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
]),
|
||||
None,
|
||||
),
|
||||
]
|
||||
];
|
||||
out.extend(stories);
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,829 @@
|
||||
//! Threaded type in the script object model: a text frame's `nextFrame`, `previousFrame` and
|
||||
//! `story`, `document.stories`, and each `Story` with its frames and its text, as the help pages
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Story/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Stories/> describe them.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help pages do not state:
|
||||
//! - Assigning `nextFrame` links the last frame of a story to the first frame of another story,
|
||||
//! whose text then flows on after it; `previousFrame` links the other way. Assigning `null`
|
||||
//! breaks that link, and no text moves across it. Point type, a frame of another
|
||||
//! document, the frame itself, a frame inside a story, a link that would make a loop and a hidden
|
||||
//! or locked frame in either story are refused with nothing changed. Assigning the frame that is
|
||||
//! already linked, or `null` where there is no link, changes nothing.
|
||||
//! - A `Story` is the story of the frame it was read from as that frame is threaded now; when the
|
||||
//! frame is deleted, it throws `Stale story`.
|
||||
//! - `document.stories` lists one story for each type object in no thread and one for each thread,
|
||||
//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose
|
||||
//! first frame has that name.
|
||||
//! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep
|
||||
//! their place through edits made through them, as a frame's ranges do, and are stale after any
|
||||
//! other change to the story's text and after File › Revert. A story of one frame gives that
|
||||
//! frame's own ranges.
|
||||
//! - `areaText` and `pathText` with a `baseFrame` thread the new frame after it, or before it when
|
||||
//! `postFix` is false; `postFix` is true when it is left out.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::TextKind;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, MemberInfo, host_ref};
|
||||
|
||||
use super::super::{
|
||||
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, arg, boolean, class, current, doc_of, doc_ref, edit_item, find_doc, float, function, get,
|
||||
handle_of, id_of, id_parts, in_compound, item_of, item_ref, method, named, num, property, returns, text, typed, whole, with_doc,
|
||||
};
|
||||
use super::{
|
||||
ATTRS, Index, Log, Part, STALE_RANGE, frame_ids, from_script, part_spans, range_ref, read_only, text_of, this_frame, to_script, touched,
|
||||
usize_of, whole_span,
|
||||
};
|
||||
use crate::cmd::threads::story_of;
|
||||
use crate::{DocState, Document, NodeId};
|
||||
|
||||
/// The error of a `Story` whose frame was deleted, or that came from an earlier run.
|
||||
pub const STALE_STORY: &str = "Stale story";
|
||||
|
||||
/// A document's uid, the document, and the first frame of each of its stories then.
|
||||
type StoryList = (u64, Weak<Document>, Rc<Vec<NodeId>>);
|
||||
|
||||
/// The story state of one run: the text of each story of two or more frames that a range was made
|
||||
/// of, by document and the frame the `Story` was read from, and the last list of stories.
|
||||
#[derive(Default)]
|
||||
pub(in crate::script) struct StoryState {
|
||||
logs: RefCell<HashMap<(u64, u64), Log>>,
|
||||
list: RefCell<Option<StoryList>>,
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, in thread order, each once, or `id` alone.
|
||||
fn frames_of(st: &DocState, id: NodeId) -> Vec<NodeId> {
|
||||
let mut frames = story_of(&st.doc, id);
|
||||
let mut seen = HashSet::new();
|
||||
frames.retain(|f| seen.insert(*f));
|
||||
if frames.len() < 2 { vec![id] } else { frames }
|
||||
}
|
||||
|
||||
/// The frames of the story `id` is a frame of, charged to the run.
|
||||
fn charged_frames(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<Vec<NodeId>, HostError> {
|
||||
h.charge_call(st.doc.text_threads.len() as u64)?;
|
||||
let frames = frames_of(st, id);
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// Whether type object `id` is area type or type on a path.
|
||||
fn threadable(st: &DocState, id: NodeId) -> bool {
|
||||
text_of(st, id).is_some_and(|t| !matches!(t.kind, TextKind::Point))
|
||||
}
|
||||
|
||||
// ---- nextFrame and previousFrame ----
|
||||
|
||||
fn neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let other = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(other.map_or(Data::Null, |f| item_ref(h, st, *f)))
|
||||
})
|
||||
}
|
||||
|
||||
fn next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// Assigns `nextFrame` (`next`) or `previousFrame` with `text.thread.setNeighbor`.
|
||||
fn set_neighbor(h: &Host, a: &[Data], next: bool) -> Answer {
|
||||
let name = if next { "nextFrame" } else { "previousFrame" };
|
||||
let item = this_frame(h, a)?;
|
||||
let other = match arg(a, 1) {
|
||||
Data::Null => None,
|
||||
d if handle_of(d, "TextFrame").is_some() => Some(item_of(h, d)?),
|
||||
_ => return Err(HostError::Type(format!("{name} must be a TextFrame or null"))),
|
||||
};
|
||||
if other.is_some_and(|o| o.doc.uid != item.doc.uid) {
|
||||
return Err(HostError::Error(format!("{name}: the two frames are in different documents")));
|
||||
}
|
||||
let now = with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) || other.is_some_and(|o| !threadable(st, o.id)) {
|
||||
return Err(HostError::Error(format!("{name}: only area type and type on a path can be threaded")));
|
||||
}
|
||||
let frames = charged_frames(h, st, item.id)?;
|
||||
let i = frames.iter().position(|f| *f == item.id);
|
||||
let current = i.and_then(|i| if next { frames.get(i + 1) } else { i.checked_sub(1).and_then(|i| frames.get(i)) });
|
||||
Ok(current.copied())
|
||||
})?;
|
||||
if now == other.map(|o| o.id) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let side = if next { "next" } else { "previous" };
|
||||
let params = json!({"id": item.id.0, "side": side, "neighbor": other.map(|o| o.id.0)});
|
||||
edit_item(h, item, "text.thread.setNeighbor", ¶ms).map_err(|e| match e {
|
||||
HostError::Error(m) => HostError::Error(format!("{name}: {m}")),
|
||||
e => e,
|
||||
})?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn set_next_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, true)
|
||||
}
|
||||
|
||||
fn set_previous_frame(h: &Host, a: &[Data]) -> Answer {
|
||||
set_neighbor(h, a, false)
|
||||
}
|
||||
|
||||
/// `TextFrame.story`.
|
||||
fn frame_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let item = this_frame(h, a)?;
|
||||
Ok(story_ref(h, item))
|
||||
}
|
||||
|
||||
/// `TextRange.story`: the story of the range's frame.
|
||||
fn range_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = super::this_range(h, a)?;
|
||||
super::resolve(h, r)?;
|
||||
Ok(story_ref(h, r.item))
|
||||
}
|
||||
|
||||
// ---- creating a frame threaded to another ----
|
||||
|
||||
/// The `baseFrame` and `postFix` arguments of `areaText` and `pathText`, checked before the frame
|
||||
/// is made: the frame to thread the new one to, and whether the new one goes after it.
|
||||
pub(super) fn base_frame(h: &Host, doc: Doc, base: &Data, post: &Data) -> std::result::Result<Option<(Item, bool)>, HostError> {
|
||||
if matches!(base, Data::Undefined | Data::Null) {
|
||||
return Ok(None);
|
||||
}
|
||||
if handle_of(base, "TextFrame").is_none() {
|
||||
return Err(HostError::Type("baseFrame must be a TextFrame".into()));
|
||||
}
|
||||
let item = item_of(h, base)?;
|
||||
if item.doc.uid != doc.uid {
|
||||
return Err(HostError::Error("baseFrame: the frame is in another document".into()));
|
||||
}
|
||||
let postfix = match post {
|
||||
Data::Undefined => true,
|
||||
d => boolean(d, "postFix")?,
|
||||
};
|
||||
with_doc(h, item.doc, |_, st| {
|
||||
if !threadable(st, item.id) {
|
||||
return Err(HostError::Error("baseFrame: only area type and type on a path can be threaded".into()));
|
||||
}
|
||||
let editable = st.doc.editable();
|
||||
if charged_frames(h, st, item.id)?.iter().any(|f| !editable(*f)) {
|
||||
return Err(HostError::Error("baseFrame: a frame of its story is hidden or locked".into()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Some((item, postfix)))
|
||||
}
|
||||
|
||||
/// Refuses a `baseFrame` for a path inside a compound path before the path is turned into type:
|
||||
/// `text.thread.add` does not thread type there.
|
||||
pub(super) fn check_base_path(h: &Host, path: Item) -> std::result::Result<(), HostError> {
|
||||
if in_compound(h, path) {
|
||||
return Err(HostError::Error("baseFrame: type made from a path inside a compound path cannot be threaded".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Threads the new frame `id` after `base`, or before it when `postfix` is false.
|
||||
pub(super) fn thread_new(h: &Host, base: Item, id: NodeId, postfix: bool) -> std::result::Result<(), HostError> {
|
||||
edit_item(h, base, "text.thread.add", &json!({"from": base.id.0, "to": id.0, "before": !postfix}))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Story ----
|
||||
|
||||
fn story_ref(h: &Host, item: Item) -> Data {
|
||||
let [high, low] = id_parts(item.id);
|
||||
host_ref("Story", &[float(h.run), float(item.doc.uid), high, low])
|
||||
}
|
||||
|
||||
/// The frame the story `d` was read from, which must still be a type object.
|
||||
fn story_of_data(h: &Host, d: &Data) -> std::result::Result<Item, HostError> {
|
||||
let Some(handle) = handle_of(d, "Story") else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a Story".into())) };
|
||||
let doc = find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
let id = id_of(*high, *low).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
match with_doc(h, doc, |_, st| text_of(st, id).is_some()) {
|
||||
true => Ok(Item { doc, id }),
|
||||
false => Err(HostError::Error(STALE_STORY.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn this_story(h: &Host, a: &[Data]) -> std::result::Result<Item, HostError> {
|
||||
story_of_data(h, arg(a, 0))
|
||||
}
|
||||
|
||||
fn story_frames(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
with_doc(h, story.doc, |_, st| Ok(Data::Array(charged_frames(h, st, story.id)?.iter().map(|f| item_ref(h, st, *f)).collect())))
|
||||
}
|
||||
|
||||
fn story_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
Ok(doc_ref(h, story.doc.uid))
|
||||
}
|
||||
|
||||
/// The story's one frame, or `None` for a story of two or more frames.
|
||||
fn single(h: &Host, story: Item) -> std::result::Result<Option<Item>, HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
Ok(match frames[..] {
|
||||
[one] => Some(Item { doc: story.doc, id: one }),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn story_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
let (index, _) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(num(float(index.len() as u64)))
|
||||
}
|
||||
|
||||
/// A range or a collection of the whole story, as `frame_class` for a story of one frame and
|
||||
/// `story_class` for a longer one.
|
||||
fn story_whole(h: &Host, a: &[Data], frame_class: &str, story_class: &str) -> Answer {
|
||||
let story = this_story(h, a)?;
|
||||
if let Some(frame) = single(h, story)? {
|
||||
let (_, r) = whole_span(h, frame)?;
|
||||
return Ok(range_ref(h, frame, r.start, r.end, r.stamp, frame_class));
|
||||
}
|
||||
let (index, stamp) = with_doc(h, story.doc, |_, st| observe(h, st, story.id))?;
|
||||
Ok(span_ref(h, story, 0, index.len(), stamp, story_class))
|
||||
}
|
||||
|
||||
fn story_text_range(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "TextRange", "StoryRange")
|
||||
}
|
||||
|
||||
fn story_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Characters", "StoryCharacters")
|
||||
}
|
||||
|
||||
fn story_words(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Words", "StoryWords")
|
||||
}
|
||||
|
||||
fn story_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
story_whole(h, a, "Paragraphs", "StoryParagraphs")
|
||||
}
|
||||
|
||||
// ---- the text of a story of two or more frames ----
|
||||
|
||||
/// The frames of the story and the text of each, in thread order.
|
||||
fn story_text(st: &DocState, frames: &[NodeId]) -> String {
|
||||
frames.iter().filter_map(|f| text_of(st, *f)).flat_map(|t| t.runs.iter().map(|r| r.text.as_str())).collect()
|
||||
}
|
||||
|
||||
/// The story's index and its generation now, read again when its document changed. The stories
|
||||
/// read from the frames of one story share one index of its text while the document is unchanged.
|
||||
fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<Index>, u64), HostError> {
|
||||
if text_of(st, anchor).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let key = (st.uid, anchor.0);
|
||||
let now = Arc::as_ptr(&st.doc);
|
||||
let current = |l: &Log| std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts;
|
||||
if !logs.get(&key).is_some_and(current) {
|
||||
let frames = charged_frames(h, st, anchor)?;
|
||||
// Another frame of the same story read at this state of the document has the same text;
|
||||
// a frame listed in two threads can belong to another story, so its frames must match.
|
||||
let mut shared = None;
|
||||
if frames.len() > 1 {
|
||||
h.charge_call(frames.len() as u64)?;
|
||||
if let Some((f, l)) =
|
||||
frames.iter().filter(|f| **f != anchor).find_map(|f| logs.get(&(st.uid, f.0)).filter(|l| current(l)).map(|l| (*f, l)))
|
||||
&& charged_frames(h, st, f)? == frames
|
||||
{
|
||||
shared = Some(l.index.clone());
|
||||
}
|
||||
}
|
||||
let index = match shared {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let text = story_text(st, &frames);
|
||||
// Joining the frames' text costs its length, as rebuilding the index does elsewhere.
|
||||
h.charge_call(text.len() as u64)?;
|
||||
match logs.get(&key) {
|
||||
Some(l) if l.reverts == st.reverts && l.index.text == text => l.index.clone(),
|
||||
_ => Rc::new(Index::new(text)),
|
||||
}
|
||||
}
|
||||
};
|
||||
match logs.get_mut(&key) {
|
||||
Some(l) => {
|
||||
if l.reverts != st.reverts || index.text != l.index.text {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index;
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
None => {
|
||||
logs.insert(key, Log { doc: Arc::downgrade(&st.doc), reverts: st.reverts, index, stamp: 0, floor: 0, edits: VecDeque::new() });
|
||||
}
|
||||
}
|
||||
}
|
||||
let l = logs.get(&key).ok_or_else(|| HostError::Error(STALE_STORY.into()))?;
|
||||
Ok((l.index.clone(), l.stamp))
|
||||
}
|
||||
|
||||
/// A range of a story: the frame the story was read from, its span in UTF-16 units and the
|
||||
/// generation it was made at.
|
||||
#[derive(Clone, Copy)]
|
||||
struct StorySpan {
|
||||
story: Item,
|
||||
start: usize,
|
||||
end: usize,
|
||||
stamp: u64,
|
||||
}
|
||||
|
||||
const STORY_PARTS: [(&str, Part); 3] = [("StoryCharacters", Part::Characters), ("StoryWords", Part::Words), ("StoryParagraphs", Part::Paragraphs)];
|
||||
|
||||
fn span_ref(h: &Host, story: Item, s: usize, e: usize, stamp: u64, class: &str) -> Data {
|
||||
let [high, low] = id_parts(story.id);
|
||||
host_ref(class, &[float(h.run), float(story.doc.uid), high, low, float(s as u64), float(e as u64), float(stamp)])
|
||||
}
|
||||
|
||||
/// The story span `d` names, when it is an object of one of `classes`.
|
||||
fn span_of(h: &Host, d: &Data, classes: &[&str]) -> std::result::Result<StorySpan, 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 {
|
||||
return Err(HostError::Type(format!("this is not a {}", classes.first().copied().unwrap_or("TextRange"))));
|
||||
};
|
||||
let story = story_of_data(h, &host_ref("Story", &[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(StorySpan { story, start, end, stamp })
|
||||
}
|
||||
|
||||
fn this_span(h: &Host, a: &[Data]) -> std::result::Result<StorySpan, HostError> {
|
||||
span_of(h, arg(a, 0), &["StoryRange"])
|
||||
}
|
||||
|
||||
/// The span and index of `r` now.
|
||||
fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc<Index>, usize, usize, u64), HostError> {
|
||||
with_doc(h, r.story.doc, |_, st| {
|
||||
let (index, stamp) = observe(h, st, r.story.id)?;
|
||||
let logs = h.dom.text.stories.logs.borrow();
|
||||
let l = logs.get(&(st.uid, r.story.id.0)).ok_or_else(|| HostError::Error(STALE_RANGE.into()))?;
|
||||
if r.stamp < l.floor || r.stamp > l.stamp {
|
||||
return Err(HostError::Error(STALE_RANGE.into()));
|
||||
}
|
||||
let (mut s, mut e) = (r.start, r.end);
|
||||
let from = l.edits.partition_point(|x| x.stamp <= r.stamp);
|
||||
for x in l.edits.range(from..) {
|
||||
let moved = |v: usize| v - x.removed + x.inserted;
|
||||
s = if s <= x.at {
|
||||
s
|
||||
} else if s >= x.at + x.removed {
|
||||
moved(s)
|
||||
} else {
|
||||
x.at
|
||||
};
|
||||
// An end inside the removed text goes to the end of the new text.
|
||||
e = if e < x.at || (e == x.at && x.removed > 0) {
|
||||
e
|
||||
} else if e >= x.at + x.removed {
|
||||
moved(e)
|
||||
} else {
|
||||
x.at + x.inserted
|
||||
};
|
||||
}
|
||||
let e = e.min(index.len());
|
||||
Ok((index, s.min(e), e, stamp))
|
||||
})
|
||||
}
|
||||
|
||||
/// Records an edit the model made to the story: `removed` units at `at` replaced by `inserted`.
|
||||
/// When the text is not what that edit gives, every earlier range goes stale. The ranges of the
|
||||
/// same story read from its other frames record the edit too, when they knew the text before it.
|
||||
fn record(h: &Host, story: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
|
||||
with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let frames = charged_frames(h, st, story.id)?;
|
||||
let now = story_text(st, &frames);
|
||||
let (a, b) = (before.byte(at, false), before.byte(at + removed, true));
|
||||
let expected = before.text.len() - (b - a) + inserted.len() == now.len()
|
||||
&& now.as_bytes().starts_with(&before.text.as_bytes()[..a])
|
||||
&& now.as_bytes().ends_with(&before.text.as_bytes()[b..])
|
||||
&& now.get(a..a + inserted.len()) == Some(inserted);
|
||||
let members: HashSet<u64> = frames.iter().map(|f| f.0).collect();
|
||||
let index = Rc::new(Index::new(now));
|
||||
let inserted = inserted.encode_utf16().count();
|
||||
let mut logs = h.dom.text.stories.logs.borrow_mut();
|
||||
let mut found = false;
|
||||
for (&(uid, anchor), l) in logs.iter_mut() {
|
||||
if uid != st.uid || !members.contains(&anchor) {
|
||||
continue;
|
||||
}
|
||||
let own = anchor == story.id.0;
|
||||
let current = l.reverts == st.reverts;
|
||||
if !own {
|
||||
h.charge_call(l.index.text.len() as u64)?;
|
||||
if !expected || !current || l.index.text != before.text {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
found |= own;
|
||||
if expected && current {
|
||||
l.push(at, removed, inserted);
|
||||
} else {
|
||||
l.stamp += 1;
|
||||
l.floor = l.stamp;
|
||||
l.edits.clear();
|
||||
}
|
||||
l.index = index.clone();
|
||||
l.doc = Arc::downgrade(&st.doc);
|
||||
l.reverts = st.reverts;
|
||||
}
|
||||
if found { Ok(()) } else { Err(HostError::Error(STALE_RANGE.into())) }
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces bytes `a..b` of the story's text with `insert`, a frame at a time from the end, with
|
||||
/// `text.editRange`: the frames before the one an edit changes keep their text, so `a` stays in
|
||||
/// place while the frames after it flow again.
|
||||
fn replace(h: &Host, story: Item, a: usize, mut b: usize, insert: &str) -> std::result::Result<(), HostError> {
|
||||
loop {
|
||||
let spans: Vec<(NodeId, usize, usize)> = with_doc(h, story.doc, |_, st| {
|
||||
if text_of(st, story.id).is_none() {
|
||||
return Err(HostError::Error(STALE_STORY.into()));
|
||||
}
|
||||
let mut at = 0;
|
||||
let spans = charged_frames(h, st, story.id)?
|
||||
.into_iter()
|
||||
.map(|f| {
|
||||
let n: usize = text_of(st, f).map_or(0, |t| t.runs.iter().map(|r| r.text.len()).sum());
|
||||
at += n;
|
||||
(f, at - n, at)
|
||||
})
|
||||
.collect();
|
||||
Ok(spans)
|
||||
})?;
|
||||
let target =
|
||||
if b > a { spans.iter().find(|(_, x, y)| *x < b && b <= *y) } else { spans.iter().find(|(_, x, y)| *x < a && a <= *y).or(spans.first()) };
|
||||
let Some(&(f, x, _)) = target else { return Err(HostError::Error(STALE_RANGE.into())) };
|
||||
let item = Item { doc: story.doc, id: f };
|
||||
if x <= a {
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": a - x, "end": b - x, "insert": insert}))?;
|
||||
return Ok(());
|
||||
}
|
||||
edit_item(h, item, "text.editRange", &json!({"id": f.0, "start": 0, "end": b - x, "insert": ""}))?;
|
||||
b = x;
|
||||
}
|
||||
}
|
||||
|
||||
fn write_contents(h: &Host, r: StorySpan, 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 (index, s, e, _) = resolve(h, r)?;
|
||||
let (a, b) = (index.byte(s, false), index.byte(e, true));
|
||||
if index.text[a..b] == insert {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
|
||||
replace(h, r.story, a, b, &insert)?;
|
||||
record(h, r.story, &index, s, e - s, &insert)?;
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn span_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let (x, y) = (index.byte(s, false), index.byte(e, true));
|
||||
Ok(text(to_script(&index.text[x..y])))
|
||||
}
|
||||
|
||||
fn span_set_contents(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, arg(a, 1))
|
||||
}
|
||||
|
||||
fn span_remove(h: &Host, a: &[Data]) -> Answer {
|
||||
write_contents(h, this_span(h, a)?, &text(""))
|
||||
}
|
||||
|
||||
fn span_start(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, _, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(s as u64)))
|
||||
}
|
||||
|
||||
fn span_end(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float(e as u64)))
|
||||
}
|
||||
|
||||
fn span_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
Ok(num(float((e - s) as u64)))
|
||||
}
|
||||
|
||||
fn span_story(h: &Host, a: &[Data]) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(story_ref(h, r.story))
|
||||
}
|
||||
|
||||
fn span_paragraph_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (index, s, e, _) = resolve(h, this_span(h, a)?)?;
|
||||
let p = touched(&index.paras, s, e).next().and_then(|i| index.paras.get(i)).map_or(0, |(x, y)| y - x);
|
||||
Ok(num(float(p as u64)))
|
||||
}
|
||||
|
||||
fn span_part(h: &Host, a: &[Data], class: &str) -> Answer {
|
||||
let r = this_span(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, class))
|
||||
}
|
||||
|
||||
fn span_characters(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryCharacters")
|
||||
}
|
||||
|
||||
fn span_words(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryWords")
|
||||
}
|
||||
|
||||
fn span_paragraphs(h: &Host, a: &[Data]) -> Answer {
|
||||
span_part(h, a, "StoryParagraphs")
|
||||
}
|
||||
|
||||
fn this_part(h: &Host, a: &[Data]) -> std::result::Result<(StorySpan, Part), HostError> {
|
||||
let part = STORY_PARTS.iter().find(|(c, _)| handle_of(arg(a, 0), c).is_some()).map(|(_, p)| *p);
|
||||
let part = part.ok_or_else(|| HostError::Type("this is not a collection of text".into()))?;
|
||||
Ok((span_of(h, arg(a, 0), &STORY_PARTS.map(|(c, _)| c))?, part))
|
||||
}
|
||||
|
||||
fn part_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
resolve(h, r)?;
|
||||
Ok(text(match part {
|
||||
Part::Characters => "Characters",
|
||||
Part::Words => "Words",
|
||||
Part::Paragraphs => "Paragraphs",
|
||||
}))
|
||||
}
|
||||
|
||||
fn span_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
resolve(h, this_span(h, a)?)?;
|
||||
Ok(text("TextRange"))
|
||||
}
|
||||
|
||||
fn story_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_story(h, a)?;
|
||||
Ok(text("Story"))
|
||||
}
|
||||
|
||||
fn part_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let (index, s, e, _) = resolve(h, r)?;
|
||||
Ok(num(float(part_spans(&index, part, s, e).0.len() as u64)))
|
||||
}
|
||||
|
||||
fn part_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, _) = this_part(h, a)?;
|
||||
let (_, s, e, stamp) = resolve(h, r)?;
|
||||
Ok(span_ref(h, r.story, s, e, stamp, "StoryRange"))
|
||||
}
|
||||
|
||||
fn part_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let (r, part) = this_part(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let (index, s, e, stamp) = resolve(h, r)?;
|
||||
let (items, spans) = part_spans(&index, part, s, e);
|
||||
let Some(k) = items.start.checked_add(i).filter(|k| *k < items.end) else { return Ok(Data::Undefined) };
|
||||
let span = match spans {
|
||||
None => index.char_span(k),
|
||||
Some(list) => list.get(k).copied(),
|
||||
};
|
||||
Ok(span.map_or(Data::Undefined, |(x, y)| span_ref(h, r.story, x, y, stamp, "StoryRange")))
|
||||
}
|
||||
|
||||
// ---- Stories ----
|
||||
|
||||
fn doc_stories_impl(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = doc_of(h, arg(a, 0), "Document")?;
|
||||
Ok(host_ref("Stories", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
/// `document.stories`.
|
||||
pub(in crate::script::dom) fn doc_stories(link: &Link) -> HostMember {
|
||||
get(link, doc_stories_impl)
|
||||
}
|
||||
|
||||
/// The first frame of each story of the document in paint order, kept while the document is
|
||||
/// unchanged.
|
||||
fn heads(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
|
||||
if let Some((uid, doc, ids)) = &*h.dom.text.stories.list.borrow()
|
||||
&& *uid == st.uid
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
return Ok(ids.clone());
|
||||
}
|
||||
let ids = frame_ids(h, st);
|
||||
h.charge_call(ids.len() as u64 + st.doc.text_threads.iter().map(|t| t.len() as u64).sum::<u64>())?;
|
||||
// A frame listed by an earlier thread belongs to that one, as `story_of` finds it.
|
||||
let (mut threaded, mut first) = (HashSet::new(), HashSet::new());
|
||||
let mut seen = HashSet::new();
|
||||
for thread in &st.doc.text_threads {
|
||||
let live: Vec<NodeId> = thread.iter().copied().filter(|f| threadable(st, *f) && seen.insert(*f)).collect();
|
||||
if live.len() >= 2 {
|
||||
first.insert(live[0]);
|
||||
threaded.extend(live);
|
||||
}
|
||||
}
|
||||
let heads: Vec<NodeId> = ids.iter().copied().filter(|id| !threaded.contains(id) || first.contains(id)).collect();
|
||||
let heads = Rc::new(heads);
|
||||
*h.dom.text.stories.list.borrow_mut() = Some((st.uid, Arc::downgrade(&st.doc), heads.clone()));
|
||||
Ok(heads)
|
||||
}
|
||||
|
||||
fn stories_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Stories")
|
||||
}
|
||||
|
||||
fn stories_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let n = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.len()))?;
|
||||
Ok(num(float(n as u64)))
|
||||
}
|
||||
|
||||
fn stories_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
stories_doc(h, a)?;
|
||||
Ok(text("Stories"))
|
||||
}
|
||||
|
||||
fn stories_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn stories_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
|
||||
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
|
||||
let id = with_doc(h, doc, |_, st| heads(h, st).map(|l| l.get(i).copied()))?;
|
||||
Ok(id.map_or(Data::Undefined, |id| story_ref(h, Item { doc, id })))
|
||||
}
|
||||
|
||||
/// `stories.index(key)`: by number, or by the name of a story's first frame.
|
||||
fn stories_index(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = stories_doc(h, a)?;
|
||||
match arg(a, 1) {
|
||||
Data::Number(_) => match stories_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
Data::String(name) => {
|
||||
let id = with_doc(h, doc, |_, st| {
|
||||
let list = heads(h, st)?;
|
||||
h.charge_call(list.len() as u64)?;
|
||||
Ok::<_, HostError>(list.iter().copied().find(|i| st.doc.node(*i).and_then(|n| n.name.as_deref()) == Some(name.as_str())))
|
||||
})?;
|
||||
id.map(|id| story_ref(h, Item { doc, id })).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- classes ----
|
||||
|
||||
/// A member of the range of a story of two or more frames that is not available yet: reading or
|
||||
/// assigning it throws, after the check that the range is still there, and `reflect` leaves it out.
|
||||
fn range_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("TextRange.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
resolve(&h, this_span(&h, &a)?)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
|
||||
/// that the story is still there, and `reflect` leaves it out.
|
||||
fn story_later(link: &Link, name: &'static str) -> Described {
|
||||
let message = format!("Story.{name} is not available yet");
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |a: Vec<Data>| {
|
||||
let h = current(&l)?;
|
||||
h.charge_call(16)?;
|
||||
this_story(&h, &a)?;
|
||||
Err(HostError::Error(message.clone()))
|
||||
});
|
||||
(name.to_string(), HostMember::Unavailable(f), MemberInfo { unavailable: true, ..MemberInfo::default() })
|
||||
}
|
||||
|
||||
/// The members of `TextFrame` this module adds.
|
||||
pub(super) fn frame_members(l: &Link) -> Vec<Described> {
|
||||
named(vec![
|
||||
("nextFrame", property(l, next_frame, set_next_frame), typed("TextFrame")),
|
||||
("previousFrame", property(l, previous_frame, set_previous_frame), typed("TextFrame")),
|
||||
("story", get(l, frame_story), typed("Story")),
|
||||
])
|
||||
}
|
||||
|
||||
/// `TextRange.story`.
|
||||
pub(super) fn range_member(l: &Link) -> Described {
|
||||
("story".into(), get(l, range_story), typed("Story"))
|
||||
}
|
||||
|
||||
/// `Story`, `Stories` and the range and collections of the text of a story of two or more frames.
|
||||
pub(super) fn classes(l: &Link) -> Vec<HostClass> {
|
||||
let collection = |t: &str| MemberInfo { collection: true, ..typed(t) };
|
||||
let mut story = named(vec![
|
||||
("typename", get(l, story_typename), typed("string")),
|
||||
("parent", get(l, story_parent), typed("Document")),
|
||||
("length", get(l, story_length), typed("number")),
|
||||
("textFrames", get(l, story_frames), typed("Array")),
|
||||
("textRange", get(l, story_text_range), typed("*")),
|
||||
("characters", get(l, story_characters), collection("*")),
|
||||
("words", get(l, story_words), collection("*")),
|
||||
("paragraphs", get(l, story_paragraphs), collection("*")),
|
||||
]);
|
||||
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
|
||||
let mut range = named(vec![
|
||||
("typename", get(l, span_typename), typed("string")),
|
||||
("parent", get(l, span_story), typed("Story")),
|
||||
("story", get(l, span_story), typed("Story")),
|
||||
("contents", property(l, span_contents, span_set_contents), typed("string")),
|
||||
("start", read_only(l, span_start, "TextRange", "start"), typed("number")),
|
||||
("end", read_only(l, span_end, "TextRange", "end"), typed("number")),
|
||||
("characterOffset", read_only(l, span_start, "TextRange", "characterOffset"), typed("number")),
|
||||
("length", read_only(l, span_length, "TextRange", "length"), typed("number")),
|
||||
("characters", get(l, span_characters), collection("StoryCharacters")),
|
||||
("words", get(l, span_words), collection("StoryWords")),
|
||||
("paragraphs", get(l, span_paragraphs), collection("StoryParagraphs")),
|
||||
("getParagraphLength", method(l, span_paragraph_length), returns("number", &[])),
|
||||
("remove", method(l, span_remove), returns("undefined", &[])),
|
||||
]);
|
||||
range.extend(
|
||||
[
|
||||
"lines",
|
||||
"insertionPoints",
|
||||
"textRanges",
|
||||
"characterAttributes",
|
||||
"paragraphAttributes",
|
||||
"kerning",
|
||||
"characterStyles",
|
||||
"paragraphStyles",
|
||||
"textSelection",
|
||||
"changeCaseTo",
|
||||
"select",
|
||||
"deSelect",
|
||||
"duplicate",
|
||||
"move",
|
||||
"getTextRunLength",
|
||||
"getLocalCharOverridesJSON",
|
||||
"getLocalParaOverridesJSON",
|
||||
]
|
||||
.into_iter()
|
||||
.chain(ATTRS.iter().map(|(n, _)| *n))
|
||||
.map(|m| range_later(l, m)),
|
||||
);
|
||||
let part = |name: &'static str| {
|
||||
class(
|
||||
name,
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, part_typename), typed("string")),
|
||||
("length", get(l, part_length), typed("number")),
|
||||
("parent", get(l, part_parent), typed("StoryRange")),
|
||||
]),
|
||||
Some(function(l, part_at)),
|
||||
)
|
||||
};
|
||||
vec![
|
||||
class("Story", None, story, None),
|
||||
class("StoryRange", None, range, None),
|
||||
part("StoryCharacters"),
|
||||
part("StoryWords"),
|
||||
part("StoryParagraphs"),
|
||||
class(
|
||||
"Stories",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, stories_typename), typed("string")),
|
||||
("length", get(l, stories_length), typed("number")),
|
||||
("parent", get(l, stories_parent), typed("Document")),
|
||||
("index", method(l, stories_index), returns("number", &[("itemKey", "*")])),
|
||||
]),
|
||||
Some(function(l, stories_at)),
|
||||
),
|
||||
]
|
||||
}
|
||||
@@ -187,6 +187,7 @@ mod script_run;
|
||||
mod script_scriptui;
|
||||
mod script_tags;
|
||||
mod script_text;
|
||||
mod script_threads;
|
||||
mod script_variables;
|
||||
mod script_xmp;
|
||||
mod scripts;
|
||||
|
||||
@@ -489,6 +489,30 @@ fn setting_a_ranges_length_moves_its_end_and_leaves_the_text() {
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
/// A length that ends inside a surrogate pair moves the range's end out to the end of the character.
|
||||
#[test]
|
||||
fn a_length_ending_inside_a_surrogate_pair_keeps_the_character_whole() {
|
||||
let (mut s, _) = doc_with("a\u{1F600}b");
|
||||
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.length = 2; vc.log([r.length, r.end, r.contents]);");
|
||||
assert_eq!(out, vec![json!([3, 3, "a\u{1F600}"])]);
|
||||
}
|
||||
|
||||
/// `textFrames.removeAll()` deletes nothing when type is on a locked artboard.
|
||||
#[test]
|
||||
fn remove_all_type_refuses_type_on_a_locked_artboard() {
|
||||
let (mut s, id) = doc_with("kept");
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
|
||||
assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", id.0)), "{e}");
|
||||
assert!(s.active().unwrap().doc.node(id).is_some());
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collections_of_text_add_words_characters_and_paragraphs() {
|
||||
let cases = [
|
||||
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Threaded type in the script object model: `nextFrame`, `previousFrame`, `story`,
|
||||
//! `document.stories`, and the text of a story of several frames.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
fn new_doc() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
/// Area type `width` × `height` at `x` holding `text`.
|
||||
fn area(s: &mut Session, x: f64, width: f64, height: f64, text: &str) -> NodeId {
|
||||
let r = s.execute("text.create", &json!({"x": x, "y": 10, "text": text, "size": 12, "area": {"width": width, "height": height}})).unwrap();
|
||||
NodeId(r["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn plain(s: &Session, id: NodeId) -> String {
|
||||
match &s.active().unwrap().doc.node(id).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
fn threads(s: &Session) -> Vec<Vec<NodeId>> {
|
||||
s.active().unwrap().doc.text_threads.clone()
|
||||
}
|
||||
|
||||
/// The text of every frame of the document's threads, in thread order.
|
||||
fn story(s: &Session, frames: &[NodeId]) -> String {
|
||||
frames.iter().map(|f| plain(s, *f)).collect()
|
||||
}
|
||||
|
||||
/// Two area frames threaded into one story whose text starts in the first, one line high, and
|
||||
/// flows on into the second.
|
||||
fn threaded(text: &str) -> (Session, NodeId, NodeId) {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 90.0, 18.0, text);
|
||||
let b = area(&mut s, 150.0, 200.0, 200.0, "");
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
const STORY: &str = "alpha beta gamma\ndelta \u{1F600}";
|
||||
|
||||
#[test]
|
||||
fn stories_list_one_story_for_each_thread_and_each_frame_in_none() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
area(&mut s, 400.0, 120.0, 40.0, "Alone");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, st = d.stories[1];\
|
||||
vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\
|
||||
vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\
|
||||
vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\
|
||||
vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\
|
||||
d.textFrames.add(); vc.log(d.stories.length);\
|
||||
vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\
|
||||
vc.log(d.textFrames[1].story.textFrames[0].contents);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(2),
|
||||
json!("Story"),
|
||||
json!(2),
|
||||
json!(true),
|
||||
json!(true),
|
||||
json!("Alone"),
|
||||
json!(1),
|
||||
json!(3),
|
||||
json!("Document"),
|
||||
json!("Document"),
|
||||
json!("Stories"),
|
||||
json!("Alone")
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_counts_utf16_units_across_its_frames() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
assert!(!first.is_empty() && !second.is_empty(), "the story flows through both frames: {first:?} {second:?}");
|
||||
assert_eq!(first.clone() + &second, STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, r = st.textRange;\
|
||||
vc.log(st.length); vc.log(r.length); vc.log(r.contents); vc.log(r.typename);\
|
||||
vc.log(st.characters.length); vc.log(st.words.length); vc.log(st.paragraphs.length);\
|
||||
vc.log(st.paragraphs[0].contents); vc.log(st.words[4].contents); vc.log(st.words[4].start);\
|
||||
vc.log(r.paragraphs[1].getParagraphLength()); vc.log(r.story.length);\
|
||||
vc.log(app.activeDocument.textFrames[0].textRange.length < r.length);",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!(25),
|
||||
json!(25),
|
||||
json!("alpha beta gamma\rdelta \u{1F600}"),
|
||||
json!("TextRange"),
|
||||
json!(24),
|
||||
json!(5),
|
||||
json!(2),
|
||||
json!("alpha beta gamma\r"),
|
||||
json!("\u{1F600}"),
|
||||
json!(23),
|
||||
json!(8),
|
||||
json!(25),
|
||||
json!(true)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// The members a long story's range does not have yet throw that they are not available, and
|
||||
/// first that a range that went stale is stale.
|
||||
#[test]
|
||||
fn a_story_range_names_the_members_it_does_not_have_yet() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange;\
|
||||
try { r.characterAttributes; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { r.size = 20; } catch (e) { vc.log(String(e.message)); }\
|
||||
try { app.activeDocument.textFrames[0].story.lines; } catch (e) { vc.log(String(e.message)); }",
|
||||
);
|
||||
assert_eq!(
|
||||
out,
|
||||
vec![
|
||||
json!("TextRange.characterAttributes is not available yet"),
|
||||
json!("TextRange.size is not available yet"),
|
||||
json!("Story.lines is not available yet")
|
||||
]
|
||||
);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.characterAttributes;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.typename;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
/// Ranges of one story read from different frames keep their places through each other's edits.
|
||||
#[test]
|
||||
fn story_ranges_read_from_different_frames_follow_each_others_edits() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, x = t[0].story.words[0], y = t[1].story.words[1];\
|
||||
x.contents = 'Q'; vc.log(y.contents); vc.log(y.start); y.contents = 'B'; vc.log(x.contents);\
|
||||
vc.log(t[1].story.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("beta"), json!(2), json!("Q"), json!("Q B gamma\rdelta \u{1F600}")]);
|
||||
}
|
||||
|
||||
/// A story range that an edit covers holds the edit's new text, as a frame's range does.
|
||||
#[test]
|
||||
fn a_story_range_an_edit_covers_holds_the_new_text() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, w = st.words[1], p = st.paragraphs[1];\
|
||||
st.textRange.contents = 'Z'; vc.log(w.contents); vc.log(p.contents); vc.log(w.typename); vc.log(st.words.typename);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("Z"), json!("Z"), json!("TextRange"), json!("Words")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_edit_across_frames_reflows_in_one_undo_step() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.textFrames[0].story, frame = app.activeDocument.textFrames[1].textRange;\
|
||||
var p = st.paragraphs[0], tail = st.paragraphs[1];\
|
||||
p.contents = 'X\\r'; vc.log(st.textRange.contents); vc.log(tail.contents); vc.log(tail.start);\
|
||||
try { frame.contents; } catch (e) { vc.log(String(e.message)); }\
|
||||
st.words[2].remove(); vc.log(st.textRange.contents);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("X\rdelta \u{1F600}"), json!("delta \u{1F600}"), json!(2), json!("Stale text range"), json!("X\rdelta ")]);
|
||||
assert_eq!(story(&s, &[a, b]), "X\ndelta ");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(story(&s, &[a, b]), STORY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_is_stale_after_another_change_to_the_story() {
|
||||
let (mut s, _, b) = threaded(STORY);
|
||||
let message = failure(
|
||||
&mut s,
|
||||
&format!(
|
||||
"var r = app.activeDocument.textFrames[0].story.textRange; vc.run('text.editRange', {{id: {}, start: 0, end: 0, insert: 'z'}}); r.contents;",
|
||||
b.0
|
||||
),
|
||||
);
|
||||
assert!(message.contains("Stale text range"), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_story_range_made_before_file_revert_is_stale_even_when_the_text_is_the_same() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let path = std::env::temp_dir().join(format!("vc-story-revert-{}.vectorcraft", std::process::id()));
|
||||
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var r = app.activeDocument.textFrames[0].story.words[1];\
|
||||
vc.run('shape.rectangle', {x: 1, y: 1, width: 5, height: 5}); vc.run('file.revert', {});\
|
||||
var st = app.activeDocument.textFrames[0].story;\
|
||||
vc.log(st.textFrames.length); vc.log(st.textRange.contents);\
|
||||
try { vc.log(r.contents); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(st.words[1].contents);",
|
||||
);
|
||||
let _ = std::fs::remove_file(&path);
|
||||
assert_eq!(out[0], json!(2), "the reverted file keeps the thread");
|
||||
assert_eq!(out[1], json!("alpha beta gamma\rdelta \u{1F600}"), "the reverted file holds the same text");
|
||||
assert!(out[2].as_str().is_some_and(|m| m.contains("Stale text range")), "{out:?}");
|
||||
assert_eq!(out[3], json!("beta"), "a range made after the revert reads the reverted text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "First story.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Second.");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.set", &json!({"ids": [p.0]})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\
|
||||
t[2].nextFrame = t[1];",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]);
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
assert_eq!(story(&s, &[a, b]), "First story.Second.");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert_eq!(s.active().unwrap().selection.objects.to_vec(), vec![p]);
|
||||
// previousFrame links the other way.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), ("First story.".into(), "Second.".into()));
|
||||
log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];");
|
||||
assert_eq!(threads(&s), vec![vec![b, a]]);
|
||||
assert_eq!(story(&s, &[b, a]), "Second.First story.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_breaks_the_link_and_each_frame_keeps_its_text() {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let (first, second) = (plain(&s, a), plain(&s, b));
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\
|
||||
vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\
|
||||
t[1].nextFrame = null;",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(1), json!(null)]);
|
||||
assert!(threads(&s).is_empty());
|
||||
assert_eq!((plain(&s, a), plain(&s, b)), (first, second));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![vec![a, b]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn area_and_path_text_thread_the_new_frame_to_a_base_frame() {
|
||||
let mut s = new_doc();
|
||||
let base = area(&mut s, 10.0, 120.0, 40.0, "Base text that is long enough to flow on into the frames made after it.");
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 350, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 300}, {"x": 400, "y": 320}], "closed": false})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems, base = d.textFrames[0];\
|
||||
var after = d.textFrames.areaText(p[2], undefined, base);\
|
||||
var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\
|
||||
var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\
|
||||
vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]);
|
||||
let t = threads(&s);
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0][1], base, "the frame made with postFix false comes before the base frame: {t:?}");
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_base_frame_is_refused_before_a_frame_is_made() {
|
||||
let mut s = new_doc();
|
||||
s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 120, "height": 60})).unwrap();
|
||||
let count = |s: &Session| s.active().unwrap().doc.node_count();
|
||||
let (n, before) = (count(&s), undo_steps(&s));
|
||||
let d = "var d = app.activeDocument, p = d.pageItems;";
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame"));
|
||||
assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix"));
|
||||
assert_eq!((count(&s), undo_steps(&s)), (n, before));
|
||||
}
|
||||
|
||||
/// A base frame given with a path inside a compound path is refused before the path is turned
|
||||
/// into type, so a script that catches the error finds the path as it was.
|
||||
#[test]
|
||||
fn a_base_frame_for_a_path_in_a_compound_path_leaves_the_path() {
|
||||
let mut s = new_doc();
|
||||
area(&mut s, 10.0, 120.0, 60.0, "Base.");
|
||||
let r1 = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
let r2 = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [r1, r2]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = null;\
|
||||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') { p = d.pageItems[i]; break; } }\
|
||||
try { d.textFrames.areaText(p, undefined, d.textFrames[0]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: type made from a path inside a compound path cannot be threaded"), json!("PathItem"), json!(1)]);
|
||||
assert_eq!(undo_steps(&s), before);
|
||||
}
|
||||
|
||||
/// A thread of `a` and `b`, a third area frame `c`, and point type `p`; what the document holds
|
||||
/// now, to check that a refused change left it alone.
|
||||
fn three() -> (Session, [NodeId; 4]) {
|
||||
let (mut s, a, b) = threaded(STORY);
|
||||
let c = area(&mut s, 400.0, 120.0, 40.0, "Third");
|
||||
let p = NodeId(s.execute("text.create", &json!({"x": 20, "y": 300, "text": "Point"})).unwrap()["id"].as_u64().unwrap());
|
||||
(s, [a, b, c, p])
|
||||
}
|
||||
|
||||
fn unchanged(s: &Session, ids: &[NodeId], before: &(Vec<Vec<NodeId>>, Vec<String>, usize)) {
|
||||
assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::<Vec<_>>(), undo_steps(s)), *before);
|
||||
}
|
||||
|
||||
fn state(s: &Session, ids: &[NodeId]) -> (Vec<Vec<NodeId>>, Vec<String>, usize) {
|
||||
(threads(s), ids.iter().map(|i| plain(s, *i)).collect(), undo_steps(s))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_to_the_frame_itself_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[2];");
|
||||
assert!(m.contains("nextFrame") && m.contains("itself"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_that_makes_a_loop_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_into_the_middle_of_a_story_is_refused() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];");
|
||||
assert!(m.contains("already has a previous frame"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];");
|
||||
assert!(m.contains("already has a next frame"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn point_type_and_other_values_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];");
|
||||
assert!(m.contains("only area type"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;");
|
||||
assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}");
|
||||
let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;");
|
||||
assert!(m.contains("TextFrame or null"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hidden_or_locked_frame_in_either_story_stops_a_link() {
|
||||
let (mut s, ids) = three();
|
||||
log(&mut s, "app.activeDocument.textFrames[2].locked = true;");
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;");
|
||||
assert!(m.contains("hidden or locked"), "{m}");
|
||||
// A script that catches the error goes on, and the links stay as they were.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = app.activeDocument.textFrames; try { t[2].nextFrame = t[1]; } catch (e) { vc.log([e.name, /hidden or locked/.test(e.message)]); }\
|
||||
vc.log(t[2].nextFrame === null);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(["Error", true]), json!(true)]);
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// Reading a story whose text is larger than what one run may pass to and from the host stops
|
||||
/// the run when the story's text is joined.
|
||||
#[test]
|
||||
fn joining_a_storys_text_counts_toward_the_runs_data_limit() {
|
||||
let text = "word ".repeat(40_000);
|
||||
let (mut s, _, _) = threaded(&text);
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(100_000)));
|
||||
let r = run(&mut s, "vc.log(app.activeDocument.stories[0].length);");
|
||||
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
|
||||
let e = r.map(|r| panic!("the run read a 200 KB story within a 100 KB limit: {r}")).unwrap_err().to_string();
|
||||
assert!(e.contains("more data to and from commands"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_frame_of_another_document_cannot_be_linked() {
|
||||
let (mut s, ids) = three();
|
||||
let before = state(&s, &ids);
|
||||
s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap();
|
||||
area(&mut s, 10.0, 100.0, 40.0, "Elsewhere");
|
||||
s.execute("shape.rectangle", &json!({"x": 150, "y": 10, "width": 80, "height": 60})).unwrap();
|
||||
let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];");
|
||||
assert!(m.contains("different documents"), "{m}");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.documents[0], p = d.pageItems[0];\
|
||||
try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\
|
||||
vc.log(p.typename); vc.log(d.textFrames.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deleted_frame_makes_its_story_and_links_stale() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;");
|
||||
assert!(m.contains("Stale story"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;");
|
||||
assert!(m.contains("Stale page item"), "{m}");
|
||||
let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;");
|
||||
assert!(m.contains("Stale text range"), "{m}");
|
||||
// A story read from a frame that stays follows it when its link is broken.
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stories_refuse_bad_keys_and_huge_numbers() {
|
||||
let (mut s, _, _) = threaded(STORY);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories; vc.log(st[1e300] === undefined); vc.log(st[-1] === undefined); vc.log(st[0.5] === undefined);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(true), json!(true)]);
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index(1e20);").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index('nobody');").contains("Not found"));
|
||||
assert!(failure(&mut s, "app.activeDocument.stories.index({});").contains("TypeError"));
|
||||
log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';");
|
||||
assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_story_walks_to_its_end_and_refuses_a_loop() {
|
||||
let mut s = new_doc();
|
||||
let ids: Vec<NodeId> = (0..120).map(|i| area(&mut s, f64::from(i % 12) * 45.0, 40.0, 20.0, if i == 0 { STORY } else { "" })).collect();
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), vec![ids.clone()]);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(f.story.textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(120), json!(120), json!(1)]);
|
||||
let before = state(&s, &ids);
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[t.length - 1].nextFrame = t[0];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[0].previousFrame = t[t.length - 1];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
let m = failure(&mut s, "var t = app.activeDocument.stories[0].textFrames; t[60].nextFrame = t[30];");
|
||||
assert!(m.contains("loop"), "{m}");
|
||||
unchanged(&s, &ids, &before);
|
||||
}
|
||||
|
||||
/// A stored thread that lists a frame twice, as a file can, is a story that visits each frame
|
||||
/// once, so a walk along `nextFrame` ends.
|
||||
#[test]
|
||||
fn a_thread_listing_a_frame_twice_is_walked_once() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b, a]];
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, f = d.stories[0].textFrames[0], n = 1; while (f.nextFrame && n < 10) { f = f.nextFrame; n++; } \
|
||||
vc.log(n); vc.log(d.stories[0].textFrames.length); vc.log(d.stories.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2), json!(1)]);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
assert!(threads(&s).is_empty());
|
||||
}
|
||||
|
||||
/// When a frame is listed in two threads, a story read from a frame of the second thread reads
|
||||
/// that thread's text, not the text of the story read before it from a shared frame.
|
||||
#[test]
|
||||
fn stories_of_threads_that_share_a_frame_keep_their_own_text() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
let c = area(&mut s, 300.0, 120.0, 60.0, "Three!");
|
||||
std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).text_threads = vec![vec![a, b], vec![b, c]];
|
||||
let out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);");
|
||||
let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count());
|
||||
assert_ne!(ab, bc);
|
||||
assert_eq!(out, vec![json!(ab), json!(bc)]);
|
||||
}
|
||||
|
||||
/// A story and its range keep the exact id of the frame they were read from, also past 2^53.
|
||||
#[test]
|
||||
fn a_story_read_from_a_frame_with_a_large_id_stays_with_that_frame() {
|
||||
let mut s = new_doc();
|
||||
// The second frame's id, 2^53 + 1, is not exact as a number.
|
||||
let big = 1u64 << 53;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
assert_eq!((a.0, b.0), (big, big + 1));
|
||||
s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var st = app.activeDocument.stories[0].textFrames[1].story, r = st.textRange; vc.log(r.contents);\
|
||||
st.textFrames[0].nextFrame = null; vc.log(st.textFrames.length); vc.log(st.textFrames[0].contents); vc.log(st.typename);",
|
||||
);
|
||||
// The whole story flows into the first frame, so the second is empty once the link is broken.
|
||||
assert_eq!(out, vec![json!("One.Two."), json!(1), json!(""), json!("Story")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_neighbor_links_and_breaks_frames_by_id_without_a_selection() {
|
||||
let mut s = new_doc();
|
||||
let a = area(&mut s, 10.0, 120.0, 60.0, "One.");
|
||||
let b = area(&mut s, 150.0, 120.0, 60.0, "Two.");
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let before = undo_steps(&s);
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": b.0})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0, b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": b.0, "side": "previous", "neighbor": a.0})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 1);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[a.0], [b.0]]}));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": a.0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r["changed"], json!(false));
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
for bad in [
|
||||
json!({"id": a.0, "side": "up", "neighbor": b.0}),
|
||||
json!({"id": a.0, "side": "next"}),
|
||||
json!({"id": a.0, "side": "next", "neighbor": 999_999}),
|
||||
] {
|
||||
assert!(s.execute("text.thread.setNeighbor", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), before + 2);
|
||||
}
|
||||
|
||||
/// Breaking a link where a paragraph starts makes the frames after it a story whose numbered
|
||||
/// paragraphs count from 1, also when that story keeps two frames.
|
||||
#[test]
|
||||
fn a_break_at_a_paragraph_start_numbers_the_later_story_from_one() {
|
||||
let mut s = new_doc();
|
||||
let items = (1..=12).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let ids = [area(&mut s, 10.0, 150.0, 60.0, &items), area(&mut s, 200.0, 150.0, 60.0, ""), area(&mut s, 400.0, 150.0, 200.0, "")];
|
||||
s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "list": "number"})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let numbers = |s: &Session, id: NodeId| {
|
||||
let Some(NodeKind::Text(t)) = s.active().unwrap().doc.node(id).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(!t.first_para_continues, "every frame starts a paragraph");
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let first = numbers(&s, ids[0]);
|
||||
assert!(!first.is_empty() && !numbers(&s, ids[1]).is_empty(), "the first two frames hold items");
|
||||
assert_ne!(numbers(&s, ids[1]).first().map(String::as_str), Some("1."));
|
||||
let r = s.execute("text.thread.setNeighbor", &json!({"id": ids[0].0, "side": "next", "neighbor": null})).unwrap();
|
||||
assert_eq!(r, json!({"changed": true, "threads": [[ids[0].0], [ids[1].0, ids[2].0]]}));
|
||||
let later = [numbers(&s, ids[1]), numbers(&s, ids[2])].concat();
|
||||
let expected: Vec<String> = (1..=later.len()).map(|n| format!("{n}.")).collect();
|
||||
assert_eq!(later, expected, "the later story counts from 1");
|
||||
assert_eq!(numbers(&s, ids[0]), first);
|
||||
}
|
||||
@@ -107,7 +107,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"Document.prototype.",
|
||||
"activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \
|
||||
groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \
|
||||
rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames toString \
|
||||
rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= tags textFrames toString \
|
||||
typename views width",
|
||||
),
|
||||
("Views.", "prototype"),
|
||||
@@ -166,7 +166,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
contents contents= convertAreaObjectToPointObject convertPointObjectToAreaObject createOutline endTValue endTValue= \
|
||||
insertionPoints insertionPoints= kind lines lines= matrix matrix= nextFrame nextFrame= opticalAlignment \
|
||||
opticalAlignment= orientation orientation= paragraphs previousFrame previousFrame= rowCount rowCount= rowGutter \
|
||||
rowGutter= startTValue startTValue= story story= textPath textPath= textRange textRanges textRanges= textSelection \
|
||||
rowGutter= startTValue startTValue= story textPath textPath= textRange textRanges textRanges= textSelection \
|
||||
textSelection= words",
|
||||
),
|
||||
("TextRange.", "prototype"),
|
||||
@@ -179,7 +179,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
|
||||
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
|
||||
spaceBefore spaceBefore= start start= story story= strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
|
||||
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
|
||||
verticalScale= words",
|
||||
),
|
||||
@@ -209,6 +209,34 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
("Justification.", "CENTER FULLJUSTIFY FULLJUSTIFYLASTLINECENTER FULLJUSTIFYLASTLINELEFT FULLJUSTIFYLASTLINERIGHT LEFT RIGHT"),
|
||||
("TextOrientation.", "HORIZONTAL VERTICAL"),
|
||||
("TextType.", "AREATEXT PATHTEXT POINTTEXT"),
|
||||
("", "Stories Story StoryCharacters StoryParagraphs StoryRange StoryWords"),
|
||||
("Stories.", "prototype"),
|
||||
("Stories.prototype.", "constructor index length parent typename"),
|
||||
("Story.", "prototype"),
|
||||
(
|
||||
"Story.prototype.",
|
||||
"characters constructor insertionPoints insertionPoints= length lines lines= paragraphs parent textFrames textRange \
|
||||
textRanges textRanges= textSelection textSelection= typename words",
|
||||
),
|
||||
("StoryRange.", "prototype"),
|
||||
(
|
||||
"StoryRange.prototype.",
|
||||
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
|
||||
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
|
||||
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
|
||||
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
|
||||
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
|
||||
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
|
||||
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
|
||||
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
|
||||
underline underline= verticalScale verticalScale= words",
|
||||
),
|
||||
("StoryCharacters.", "prototype"),
|
||||
("StoryCharacters.prototype.", "constructor length parent typename"),
|
||||
("StoryWords.", "prototype"),
|
||||
("StoryWords.prototype.", "constructor length parent typename"),
|
||||
("StoryParagraphs.", "prototype"),
|
||||
("StoryParagraphs.prototype.", "constructor length parent typename"),
|
||||
// Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s
|
||||
// `visibilityVariable` is in its row above.
|
||||
("", "Dataset Datasets Variable VariableKind Variables"),
|
||||
|
||||
+4
-4
@@ -846,11 +846,11 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
|
||||
|
||||
## G6 Automation and scripting
|
||||
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths, stories and threads
|
||||
of type, and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
- **Missing:** the rest of the document object model for scripts (layers, artboards, paths and the other classes)
|
||||
and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
|
||||
documents, new documents, each document's selection and its page items, its text frames with their text ranges and
|
||||
character and paragraph attributes, the installed fonts, and each document's variables, data sets and variable
|
||||
libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
character and paragraph attributes, their links to each other and the stories they form, the installed fonts, and
|
||||
each document's variables, data sets and variable libraries. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine`
|
||||
runs a script in a named engine whose globals last between runs,
|
||||
File › Scripts lists the scripts of the Scripts folder, and
|
||||
Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and
|
||||
|
||||
+44
-5
@@ -3005,8 +3005,8 @@ other files through `$`:
|
||||
`removeAll()`. `add()` makes empty point type at the origin and `pointText(anchor, orientation?)` at `anchor`, both
|
||||
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
|
||||
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`
|
||||
value; a `startTValue`, `endTValue`, `baseFrame` or `postFix` that is given throws an error that says it is not
|
||||
available yet. A `TextFrame`
|
||||
value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and
|
||||
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
|
||||
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
|
||||
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
|
||||
@@ -3058,9 +3058,36 @@ other files through `$`:
|
||||
`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.
|
||||
string runs no command. Members the help pages list that are not here, such as `TextFrame.lines`,
|
||||
`TextFrame.textPath` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`,
|
||||
`end`, `characterOffset` and `orientation` cannot be set yet.
|
||||
- Threaded type (https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/,
|
||||
https://ai-scripting.docsforadobe.dev/jsobjref/Story/, https://ai-scripting.docsforadobe.dev/jsobjref/Stories/): a
|
||||
`TextFrame` has `nextFrame` and `previousFrame`, the frames after and before it in its story (`null` at either end),
|
||||
and `story`; a `TextRange` has `story` too. Assigning `nextFrame` or `previousFrame` runs `text.thread.setNeighbor`:
|
||||
a frame links the last frame of one story to the first frame of another, whose text flows on after the first story's
|
||||
text, and `null` breaks that link, no text moving across it. `areaText(path, orientation?, baseFrame?,
|
||||
postFix?)` and `pathText(path, startTValue?, endTValue?, orientation?, baseFrame?, postFix?)` thread the new frame
|
||||
after `baseFrame`, or before it when `postFix` is false, with `text.thread.add`; `startTValue` and `endTValue` are
|
||||
not available yet. `Document.stories` lists the stories with `length`, `[i]` and `index(key)`. A `Story` has
|
||||
`parent` (its document), `length`, `textFrames` (an array of its frames in thread order), `textRange`, `characters`,
|
||||
`words` and `paragraphs`; `lines`, `insertionPoints`, `textRanges` and `textSelection` are not available yet.
|
||||
VectorCraft's own rules: point type, a frame of another document, the frame itself, a frame inside a story, a link
|
||||
that would make a loop and a story with a hidden or locked frame are refused with nothing changed, and assigning the
|
||||
link that is already there, or `null` where there is none, runs no command. `postFix` is true when it is left out,
|
||||
and a `baseFrame` given with a path inside a compound path is refused before the path is turned into type.
|
||||
`Document.stories` lists one story for each type object in no thread and one for each thread, in the order of
|
||||
their first frames in `Document.textFrames`, topmost first, and `index` with a string finds the first story whose first frame has that name. A frame that
|
||||
a stored thread lists twice is in its story once. A `Story` is
|
||||
the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is
|
||||
deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its
|
||||
frames' text in thread order, counted in UTF-16 units: its `textRange` reads and writes across the frames, and
|
||||
writing it edits the frames from the last one it reaches back to the first, inside the run's one undo step, and the
|
||||
story then flows through its frames again. Such a range has `contents`, `start`, `end`, `characterOffset`,
|
||||
`length`, `parent` and `story` (its story), `characters`, `words`, `paragraphs`, `getParagraphLength()` and
|
||||
`remove()`; its character and paragraph attributes and the other members are not available yet. It keeps its place
|
||||
through edits made through the story's ranges and throws `Stale text range` after any other change to the story's
|
||||
text and after `file.revert`.
|
||||
- A `Document` also has `variables`, `dataSets`, `activeDataset`, `variablesLocked`, `importVariables(file)` and
|
||||
`exportVariables(file)` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/). `variables`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Variables/) and `dataSets`
|
||||
@@ -13026,6 +13053,18 @@ after it (`out`). The whole story flows into the frames before the break; the fr
|
||||
threaded with each other when two or more remain, and the first of them starts a paragraph. It refuses an `id` that
|
||||
doesn't exist, a `port` other than `in` or `out`, and a side where no frame of a thread comes before or after `id`.
|
||||
|
||||
`text.thread.setNeighbor {id, side: "next" | "previous", neighbor: id | null}` is what a script's `nextFrame` and
|
||||
`previousFrame` assignments run, and needs no selection. With an id it links area type or type on a path `id` to
|
||||
`neighbor` after it (`next`) or before it (`previous`): `id` must be the last frame of its story for `next` (the first
|
||||
for `previous`) and `neighbor` the first (the last) frame of another story, and the second story's text flows on after
|
||||
the first's (one undo step, Thread Text). With `null` it breaks the link on that side, and the frames on each side
|
||||
form a story of their own (one undo step, Break Thread): no text moves across the break, and the frames after it flow
|
||||
their own text again from their first frame, which now starts a paragraph. It refuses point type and
|
||||
other art, a frame linked to itself, a link that would make a loop or go to a frame inside a story, and a story with a
|
||||
hidden or locked frame, with nothing changed. A link that is already there, or a break where there is no link, changes
|
||||
nothing and records no undo step. The selection is kept. It returns `{changed, threads}`, `threads` listing the
|
||||
stories of the frames involved after the change, a story of one frame as `[id]`.
|
||||
|
||||
`select.same.linkBlockSeries` (Select › Same › Link Block Series) selects every frame of the threads that the selected
|
||||
type objects, and the type inside selected groups, are in, in thread order, and returns `{count}`. Type in no thread
|
||||
selects itself, and other selected objects are left out. With frames of several threads selected, it selects the frames
|
||||
|
||||
+1
-1
@@ -206,7 +206,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
|
||||
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
|
||||
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items; the rest of the script document model (layers, artboards, paths, type and the other classes) and batch work remain | 18–27 |
|
||||
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and fonts, and its stories and threaded frames; the rest of the script document model (layers, artboards, paths, text lines and styles and the other classes) and batch work remain | 18–27 |
|
||||
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
|
||||
@@ -1115,7 +1115,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709).
|
||||
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
|
||||
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
|
||||
|
||||
Reference in new issue
Block a user