diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 4542b6b864..26514918aa 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -669,6 +669,7 @@ pub(super) const ALLOWED: &[&str] = &[ "text.thread.info", "text.thread.releaseSelection", "text.thread.remove", + "text.thread.setNeighbor", "text.touchType", "threeD.addGraphic", "threeD.mapArt", diff --git a/crates/engine/src/cmd/threads.rs b/crates/engine/src/cmd/threads.rs index f4f807cb15..1a79fbfbc9 100644 --- a/crates/engine/src/cmd/threads.rs +++ b/crates/engine/src/cmd/threads.rs @@ -59,6 +59,15 @@ pub fn specs() -> Vec { 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::>()).collect::>())) }), @@ -986,5 +995,111 @@ fn break_thread(s: &mut Session, p: &Value) -> Result { 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 { + 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::>()).collect::>()) +} + +/// `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 { + 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 = 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; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index d467345a2c..49ae9d1138 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1767,6 +1767,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("textFrames", text::doc_text_frames(l)), + ("stories", text::threads::doc_stories(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); document.extend( diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..822e34e954 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -44,6 +44,8 @@ use super::{ }; use crate::{DocState, Document, NodeId, NodeKind}; +pub(super) mod 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"; @@ -188,6 +190,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>>, + stories: threads::StoryState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1191,24 +1194,32 @@ 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. @@ -1462,14 +1473,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("convertAreaObjectToPointObject", method(l, frame_to_point)), ("convertPointObjectToAreaObject", method(l, frame_to_area)), ]); + frame.extend(threads::frame_members(l)); frame.extend( [ "lines", "insertionPoints", "textRanges", - "story", - "nextFrame", - "previousFrame", "textPath", "anchor", "antialias", @@ -1504,12 +1513,12 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.push(threads::range_member(l)); range.extend( [ "lines", "insertionPoints", "textRanges", - "story", "kerning", "characterStyles", "paragraphStyles", @@ -1537,7 +1546,8 @@ pub(super) fn classes(l: &Link) -> Vec { chars.extend(attr_members(l)); let mut paras = named(vec![("typename", get(l, para_attrs_typename))]); paras.extend(para_members(l)); - vec![ + let stories = threads::classes(l); + let mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1596,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(stories); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs new file mode 100644 index 0000000000..ee81129944 --- /dev/null +++ b/crates/engine/src/script/dom/text/threads.rs @@ -0,0 +1,786 @@ +//! 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 +//! , +//! and +//! 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 paint order of their first frames. `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, host_ref}; + +use super::super::{ + Answer, 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, later, method, named, num, property, text, 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, Rc>); + +/// 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>, + list: RefCell>, +} + +/// 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 { + 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, 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, 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 { + 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 { + 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, 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. +fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc, 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); + match logs.get_mut(&key) { + Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {} + Some(l) => { + let frames = charged_frames(h, st, anchor)?; + let text = story_text(st, &frames); + if l.reverts != st.reverts || text != l.index.text { + l.stamp += 1; + l.floor = l.stamp; + l.edits.clear(); + l.index = Rc::new(Index::new(text)); + } + l.doc = Arc::downgrade(&st.doc); + l.reverts = st.reverts; + } + None => { + let frames = charged_frames(h, st, anchor)?; + let index = Rc::new(Index::new(story_text(st, &frames))); + 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 { + 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 { + span_of(h, arg(a, 0), &["StoryRange"]) +} + +/// The span and index of `r` now. +fn resolve(h: &Host, r: StorySpan) -> std::result::Result<(Rc, 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 = 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>, 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::())?; + // 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 = 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 = 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_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. +fn range_later(link: &Link, name: &'static str) -> (String, HostMember) { + let message = format!("TextRange.{name} is not available yet"); + let l = link.clone(); + let f: HostFunction = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16)?; + resolve(&h, this_span(&h, &a)?)?; + Err(HostError::Error(message.clone())) + }); + (name.to_string(), HostMember::Property { get: f.clone(), set: f }) +} + +/// The members of `TextFrame` this module adds. +pub(super) fn frame_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![ + ("nextFrame", property(l, next_frame, set_next_frame)), + ("previousFrame", property(l, previous_frame, set_previous_frame)), + ("story", get(l, frame_story)), + ]) +} + +/// `TextRange.story`. +pub(super) fn range_member(l: &Link) -> (String, HostMember) { + ("story".into(), get(l, range_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 { + let mut story = named(vec![ + ("typename", get(l, story_typename)), + ("parent", get(l, story_parent)), + ("length", get(l, story_length)), + ("textFrames", get(l, story_frames)), + ("textRange", get(l, story_text_range)), + ("characters", get(l, story_characters)), + ("words", get(l, story_words)), + ("paragraphs", get(l, story_paragraphs)), + ]); + story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m))); + let mut range = named(vec![ + ("typename", get(l, span_typename)), + ("parent", get(l, span_story)), + ("story", get(l, span_story)), + ("contents", property(l, span_contents, span_set_contents)), + ("start", read_only(l, span_start, "TextRange", "start")), + ("end", read_only(l, span_end, "TextRange", "end")), + ("characterOffset", read_only(l, span_start, "TextRange", "characterOffset")), + ("length", read_only(l, span_length, "TextRange", "length")), + ("characters", get(l, span_characters)), + ("words", get(l, span_words)), + ("paragraphs", get(l, span_paragraphs)), + ("getParagraphLength", method(l, span_paragraph_length)), + ("remove", method(l, span_remove)), + ]); + 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)), ("length", get(l, part_length)), ("parent", get(l, part_parent))]), + 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)), + ("length", get(l, stories_length)), + ("parent", get(l, stories_parent)), + ("index", method(l, stories_index)), + ]), + Some(function(l, stories_at)), + ), + ] +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..c9326a496c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -179,6 +179,7 @@ mod script_include; mod script_io; mod script_run; mod script_text; +mod script_threads; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs new file mode 100644 index 0000000000..6d919a21d9 --- /dev/null +++ b/crates/engine/src/tests/script_threads.rs @@ -0,0 +1,596 @@ +//! 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 { + s.execute("script.run", &json!({"source": source, "name": "t.js"})) +} + +/// What the run logged. +fn log(s: &mut Session, source: &str) -> Vec { + let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The message of the run's failure. +fn failure(s: &mut Session, source: &str) -> String { + run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string() +} + +fn undo_steps(s: &Session) -> usize { + s.active().unwrap().history.undo.len() +} + +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> { + 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[0];\ + 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[1].textFrames[0].contents); vc.log(d.stories[1].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[2].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[0].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[0].story.textRange.contents);\ + t[0].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[0].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[1].story; t[1].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[0].nextFrame);\ + t[0].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[1], undefined, base);\ + var first = d.textFrames.areaText(p[2], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[3], 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[1], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], undefined, p[1]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[1], 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, usize)) { + assert_eq!((threads(s), ids.iter().map(|i| plain(s, *i)).collect::>(), undo_steps(s)), *before); +} + +fn state(s: &Session, ids: &[NodeId]) -> (Vec>, Vec, 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[1].nextFrame = t[0];"); + assert!(m.contains("loop"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + 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[2].nextFrame = t[1];"); + assert!(m.contains("already has a previous frame"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + 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[2].nextFrame = t[3];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + assert!(m.contains("only area type"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); + let m = failure(&mut s, "app.activeDocument.textFrames[2].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[1].locked = true;"); + let before = state(&s, &ids); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + assert!(m.contains("hidden or locked"), "{m}"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + assert!(m.contains("hidden or locked"), "{m}"); + unchanged(&s, &ids, &before); +} + +#[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"); + let m = failure(&mut s, "app.documents[0].textFrames[2].nextFrame = app.documents[1].textFrames[0];"); + assert!(m.contains("different documents"), "{m}"); + let m = failure(&mut s, "app.documents[1].textFrames.areaText(app.documents[1].pageItems[0], undefined, app.documents[0].textFrames[2]);"); + assert!(m.contains("another document") || m.contains("PathItem"), "{m}"); + 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[1], st = f.story; f.remove(); st.length;"); + assert!(m.contains("Stale story"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + assert!(m.contains("Stale page item"), "{m}"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], 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[1].story; t[0].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[0].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 = (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::>()})).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()); +} + +/// 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::>().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::>()})).unwrap(); + s.execute("text.thread.create", &json!({})).unwrap(); + s.execute("text.setFormat", &json!({"ids": ids.iter().map(|i| i.0).collect::>(), "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::>() + }; + 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 = (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); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index c7e7000f13..b638262389 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -90,7 +90,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= textFrames typename \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames typename \ views views= width", ), ("Layer.", "prototype"), @@ -135,7 +135,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"), @@ -147,7 +147,7 @@ const INSIDE: &[(&str, &str)] = &[ getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale horizontalScale= insertionPoints \ insertionPoints= kerning kerning= leading leading= length length= lines lines= move move= paragraphAttributes \ paragraphStyles paragraphStyles= paragraphs parent remove rotation rotation= select select= size size= start start= \ - story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ + story strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), ("Characters.", "prototype"), @@ -176,6 +176,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"), ]; /// The classes the host adds with nothing but a prototype and its constructor: `DocumentPreset` diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..2a6e8005f9 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -807,10 +807,10 @@ 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, and the installed fonts. 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, and the installed fonts. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index a75c5386f5..2f81d1838d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2728,9 +2728,36 @@ app through the global object `vc`, and writes to the Script Console and runs ot the auto leading. A bad value throws an error and changes nothing. Setting `textFont` sets the font, then throws when `text.setRangeStyle` warns that the font is not available, or when Missing Glyph Protection keeps characters the font has no glyph for in their font, giving how many. A `TextFont` from an earlier run throws - `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and + `Stale text font`. 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`, `length` 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 paint order of + their first frames, 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`. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -11523,6 +11550,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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..355a11543a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1026,6 +1026,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: 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: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.