Scripts: stories of one thread share their text index, and a deleted story's missing members say Stale story

Stories read from different frames of one thread share one index of the
story's text while the document is unchanged, instead of each keeping its
own copy. A frame listed in two threads shares only with a story whose
frames match. Story.lines, insertionPoints, textRanges and textSelection
check the story first, so a story whose frame was deleted throws Stale
story.

The cross-document baseFrame test passes a rectangle of the other document
and checks the error and that the rectangle stays a path. docs/mcp.md no
longer says baseFrame and postFix throw, the text-frame entry in
docs/target-app-parity.md no longer lists stories and threading as missing,
and the M13 row in docs/roadmap.md lists text frames and stories.
This commit is contained in:
dotCooCoo committed 2026-11-21 22:08:05 -08:00
1 parent 4fb3223368
commit a5690d2d35
5 files changed
+84 -25

No files matched your search

+55 -19
View File
@@ -34,7 +34,7 @@ use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_
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,
id_of, id_parts, in_compound, item_of, item_ref, 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,
@@ -284,7 +284,8 @@ 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 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()));
@@ -292,24 +293,45 @@ fn observe(h: &Host, st: &DocState, anchor: NodeId) -> std::result::Result<(Rc<I
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));
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());
}
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 index = match shared {
Some(index) => index,
None => {
let text = story_text(st, &frames);
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()))?;
@@ -691,6 +713,20 @@ fn range_later(link: &Link, name: &'static str) -> (String, HostMember) {
(name.to_string(), HostMember::Property { get: f.clone(), set: f })
}
/// A member of `Story` that is not available yet: reading or assigning it throws, after the check
/// that the story is still there.
fn story_later(link: &Link, name: &'static str) -> (String, HostMember) {
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::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![
@@ -717,7 +753,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("words", get(l, story_words)),
("paragraphs", get(l, story_paragraphs)),
]);
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| later(l, "Story", m)));
story.extend(["lines", "insertionPoints", "textRanges", "textSelection"].into_iter().map(|m| story_later(l, m)));
let mut range = named(vec![
("typename", get(l, span_typename)),
("parent", get(l, span_story)),
+25 -2
View File
@@ -440,10 +440,16 @@ fn a_frame_of_another_document_cannot_be_linked() {
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[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}");
let out = log(
&mut s,
"var d = app.documents[1], p = d.pageItems[1];\
try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[2]); } 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);
}
@@ -453,6 +459,8 @@ 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[1], st = f.story; f.remove(); st.lines;");
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;");
@@ -520,6 +528,21 @@ fn a_thread_listing_a_frame_twice_is_walked_once() {
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[2].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() {
+2 -2
View File
@@ -2692,8 +2692,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot
`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
+1 -1
View File
@@ -196,7 +196,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) | 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 (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), 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 |
+1 -1
View File
@@ -1025,7 +1025,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). Layers, paths and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Stories, threading, lines, styles, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs, 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: 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`.