From 3ef896191383d4201f17da9b9925f4b237aa1d48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:34:22 -0800 Subject: [PATCH 1/9] Scripts: app.doScript plays an action of the Actions panel A script can play an action by name with app.doScript(action, set, dialogs?), the DoScript method of the scripting reference. script.run takes a new `actions` param, and the app fills it with the Actions panel's actions and their included steps; a recorded command.batch step gives its own steps. - The action and its set are matched by their exact names. A name that matches no action or more than one, an action with no included step, a stop, and a step a script may not run or the engine does not have (a View menu step, or one that plays an action or runs a script) throw before any step runs, so an action cannot play itself. - Each step runs as vc.run runs a command: it joins the run's one undo step for each changed document, counts as a host call, and reads and writes files only where the script may. A failed step is put back and its error gives the step's place, the action and the command. - A step that acts on the active artboard (paste in place, in front and in back, Align, Distribute Objects and Distribute Spacing to the artboard, All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and names no artboard gets the active document's active artboard, as the Actions panel's playback gives it. The index is the one the artboard had as the run started, clamped to the last artboard after a step deletes artboards. While the Artboard tool has several artboards selected, a paste step gets none and Fit to Artwork Bounds gets those artboards. - dialogs must be true or false (default false). app.loadAction and app.unloadAction throw an error that says they are not available yet. - `actions` is checked before the script starts: at most 4,096 actions, 10,000 steps an action, 100,000 in all and 16 MiB. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/scripts.rs | 4 +- crates/engine/src/script/actions.rs | 304 +++++++++++++++++++++ crates/engine/src/script/dom.rs | 5 +- crates/engine/src/script/mod.rs | 10 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_actions.rs | 319 ++++++++++++++++++++++ crates/engine/src/tests/script_folder.rs | 1 + crates/ui-egui/src/app/commands.rs | 2 + crates/ui-egui/src/panels/actions.rs | 117 ++++++++ docs/mcp.md | 21 ++ docs/target-app-parity.md | 1 + 12 files changed, 783 insertions(+), 4 deletions(-) create mode 100644 crates/engine/src/script/actions.rs create mode 100644 crates/engine/src/tests/script_actions.rs diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 4f0d2bad63..e838b53ebc 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -848,7 +848,7 @@ pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, artboard_tool_picks, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; /// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index cf46d853d8..9bc8c427ca 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), actions?: [{set, name, steps: [{command, params?, step?: the step's place in the action, a whole number from 1 (default its place in the list)}]}] (the actions app.doScript(action, set, dialogs?) plays, matched by their exact names; a command.batch step gives its own steps; at most 4096 actions, 10000 steps an action, 100000 steps in all and 16 MiB as JSON; in the app, the Actions panel's actions with their included steps, which a caller's list replaces), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args; app.doScript(action, set, dialogs?) plays the action of actions with those exact names and returns undefined once every step has run: a name that matches none or more than one, a stop, and a step whose command a script may not run or the engine does not have (a View menu step, or one that plays an action) throw an error before any step runs; each step then runs as vc.run runs a command, counted as a host call, and a step that fails is put back and throws an error that names its place and the action, the steps before it staying done; dialogs must be true or false (default false) and changes nothing, as no step opens a dialog. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -171,6 +171,7 @@ fn run(s: &mut Session, p: &Value) -> Result { if s.script_frames && !answers.is_empty() { return Err(param("`answers` is only for a run with nobody to ask: in the app, the person answers each dialog")); } + let actions = script::actions::parse(p.get("actions")).map_err(param)?; let fuel = max_fuel(p)?; let installed = switch_or(p, "installed", false, "script.run")?; let mut checked_real = None; @@ -217,6 +218,7 @@ fn run(s: &mut Session, p: &Value) -> Result { fuel, locale, answers, + actions, }; let name = s.script_start(request)?; if s.script_frames { diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..16c072cebd --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -0,0 +1,304 @@ +//! `app.doScript(action, set, dialogs?)`: plays an action of the Actions panel inside the script's +//! run, as the VBScript reference's `DoScript` method of the Application object describes it +//! (). +//! +//! The actions a run can play come with its request (`script.run`'s `actions`), each with the steps +//! that playback runs: the included steps, those of a recorded `command.batch` one by one. In the app +//! they are the Actions panel's. +//! +//! VectorCraft's own rules, which the reference does not state: +//! - The action and its set are matched by their exact names; a name that matches no action, or +//! more than one, throws before any step runs. +//! - The call returns when every step has run, or when the run is asked to stop. Each step runs as `vc.run` runs a command: it joins +//! the run's transaction and its one undo step for each changed document, it is counted as a host +//! call, it reads and writes files only where the script may, and a step that fails is put back +//! and throws an error that names the step and the action, while the steps before it stay done. +//! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine +//! does not have (a View menu step, or one that plays an action), and a stop throw before any step +//! runs. An action cannot play another action, so it cannot play itself. +//! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it +//! changes nothing. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostMember}; + +use super::{Host, Link, command, current, refused_to_scripts}; + +/// The most actions a run's request may carry. +pub const MAX_ACTIONS: usize = 4096; +/// The most steps one action may have, after a `command.batch` step gives its own steps. +pub const MAX_ACTION_STEPS: usize = 10_000; +/// The most steps the actions of one request may have in all. +pub const MAX_ALL_STEPS: usize = 100_000; +/// The most bytes of the request's actions, as JSON. +pub const MAX_ACTIONS_BYTES: usize = 16 << 20; +/// The longest name of an action or a set, in bytes. +pub const MAX_NAME_BYTES: usize = 1024; +/// The longest command id of a step, in bytes. +const MAX_ID_BYTES: usize = 256; +/// The command id of a stop, which waits for the person in the Actions panel. +pub const STOP_STEP: &str = "action.stop"; + +/// An action a run can play: its set's name, its name and the steps playback runs. +#[derive(Clone, Debug)] +pub struct Playable { + set: String, + name: String, + steps: Vec, +} + +/// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a +/// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and +/// their size as JSON. +#[derive(Clone, Debug)] +struct Step { + place: String, + id: String, + params: Value, + bytes: u64, +} + +/// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the +/// step's place in the action (1 for the first; default its place in the list), within the limits +/// above. A `command.batch` step gives its own steps, each at the batch's place and its own. +pub fn parse(v: Option<&Value>) -> Result, String> { + let Some(v) = v else { return Ok(Vec::new()) }; + let Value::Array(list) = v else { return Err("`actions` must be a list".into()) }; + if list.len() > MAX_ACTIONS { + return Err(format!("`actions` holds more than {MAX_ACTIONS} actions")); + } + if let Some(place) = super::too_deep(v) { + return Err(format!("`actions{place}` is nested more than 64 levels deep")); + } + if serde_json::to_vec(v).map_or(true, |b| b.len() > MAX_ACTIONS_BYTES) { + return Err("`actions` is larger than 16 MiB".into()); + } + let mut all = 0usize; + let mut out = Vec::with_capacity(list.len()); + for (i, a) in list.iter().enumerate() { + let at = format!("`actions[{i}]`"); + let Value::Object(a) = a else { return Err(format!("{at} must be an object")) }; + only_keys(a, &["set", "name", "steps"], &at)?; + let set = name_of(a, "set", &at)?; + let name = name_of(a, "name", &at)?; + let Some(Value::Array(given)) = a.get("steps") else { return Err(format!("{at}.steps must be a list")) }; + let mut steps = Vec::new(); + for (j, s) in given.iter().enumerate() { + let at = format!("{at}.steps[{j}]"); + let Value::Object(s) = s else { return Err(format!("{at} must be an object")) }; + only_keys(s, &["command", "params", "step"], &at)?; + let place = match s.get("step") { + None => (j + 1).to_string(), + Some(n) => match n.as_u64().filter(|n| (1..=1_000_000).contains(n)) { + Some(n) => n.to_string(), + None => return Err(format!("{at}.step must be a whole number from 1 to 1000000")), + }, + }; + let (id, params) = command_of(s, &at)?; + match params.get("commands") { + Some(Value::Array(inner)) if id == "command.batch" => { + for (k, c) in inner.iter().enumerate() { + let at = format!("{at}.params.commands[{k}]"); + let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; + let (id, params) = command_of(c, &at)?; + if id == "command.batch" { + return Err(format!("{at} is a command.batch inside a command.batch")); + } + steps.push(step(format!("{place}.{}", k + 1), id, params)); + } + } + _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), + _ => steps.push(step(place, id, params)), + } + if steps.len() > MAX_ACTION_STEPS { + return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); + } + } + all += steps.len(); + if all > MAX_ALL_STEPS { + return Err(format!("`actions` has more than {MAX_ALL_STEPS} steps in all")); + } + out.push(Playable { set, name, steps }); + } + Ok(out) +} + +impl Playable { + /// The steps the action runs. + pub fn len(&self) -> usize { + self.steps.len() + } + + /// Whether the action runs no step. + pub fn is_empty(&self) -> bool { + self.steps.is_empty() + } +} + +fn only_keys(o: &Map, keys: &[&str], at: &str) -> Result<(), String> { + match o.keys().find(|k| !keys.contains(&k.as_str())) { + Some(k) => Err(format!("{at} has the unknown key `{}`", shown(k))), + None => Ok(()), + } +} + +fn name_of(o: &Map, key: &str, at: &str) -> Result { + match o.get(key) { + Some(Value::String(s)) if s.len() <= MAX_NAME_BYTES => Ok(s.clone()), + Some(Value::String(_)) => Err(format!("{at}.{key} is longer than {MAX_NAME_BYTES} bytes")), + _ => Err(format!("{at}.{key} must be a string")), + } +} + +/// A step's `command` and `params` (default `{}`). +fn command_of(o: &Map, at: &str) -> Result<(String, Value), String> { + let id = match o.get("command") { + Some(Value::String(id)) if !id.is_empty() && id.len() <= MAX_ID_BYTES => id.clone(), + _ => return Err(format!("{at}.command must be a command id")), + }; + let params = match o.get("params") { + None => json!({}), + Some(p @ Value::Object(_)) => p.clone(), + Some(_) => return Err(format!("{at}.params must be an object")), + }; + Ok((id, params)) +} + +fn step(place: String, id: String, params: Value) -> Step { + let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); + Step { place, id, params, bytes } +} + +/// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters +/// as U+FFFD. +fn shown(text: &str) -> String { + const MAX: usize = 80; + let mut out: String = text.chars().take(MAX).map(|c| if c.is_control() { '\u{fffd}' } else { c }).collect(); + if text.chars().nth(MAX).is_some() { + out.push('…'); + } + out +} + +/// The members of `app` this module adds. +pub(super) fn app_members(link: &Link) -> Vec<(String, HostMember)> { + let l = link.clone(); + let play = Rc::new(move |a: Vec| { + let h = current(&l)?; + h.charge_call(16 + a.iter().map(super::data_size).sum::())?; + do_script(&h, &a) + }); + let mut members = vec![("doScript".to_string(), HostMember::Method(play))]; + members.extend(["loadAction", "unloadAction"].map(|name| super::dom::later(link, "Application", name))); + members +} + +fn arg(a: &[Data], i: usize) -> &Data { + a.get(i).unwrap_or(&Data::Undefined) +} + +/// `app.doScript(action, set, dialogs?)`, its arguments after `this`. +fn do_script(h: &Host, a: &[Data]) -> std::result::Result { + if a.len() > 4 { + return Err(HostError::Type("doScript takes an action's name, its set's name and dialogs".into())); + } + let (Data::String(action), Data::String(set)) = (arg(a, 1), arg(a, 2)) else { + return Err(HostError::Type("doScript needs the action's name and its set's name, as strings".into())); + }; + if action.is_empty() || set.is_empty() { + return Err(HostError::Error("doScript needs the action's name and its set's name".into())); + } + if action.len() > MAX_NAME_BYTES || set.len() > MAX_NAME_BYTES { + return Err(HostError::Range(format!("an action's or a set's name is at most {MAX_NAME_BYTES} bytes"))); + } + if !matches!(arg(a, 3), Data::Undefined | Data::Bool(_)) { + return Err(HostError::Type("doScript's dialogs must be true or false".into())); + } + let found: Vec<&Playable> = h.actions.iter().filter(|p| p.set == *set && p.name == *action).take(2).collect(); + let p = match found.as_slice() { + [p] => *p, + [] if !h.actions.iter().any(|p| p.set == *set) => return Err(HostError::Error(format!("there is no action set “{}”", shown(set)))), + [] => return Err(HostError::Error(format!("the set “{}” has no action “{}”", shown(set), shown(action)))), + _ => return Err(HostError::Error(format!("the set “{}” has more than one action “{}”", shown(set), shown(action)))), + }; + if p.steps.is_empty() { + return Err(HostError::Error(format!("the action “{}” has no included steps", shown(&p.name)))); + } + // Every step is checked before the first runs, so a step that cannot run leaves the documents as + // they were. + for s in &p.steps { + let refused = s.id == STOP_STEP || refused_to_scripts(&s.id) || crate::find_command(&s.id).is_none(); + if refused { + let (place, name, id) = (&s.place, shown(&p.name), shown(&s.id)); + return Err(HostError::Error(if s.id == STOP_STEP { + format!("step {place} of “{name}” is a stop, which a script cannot wait at") + } else { + format!("step {place} of “{name}” runs `{id}`, which a script cannot run") + })); + } + } + for s in &p.steps { + // A run asked to stop runs no further step; the realm ends it at its next instruction and + // puts the documents back. + if h.session.borrow().script_stop.is_set() { + break; + } + h.charge_call(16 + s.id.len() as u64 + s.bytes)?; + // Saved steps run as they run in the Actions panel: keys their commands no longer read are + // passed over. + let params = on_active_artboard(&h.session.borrow(), &h.active_artboards, &s.id, &s.params); + let outer = h.session.borrow_mut().set_replaying(true); + let r = command(h, &s.id, ¶ms); + h.session.borrow_mut().set_replaying(outer); + if let Err(e) = r { + let named = |m: String| format!("action step {} of “{}” (`{}`) failed: {m}", s.place, shown(&p.name), shown(&s.id)); + return Err(match e { + HostError::Error(m) | HostError::Type(m) | HostError::Range(m) | HostError::Syntax(m) => HostError::Error(named(m)), + other => other, + }); + } + } + Ok(Data::Undefined) +} + +/// `params` of step `id`, with the active artboard of the active document added as a +/// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for +/// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to +/// Selected Art. The active artboard is the index `start` gives for the document (its index as the +/// run started, which the view keeps), past the last artboard the last one, as the view shows it +/// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While +/// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its +/// `indices` instead, and a paste step gets none (it pastes on them). A paste step in a document +/// without artboards, or one that names `artboards`, and a Fit to Artwork Bounds step that names +/// `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: &str, params: &Value) -> Value { + let mut params = params.clone(); + let Some(st) = s.active() else { return params }; + let n = st.doc.artboards.len(); + let active = match start.iter().find(|(uid, _)| *uid == st.uid) { + Some((_, i)) => (*i).min(n.saturating_sub(1)), + None => super::dom::active_artboard(st), + }; + let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); + let fit_art = id == "artboard.fitToArt"; + let key = if crate::ON_ACTIVE_ARTBOARD.contains(&id) { + "artboard" + } else if crate::FIT_ACTIVE_ARTBOARD.contains(&id) { + "index" + } else { + return params; + }; + let Some(p) = params.as_object_mut() else { return params }; + if p.contains_key(key) || (fit_art && p.contains_key("indices")) || (paste && (n == 0 || p.contains_key("artboards"))) { + return params; + } + let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; + if picks.is_empty() { + p.insert(key.into(), json!(active)); + } else if fit_art { + p.insert("indices".into(), json!(picks)); + } + params +} diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 241720f786..7d66e3cbc2 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -152,7 +152,7 @@ fn method(link: &Link, f: Member) -> HostMember { /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document or page item `this` is still there. -fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { +pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> (String, HostMember) { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -397,7 +397,7 @@ struct Frame { } /// The index of the active artboard of `st`, as the view keeps it. -fn active_artboard(st: &DocState) -> usize { +pub(super) fn active_artboard(st: &DocState) -> usize { let index_of = |id: u32| st.doc.artboards.iter().position(|a| a.id == id); st.active_artboard.and_then(index_of).or_else(|| st.doc.opened_artboard.and_then(index_of)).unwrap_or(0) } @@ -1721,6 +1721,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("getIsFileOpen", method(l, app_is_open)), ]); application.push(later(l, "Application", "beep")); + application.extend(super::actions::app_members(l)); let preset = { let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..770934ce98 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -48,6 +48,7 @@ //! that holds the run's host only while the run goes on. An error, a limit or a stop puts the //! documents back and keeps the engine's globals; an internal error drops the engine. +pub mod actions; pub mod console; pub mod dialogs; pub mod dollar; @@ -202,6 +203,8 @@ pub(crate) struct Request { pub locale: String, /// The answers to the dialogs of a run with nobody to ask, in order. pub answers: Vec, + /// The actions `app.doScript` can play. + pub actions: Vec, } thread_local! { @@ -802,6 +805,11 @@ struct Host { args: RefCell<(Data, u64)>, /// The run's state of the script object model (`app`). dom: dom::State, + /// The actions `app.doScript` can play. + actions: Vec, + /// The index of each open document's active artboard as the run starts, by document uid. The + /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. + active_artboards: Vec<(u64, usize)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -2065,6 +2073,8 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::default(), + actions: request.actions, + active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index adcaefd59d..db1b95966b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -169,6 +169,7 @@ mod repeat_edit; mod save; mod saveoptions; mod scalestrokes; +mod script_actions; mod script_console; mod script_dialogs; mod script_dollar; diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs new file mode 100644 index 0000000000..02ee9f5957 --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -0,0 +1,319 @@ +//! `app.doScript`: a script plays an action of `script.run`'s `actions`. + +use serde_json::{Value, json}; + +use crate::*; + +fn run_with(s: &mut Session, source: &str, actions: &Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "t.js", "actions": actions})) +} + +fn log_with(s: &mut Session, source: &str, actions: &Value) -> Vec { + let r = run_with(s, source, actions).unwrap_or_else(|e| panic!("{source}: {e}")); + r["log"].as_array().cloned().unwrap_or_default() +} + +/// The error message a `try` around `call` logs, or `"ok"`. +fn caught(s: &mut Session, call: &str, actions: &Value) -> String { + let source = format!("try {{ {call}; vc.log('ok'); }} catch (e) {{ vc.log(e.name + ': ' + e.message); }}"); + log_with(s, &source, actions).first().and_then(Value::as_str).unwrap_or_default().to_string() +} + +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +fn objects(s: &Session) -> usize { + s.active().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +fn undo_labels(s: &Session) -> Vec { + s.active().unwrap().history.undo.iter().map(|e| e.label.clone()).collect() +} + +fn rect(x: i64) -> Value { + json!({"command": "shape.rectangle", "params": {"x": x, "y": 10, "width": 20, "height": 20}}) +} + +/// One set, `Set`, with the actions given as (name, steps). +fn set(actions: &[(&str, Vec)]) -> Value { + Value::Array(actions.iter().map(|(name, steps)| json!({"set": "Set", "name": name, "steps": steps})).collect()) +} + +#[test] +fn do_script_plays_every_step_as_one_undo_step_with_the_script() { + let mut s = doc(); + let before = undo_labels(&s); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let out = log_with(&mut s, "vc.run('shape.rectangle', {x: 100, y: 10, width: 5, height: 5}); vc.log(app.doScript('Two', 'Set'));", &actions); + assert_eq!(out, vec![Value::Null], "doScript returns undefined"); + assert_eq!(objects(&s), 3); + let after = undo_labels(&s); + assert_eq!(after.len(), before.len() + 1, "{after:?}"); + assert_eq!(after.last().map(String::as_str), Some(script::STEP_LABEL)); + // The steps of a recorded `command.batch` run one by one, each counted as a host call. + let batch = set(&[("Batch", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), rect(10), rect(20)]}})])]); + let r = run_with(&mut s, "app.doScript('Batch', 'Set', false);", &batch).unwrap(); + assert_eq!(objects(&s), 6); + let r0 = run_with(&mut s, "1;", &batch).unwrap(); + assert!(r["hostCalls"].as_u64().unwrap() >= r0["hostCalls"].as_u64().unwrap() + 4, "{r}"); +} + +#[test] +fn a_later_throw_puts_back_what_the_action_did() { + let mut s = doc(); + let before = (objects(&s), undo_labels(&s)); + let actions = set(&[("Two", vec![rect(0), rect(50)])]); + let e = run_with(&mut s, "app.doScript('Two', 'Set'); throw new Error('late');", &actions).unwrap_err().to_string(); + assert!(e.contains("late"), "{e}"); + assert_eq!((objects(&s), undo_labels(&s)), before); +} + +#[test] +fn a_failed_step_is_put_back_and_the_steps_before_it_stay() { + let mut s = doc(); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let actions = set(&[("Bad", vec![rect(0), bad, rect(50)])]); + let m = caught(&mut s, "app.doScript('Bad', 'Set')", &actions); + assert!(m.starts_with("Error: action step 2 of “Bad” (`object.move`) failed:"), "{m}"); + assert_eq!(objects(&s), 1, "the first step stays done and the third never runs"); +} + +#[test] +fn names_are_matched_exactly_and_must_be_one_action() { + let mut s = doc(); + let actions = json!([ + {"set": "Set", "name": "One", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Twice", "steps": [rect(0)]}, + {"set": "Set", "name": "Empty", "steps": []}, + ]); + assert_eq!(caught(&mut s, "app.doScript('one', 'Set')", &actions), "Error: the set “Set” has no action “one”"); + assert_eq!(caught(&mut s, "app.doScript('One', 'set')", &actions), "Error: there is no action set “set”"); + assert_eq!(caught(&mut s, "app.doScript('Twice', 'Set')", &actions), "Error: the set “Set” has more than one action “Twice”"); + assert_eq!(caught(&mut s, "app.doScript('Empty', 'Set')", &actions), "Error: the action “Empty” has no included steps"); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set')", &json!([])), "Error: there is no action set “Set”"); + assert_eq!(objects(&s), 0); + assert_eq!(caught(&mut s, "app.doScript('One', 'Set', true)", &actions), "ok"); + assert_eq!(objects(&s), 1); + assert_eq!(caught(&mut s, "app.loadAction(1)", &actions), "Error: Application.loadAction is not available yet"); + assert_eq!(caught(&mut s, "app.unloadAction('Set', '')", &actions), "Error: Application.unloadAction is not available yet"); +} + +#[test] +fn bad_arguments_throw_and_change_nothing() { + let mut s = doc(); + let actions = set(&[("One", vec![rect(0)])]); + for (call, want) in [ + ("app.doScript()", "TypeError"), + ("app.doScript(1, 'Set')", "TypeError"), + ("app.doScript('One', {})", "TypeError"), + ("app.doScript('One', 'Set', 'yes')", "TypeError"), + ("app.doScript('One', 'Set', 1)", "TypeError"), + ("app.doScript('One', 'Set', false, 4)", "TypeError"), + ("app.doScript('', 'Set')", "Error"), + ("app.doScript(new Array(2000).join('x'), 'Set')", "RangeError"), + ] { + let m = caught(&mut s, call, &actions); + assert!(m.starts_with(&format!("{want}:")), "{call}: {m}"); + } + assert_eq!(objects(&s), 0); +} + +#[test] +fn steps_a_script_may_not_run_stop_the_action_before_any_step() { + let mut s = doc(); + s.prefs.show_external_script_warning = true; + let steps = [ + (json!({"command": "script.run", "params": {"source": "1"}}), "runs `script.run`, which a script cannot run"), + (json!({"command": "prefs.set", "params": {"key": "showExternalScriptWarning", "value": false}}), "runs `prefs.set`"), + (json!({"command": "ui.action.play", "params": {"set": "Set", "action": "Loop"}}), "runs `ui.action.play`"), + (json!({"command": "ui.runScript", "params": {"source": "1"}}), "runs `ui.runScript`"), + (json!({"command": "view.zoomIn"}), "runs `view.zoomIn`"), + (json!({"command": "action.stop", "params": {"message": "wait"}}), "is a stop, which a script cannot wait at"), + ]; + for (bad, want) in steps { + let actions = set(&[("Loop", vec![rect(0), bad.clone()])]); + let m = caught(&mut s, "app.doScript('Loop', 'Set')", &actions); + assert!(m.starts_with("Error: step 2 of “Loop” ") && m.contains(want), "{bad}: {m}"); + assert_eq!(objects(&s), 0, "{bad}: no step ran"); + } + assert!(s.prefs.show_external_script_warning); + // A refused command inside a recorded batch is refused too. + let batch = set(&[("B", vec![json!({"command": "command.batch", "params": {"commands": [rect(0), {"command": "script.run", "params": {}}]}})])]); + let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); + assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); + assert_eq!(objects(&s), 0); +} + +#[test] +fn an_action_step_keeps_the_scripts_file_gate() { + let mut s = doc(); + let path = std::env::temp_dir().join(format!("vc-do-script-{}.svg", std::process::id())); + let _ = std::fs::remove_file(&path); + let export = json!({"command": "document.export", "params": {"path": path.to_string_lossy(), "format": "svg"}}); + let actions = set(&[("Export", vec![export])]); + let m = caught(&mut s, "app.doScript('Export', 'Set')", &actions); + assert!(m.contains("Script file access denied"), "{m}"); + assert!(!path.exists()); +} + +#[test] +fn a_long_action_is_held_to_the_host_call_limit() { + let mut s = doc(); + // Each step counts as a host call of its own, and its result as another, as for `vc.run`, so the + // steps of one call cannot pass the limit. + let calls = |s: &mut Session, steps: usize| { + let actions = set(&[("One", vec![json!({"command": "select.none"}); steps])]); + run_with(s, "app.doScript('One', 'Set');", &actions).unwrap()["hostCalls"].as_u64().unwrap() + }; + let (one, many) = (calls(&mut s, 1), calls(&mut s, 1001)); + assert!(many >= one + 2000, "{one} {many}"); +} + +#[test] +fn bad_action_lists_are_refused_before_the_script_runs() { + let mut s = doc(); + let step = || json!({"command": "select.none"}); + let cases = [ + (json!({}), "`actions` must be a list"), + (json!([1]), "`actions[0]` must be an object"), + (json!([{"set": "S", "name": 1, "steps": []}]), "`actions[0]`.name must be a string"), + (json!([{"set": "S", "name": "A"}]), "`actions[0]`.steps must be a list"), + (json!([{"set": "S", "name": "A", "steps": [], "key": 1}]), "unknown key `key`"), + (json!([{"set": "S", "name": "A", "steps": [{"command": ""}]}]), "command must be a command id"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "params": []}]}]), "params must be an object"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "select.none", "step": 0}]}]), "step must be a whole number"), + (json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {}}]}]), "params.commands must be a list"), + ( + json!([{"set": "S", "name": "A", "steps": [{"command": "command.batch", "params": {"commands": [{"command": "command.batch", "params": {"commands": []}}]}}]}]), + "a command.batch inside a command.batch", + ), + (json!([{"set": "S", "name": "x".repeat(2000), "steps": []}]), "longer than 1024 bytes"), + (Value::Array(vec![json!({"set": "S", "name": "A", "steps": []}); script::actions::MAX_ACTIONS + 1]), "more than 4096 actions"), + (json!([{"set": "S", "name": "A", "steps": vec![step(); script::actions::MAX_ACTION_STEPS + 1]}]), "more than 10000 steps"), + ]; + for (actions, want) in cases { + let e = run_with(&mut s, "vc.run('shape.rectangle', {x: 0, y: 0, width: 1, height: 1});", &actions).unwrap_err().to_string(); + assert!(e.contains(want), "{want}: {e}"); + } + let many: Vec = (0..11).map(|i| json!({"set": "S", "name": format!("A{i}"), "steps": vec![step(); 10_000]})).collect(); + let e = run_with(&mut s, "1;", &Value::Array(many)).unwrap_err().to_string(); + assert!(e.contains("more than 100000 steps in all"), "{e}"); + assert_eq!(objects(&s), 0, "no run started"); +} + +#[test] +fn a_kept_engine_plays_the_actions_of_the_run_that_calls_it() { + let mut s = doc(); + let first = set(&[("One", vec![rect(0)])]); + log_with(&mut s, "#targetengine keep\nvar play = function () { app.doScript('One', 'Set'); };", &first); + assert_eq!(objects(&s), 0); + // The next run has no actions: the function kept from the first run finds none. + let call = "#targetengine keep\ntry { play(); vc.log('ok'); } catch (e) { vc.log(e.message); }"; + assert_eq!(log_with(&mut s, call, &json!([])), vec![json!("there is no action set “Set”")]); + let two = set(&[("One", vec![rect(0), rect(30)])]); + assert_eq!(log_with(&mut s, call, &two), vec![json!("ok")]); + assert_eq!(objects(&s), 2); +} + +/// Makes artboard `index` of the active document the view's active one, as the app does before each +/// command. +fn make_active(s: &mut Session, index: usize) { + let id = s.active().unwrap().doc.artboards[index].id; + s.doc_mut().unwrap().active_artboard = Some(id); +} + +/// A step that acts on the active artboard, Align to Artboard in a recorded batch and Fit to Selected +/// Art, acts on the active artboard's index as the run started; after the script deletes that +/// artboard, the last one. A step that names its artboard keeps it. +#[test] +fn steps_act_on_the_artboard_active_as_they_run() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&s); + make_active(&mut s, 2); + let align = |to: Value| json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard", "artboard": to}}); + let mut first = align(json!(0)); + first["params"].as_object_mut().unwrap().remove("artboard"); + let actions = set(&[ + ("Align", vec![json!({"command": "command.batch", "params": {"commands": [first]}})]), + ("Align 1", vec![align(json!(0))]), + ("Fit", vec![json!({"command": "artboard.fitToSelection"})]), + ]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "vc.run('artboard.delete', {index: 2}); app.doScript('Align', 'Set'); app.doScript('Fit', 'Set');", &actions); + let art = s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to the last artboard, where the deleted active one was"); + assert_eq!(boards(&s), [was[0], art], "Fit to Selected Art resizes that artboard and leaves the other"); + log_with(&mut s, "app.doScript('Align 1', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); +} + +/// The active artboard a step gets is the index it had as the run started: after a step deletes an +/// artboard before it, the artboard now at that index, as the view shows it. +#[test] +fn steps_keep_the_active_artboards_index() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + let uid = s.active().unwrap().uid; + let add = |s: &Session| script::actions::on_active_artboard(s, &[(uid, 1)], "object.align", &json!({})); + assert_eq!(add(&s), json!({"artboard": 1})); + s.execute("artboard.delete", &json!({"index": 0})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); + s.execute("artboard.delete", &json!({"index": 1})).unwrap(); + assert_eq!(add(&s), json!({"artboard": 0}), "past the last artboard, the last one"); +} + +/// A Fit to Artwork Bounds step that names no artboard fits the active one; one that names its +/// `indices` fits those. +#[test] +fn a_fit_to_artwork_bounds_step_fits_the_active_artboard_or_its_own() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + make_active(&mut s, 1); + let actions = set(&[ + ("Fit", vec![json!({"command": "artboard.fitToArt"})]), + ("Fit first", vec![json!({"command": "artboard.fitToArt", "params": {"indices": [0]}})]), + ]); + let boards = |s: &Session| s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + assert_eq!(boards(&s), [was[0], art[1]], "the active artboard fits its art"); + log_with(&mut s, "app.doScript('Fit first', 'Set');", &actions); + assert_eq!(boards(&s), art, "the step's own indices"); +} + +/// While the Artboard tool has several artboards selected, a paste step gets no artboard, so that it +/// pastes on those, and a Fit to Artwork Bounds step gets those as its `indices`; the other steps +/// still get the active one. +#[test] +fn paste_and_fit_steps_keep_the_artboard_tools_selection() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); + make_active(&mut s, 1); + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &[], id, &json!({})); + assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + for id in ["edit.pasteInPlace", "edit.pasteInFront", "edit.pasteInBack"] { + assert_eq!(add(&s, id), json!({}), "{id}"); + } + assert_eq!(add(&s, "artboard.fitToArt"), json!({"indices": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); + assert_eq!(add(&s, "shape.rectangle"), json!({})); +} diff --git a/crates/engine/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 8ea0482826..11b2fe1360 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -359,6 +359,7 @@ fn an_installed_run_reads_its_includes_in_the_folder_its_read_found() { fuel: script::DEFAULT_FUEL, locale: "en_US".into(), answers: Vec::new(), + actions: Vec::new(), }; s.script_start(request).unwrap(); assert_eq!(s.script_run_to_end().unwrap()["log"], json!([1])); diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 042e8b37a5..02a9f756ea 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -156,6 +156,8 @@ impl VectorcraftApp { } let mut params = params; self.add_active_artboard(id, &mut params); + // A script's `app.doScript` plays the Actions panel's actions. + panels::actions::add_script_actions(self, id, &mut params); // Edit Symbol from the Symbols panel in a document without artboards centers the symbol's // art in the view, whose center the app passes as `viewCenter`, to a batch's symbol.edit // steps too. diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 12fc7c395e..9c0563b849 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -585,6 +585,64 @@ pub(crate) fn has_stop(commands: &[Value]) -> bool { commands.iter().any(is_stop) } +/// For command `id` `script.run`: gives its `params` the panel's actions as `actions`, which the +/// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel +/// order, with its steps as playback runs them ([`Action::playback_steps`]) and each step's place in +/// the action. An action that `actions` cannot hold (a step that is not a command, a name that is +/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, parse}; + let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; + if p.contains_key("actions") { + return; + } + let (mut list, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); + for (set, a) in app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))) { + if list.len() >= MAX_ACTIONS { + break; + } + // The commands of a recorded `command.batch` step go back into one batch step, so that an + // error names a failing command by the batch's place and its own (`3.2`). + let mut played: Vec = Vec::new(); + for s in a.playback_steps() { + let params = match s.command.get("params") { + None | Some(Value::Null) => json!({}), + Some(p) => p.clone(), + }; + let one = json!({"command": s.command.get("command").cloned().unwrap_or(Value::Null), "params": params}); + let place = s.row + 1; + if a.steps.get(s.row).is_none_or(|(id, _)| id != "command.batch") { + let mut one = one; + one["step"] = json!(place); + played.push(one); + continue; + } + match played.last_mut() { + Some(last) if last["command"] == "command.batch" && last["step"] == place => { + if let Some(Value::Array(inner)) = last.pointer_mut("/params/commands") { + inner.push(one); + } + } + _ => played.push(json!({"command": "command.batch", "params": {"commands": [one]}, "step": place})), + } + } + let entry = json!({"set": set.name, "name": a.name, "steps": played}); + let one = Value::Array(vec![entry]); + let Ok(parsed) = parse(Some(&one)) else { continue }; + let count = parsed.first().map_or(0, vectorcraft_engine::script::actions::Playable::len); + let size = serde_json::to_vec(&one).map_or(usize::MAX, |b| b.len()); + if steps + count > MAX_ALL_STEPS || bytes.saturating_add(size) > MAX_ACTIONS_BYTES { + continue; + } + steps += count; + bytes += size; + if let Value::Array(mut one) = one { + list.append(&mut one); + } + } + p.insert("actions".into(), Value::Array(list)); +} + /// The message and Allow Continue setting in a stop's params; each may be left out. A saved stop /// with no params reads as null here. A value of another type, or params that are neither null /// nor an object, is an error. @@ -7449,6 +7507,65 @@ mod tests { panic!("the script did not end"); } + /// A script's `app.doScript` plays the panel's actions with their included steps; an action whose + /// step `script.run`'s `actions` cannot hold is left out, and a caller's own list is kept. + #[test] + fn a_script_plays_the_panels_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = |x: i64| ("shape.rectangle".to_string(), json!({"x": x, "y": 10, "width": 10, "height": 10})); + let mut draw = Action::new("Draw", vec![rect(0), rect(20), rect(40)]); + draw.excluded_steps.insert(1); + let odd = Action::new("Odd", vec![rect(0), ("select.none".to_string(), json!(5))]); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let batch = ("command.batch".to_string(), json!({"commands": [{"command": "select.none"}, bad]})); + let batched = Action::new("Batched", vec![("select.none".to_string(), json!({})), batch]); + app.ui.action_sets.push(ActionSet::new("Mine", vec![draw, odd, batched])); + let objects = + |app: &VectorcraftApp| app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()); + let undo = app.session.active().map_or(0, |d| d.history.undo.len()); + app.session.script_frames = false; + let source = "app.doScript('Draw', 'Mine'); try { app.doScript('Odd', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Odd”"])); + assert_eq!(objects(&app), 2, "the excluded step does not run"); + assert_eq!(app.session.active().map_or(0, |d| d.history.undo.len()), undo + 1); + // A failing command of a recorded batch is named by the batch's place and its own. + let source = "try { app.doScript('Batched', 'Mine'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let m = r["log"][0].as_str().unwrap_or_default(); + assert!(m.starts_with("action step 2.2 of “Batched” (`object.move`) failed:"), "{m}"); + let r = app + .run("script.run", json!({"source": "try { app.doScript('Draw', 'Mine'); } catch (e) { vc.log(e.message); }", "actions": []})) + .unwrap(); + assert_eq!(r["log"], json!(["there is no action set “Mine”"])); + assert_eq!(objects(&app), 2); + } + + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's + /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. + #[test] + fn a_script_plays_the_actions_on_the_active_artboard() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 100, "height": 100, "units": "Points", "artboards": 2})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + app.run("paint.setStroke", json!({"none": true})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let batch = ("command.batch".to_string(), json!({"commands": [align]})); + let fit = ("artboard.fitToSelection".to_string(), json!({})); + app.ui.action_sets.push(ActionSet::new("Mine", vec![Action::new("Align", vec![batch]), Action::new("Fit", vec![fit])])); + let boards = |app: &VectorcraftApp| app.session.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect::>(); + let was = boards(&app); + app.view_mut().unwrap().artboard = 1; + app.session.script_frames = false; + let source = "app.doScript('Align', 'Mine'); app.doScript('Fit', 'Mine');"; + app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + let art = app.session.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap(); + assert_eq!(art.x0, was[1].x0, "aligned to artboard 2, the active one"); + assert_eq!(boards(&app), [was[0], art], "Fit to Selected Art resizes artboard 2 and leaves artboard 1"); + } + /// Begin Recording with `filler` steps already recorded. fn recording_with(app: &mut VectorcraftApp, filler: usize) { app.run(START_RECORDING, json!({})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 9bc2be8efc..cda10102c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2680,6 +2680,27 @@ app through the global object `vc`, and writes to the Script Console and runs ot `app.beep`, throw an error that says they are not available yet when they are read or assigned. Other members those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds themselves, such as a path's fill, are not defined yet and read as `undefined`. +- `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method + of the scripting reference + https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf + describes it, and returns `undefined` once every step has run. The actions come from `script.run`'s `actions`; the + app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own + steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and + Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to + Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run + started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one + past the end. While the Artboard tool has several artboards selected, a paste step and a Fit to Artwork Bounds step + act on those instead, as in the panel's playback. VectorCraft's own rules: the action and its set are matched by + their exact names, and a name that matches no action or more than one throws an error before any step runs, as does + an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any + step runs, so an action cannot play itself. + Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts + as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an + error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an + uncaught error later puts them back with the rest of the run. `dialogs` must be `true` or `false` (default + `false`); no step opens a dialog, so it changes nothing. `app.loadAction` and `app.unloadAction` throw an error + that says they are not available yet when they are read or assigned. - `$.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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b252b56a6..3b035c722c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,6 +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, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.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`. From 59facefcd2b5037610cbace1bb8c06e443bb9dd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 14:25:31 -0800 Subject: [PATCH 2/9] Scripts: doScript checks a Batch step's commands before any step runs An action step that runs action.batch plays its own list of commands on each file. app.doScript now checks those commands with the action's steps, so a stop, a command a script may not run or a command the engine does not have among them throws an error naming the step (as 2.2) before any step of the action runs. --- crates/engine/src/script/actions.rs | 31 ++++++++++++++++++----- crates/engine/src/tests/script_actions.rs | 6 +++++ docs/mcp.md | 3 ++- 3 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index 16c072cebd..a0fabf2103 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -15,7 +15,8 @@ //! and throws an error that names the step and the action, while the steps before it stay done. //! - A step a script may not run ([`super::refused_to_scripts`]), a step whose command the engine //! does not have (a View menu step, or one that plays an action), and a stop throw before any step -//! runs. An action cannot play another action, so it cannot play itself. +//! runs, as does such a command among those an `action.batch` step plays. An action cannot play +//! another action, so it cannot play itself. //! - `dialogs` is `true` or `false` (default `false`); VectorCraft's steps open no dialogs, so it //! changes nothing. @@ -229,13 +230,12 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { // Every step is checked before the first runs, so a step that cannot run leaves the documents as // they were. for s in &p.steps { - let refused = s.id == STOP_STEP || refused_to_scripts(&s.id) || crate::find_command(&s.id).is_none(); - if refused { - let (place, name, id) = (&s.place, shown(&p.name), shown(&s.id)); - return Err(HostError::Error(if s.id == STOP_STEP { + if let Some((place, id)) = refused_step(s) { + let name = shown(&p.name); + return Err(HostError::Error(if id == STOP_STEP { format!("step {place} of “{name}” is a stop, which a script cannot wait at") } else { - format!("step {place} of “{name}” runs `{id}`, which a script cannot run") + format!("step {place} of “{name}” runs `{}`, which a script cannot run", shown(&id)) })); } } @@ -263,6 +263,25 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { Ok(Data::Undefined) } +/// The place and command of the first command step `s` would run that a script may not run: the +/// step itself, or one of the `commands` an `action.batch` step plays on each file (placed as the +/// batch's place and its own, as in `3.2`). A stop, a command a script may not run and a command the +/// engine does not have are refused. +fn refused_step(s: &Step) -> Option<(String, String)> { + let refused = |id: &str| id == STOP_STEP || refused_to_scripts(id) || crate::find_command(id).is_none(); + if refused(&s.id) { + return Some((s.place.clone(), s.id.clone())); + } + if s.id != "action.batch" { + return None; + } + let commands = s.params.get("commands").and_then(Value::as_array)?; + commands.iter().enumerate().find_map(|(k, c)| { + let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + refused(id).then(|| (format!("{}.{}", s.place, k + 1), id.to_owned())) + }) +} + /// `params` of step `id`, with the active artboard of the active document added as a /// `command.batch` given that artboard adds it when the Actions panel plays the step: `artboard` for /// the commands that act on the active artboard, `index` for Fit to Artwork Bounds and Fit to diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 02ee9f5957..4fbcd55751 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -146,6 +146,12 @@ fn steps_a_script_may_not_run_stop_the_action_before_any_step() { let m = caught(&mut s, "app.doScript('B', 'Set')", &batch); assert!(m.starts_with("Error: step 1.2 of “B” runs `script.run`"), "{m}"); assert_eq!(objects(&s), 0); + // So is one among the commands a Batch step plays on each file, before the steps ahead of it run. + let files = json!({"command": "action.batch", "params": {"commands": [{"command": "select.all"}, {"command": "prefs.set", "params": {}}]}}); + let batch = set(&[("F", vec![rect(0), files])]); + let m = caught(&mut s, "app.doScript('F', 'Set')", &batch); + assert!(m.starts_with("Error: step 2.2 of “F” runs `prefs.set`, which a script cannot run"), "{m}"); + assert_eq!(objects(&s), 0); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index cda10102c0..6b507eab99 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2694,7 +2694,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot their exact names, and a name that matches no action or more than one throws an error before any step runs, as does an action with no included step. A stop, and a step whose command a script may not run or the engine does not have (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any - step runs, so an action cannot play itself. + step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an + action cannot play itself. Each step then runs as `vc.run` runs a command: it joins the run's one undo step for each changed document, counts as a host call, and reads and writes files only where the script may. A step that fails is put back and throws an error that gives the step's place, the action's name and the step's command, and the steps before it stay done; an From fdad498dbc15f22757be41cc64653cff9910a37b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 17:46:59 -0800 Subject: [PATCH 3/9] Scripts: doScript keeps the run's artboard picks and a batch's artboard - The Artboard tool's selection as script.run starts is kept for the steps app.doScript plays: the run gives the tool fresh state, which dropped it, so a paste or Fit to Artwork Bounds step acted on the active artboard only. - A step of a command.batch step that names its artboard acts on that artboard, past the last one the last, as command.batch gives it. - The app leaves out every action of a set that shares a name with an action it cannot pass, so that name is never one a script can play. - The host name check lists doScript, loadAction and unloadAction. --- crates/engine/src/script/actions.rs | 58 ++++++++++---- crates/engine/src/script/mod.rs | 8 ++ crates/engine/src/tests/script_actions.rs | 75 ++++++++++++++++++- .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/ui-egui/src/panels/actions.rs | 43 ++++++++++- docs/mcp.md | 10 ++- 6 files changed, 174 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs index a0fabf2103..b4a7a743a3 100644 --- a/crates/engine/src/script/actions.rs +++ b/crates/engine/src/script/actions.rs @@ -52,13 +52,14 @@ pub struct Playable { /// A step of a [`Playable`]: its place in the action as errors give it (1 for the first; a step of a /// `command.batch` step has the batch's place and its own, as in `3.2`), its command, its params and -/// their size as JSON. +/// their size as JSON, and for a step of a `command.batch` step the `artboard` that batch names. #[derive(Clone, Debug)] struct Step { place: String, id: String, params: Value, bytes: u64, + artboard: Option, } /// `script.run`'s `actions`: `[{set, name, steps: [{command, params?, step?}]}]`, where `step` is the @@ -100,6 +101,9 @@ pub fn parse(v: Option<&Value>) -> Result, String> { let (id, params) = command_of(s, &at)?; match params.get("commands") { Some(Value::Array(inner)) if id == "command.batch" => { + // The batch's `artboard`, for its steps that act on the active artboard, as + // `command.batch` reads it. + let artboard = params.get("artboard").and_then(Value::as_u64); for (k, c) in inner.iter().enumerate() { let at = format!("{at}.params.commands[{k}]"); let Value::Object(c) = c else { return Err(format!("{at} must be an object")) }; @@ -107,11 +111,11 @@ pub fn parse(v: Option<&Value>) -> Result, String> { if id == "command.batch" { return Err(format!("{at} is a command.batch inside a command.batch")); } - steps.push(step(format!("{place}.{}", k + 1), id, params)); + steps.push(step(format!("{place}.{}", k + 1), id, params, artboard)); } } _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), - _ => steps.push(step(place, id, params)), + _ => steps.push(step(place, id, params, None)), } if steps.len() > MAX_ACTION_STEPS { return Err(format!("{at}: the action has more than {MAX_ACTION_STEPS} steps")); @@ -167,9 +171,9 @@ fn command_of(o: &Map, at: &str) -> Result<(String, Value), Strin Ok((id, params)) } -fn step(place: String, id: String, params: Value) -> Step { +fn step(place: String, id: String, params: Value, artboard: Option) -> Step { let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); - Step { place, id, params, bytes } + Step { place, id, params, bytes, artboard } } /// `text` as an error shows it: at most 80 characters, with … after a cut, and control characters @@ -248,7 +252,8 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result { h.charge_call(16 + s.id.len() as u64 + s.bytes)?; // Saved steps run as they run in the Actions panel: keys their commands no longer read are // passed over. - let params = on_active_artboard(&h.session.borrow(), &h.active_artboards, &s.id, &s.params); + let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard }; + let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params); let outer = h.session.borrow_mut().set_replaying(true); let r = command(h, &s.id, ¶ms); h.session.borrow_mut().set_replaying(outer); @@ -289,16 +294,24 @@ fn refused_step(s: &Step) -> Option<(String, String)> { /// run started, which the view keeps), past the last artboard the last one, as the view shows it /// after a step deletes artboards; a document the run opened has its own ([`super::dom`]'s). While /// the Artboard tool has several artboards selected, a Fit to Artwork Bounds step gets those as its -/// `indices` instead, and a paste step gets none (it pastes on them). A paste step in a document -/// without artboards, or one that names `artboards`, and a Fit to Artwork Bounds step that names -/// `indices`, get none. A key the step gives is kept. -pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: &str, params: &Value) -> Value { +/// `indices` instead, and a paste step gets none (it pastes on them). The run gives the tool fresh +/// state, which drops its selection, so while the tool is still the Artboard tool and has none, the +/// selection [`Start::picks`] holds for the document as the run started applies: a Fit to Artwork +/// Bounds step gets those as its `indices` and a paste step as its `artboards`, the ones past the +/// last artboard left out, and only while two or more remain. A step of a recorded `command.batch` +/// that names its `artboard` ([`Start::batch`]) gets that artboard instead of the active one, past +/// the last artboard the last one, and none in a document without artboards, as `command.batch` +/// gives it. A paste step in a document without artboards, or one that names `artboards`, and a Fit +/// to Artwork Bounds step that names `indices`, get none. A key the step gives is kept. +pub(crate) fn on_active_artboard(s: &crate::Session, start: &Start<'_>, id: &str, params: &Value) -> Value { let mut params = params.clone(); let Some(st) = s.active() else { return params }; let n = st.doc.artboards.len(); - let active = match start.iter().find(|(uid, _)| *uid == st.uid) { - Some((_, i)) => (*i).min(n.saturating_sub(1)), - None => super::dom::active_artboard(st), + let active = match (start.batch, start.active.iter().find(|(uid, _)| *uid == st.uid)) { + (Some(_), _) if n == 0 => return params, + (Some(a), _) => usize::try_from(a).map_or(n - 1, |a| a.min(n - 1)), + (None, Some((_, i))) => (*i).min(n.saturating_sub(1)), + (None, None) => super::dom::active_artboard(st), }; let paste = matches!(id, "edit.pasteInPlace" | "edit.pasteInFront" | "edit.pasteInBack"); let fit_art = id == "artboard.fitToArt"; @@ -314,10 +327,27 @@ pub(crate) fn on_active_artboard(s: &crate::Session, start: &[(u64, usize)], id: return params; } let picks = if paste || fit_art { crate::cmd::artboard_tool_picks(s) } else { Vec::new() }; - if picks.is_empty() { + let kept: Vec = match start.picks { + Some((uid, list)) if picks.is_empty() && (paste || fit_art) && *uid == st.uid && s.tool_id() == "artboard" => { + list.iter().copied().filter(|i| *i < n).collect() + } + _ => Vec::new(), + }; + if kept.len() >= 2 { + p.insert((if fit_art { "indices" } else { "artboards" }).into(), json!(kept)); + } else if picks.is_empty() { p.insert(key.into(), json!(active)); } else if fit_art { p.insert("indices".into(), json!(picks)); } params } + +/// What [`on_active_artboard`] reads besides the session: the index of each open document's active +/// artboard as the run started, by document uid; the Artboard tool's selection as the run started, +/// with its document's uid; and the `artboard` a step's recorded `command.batch` names. +pub(crate) struct Start<'a> { + pub active: &'a [(u64, usize)], + pub picks: Option<&'a (u64, Vec)>, + pub batch: Option, +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 770934ce98..f2eeaa57ee 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -810,6 +810,10 @@ struct Host { /// The index of each open document's active artboard as the run starts, by document uid. The /// view keeps that index while the run goes on, so the steps `app.doScript` plays act on it. active_artboards: Vec<(u64, usize)>, + /// The artboards the Artboard tool had selected in the active document as the run starts (two or + /// more), with that document's uid. The run gives the tool fresh state, which drops them, so the + /// steps `app.doScript` plays read them here. + artboard_picks: Option<(u64, Vec)>, } /// A run's host calls by kind, as its report gives them in `hostCallCounts`. @@ -1963,6 +1967,9 @@ impl Session { if self.script_copy_first && self.docs.iter().any(DocState::is_dirty) && cmd::recovery::save_copies(self).is_err() { return Err(EngineError::Other(NO_RECOVERY_COPY.to_string())); } + // The Artboard tool's selection, which the fresh tool state below drops. + let picks = cmd::artboard_tool_picks(self); + let artboard_picks = self.active().filter(|_| !picks.is_empty()).map(|d| (d.uid, picks)); self.reset_tool(); let open: Vec = self.docs.iter().map(|d| d.uid).collect(); self.script_high_water.retain(|uid, _| open.contains(uid)); @@ -2075,6 +2082,7 @@ impl Session { dom: dom::State::default(), actions: request.actions, active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, }); *link.borrow_mut() = Some(host.clone()); let args = match to_data(&Value::Object(request.args), &DataLimits::default(), 0, &mut (0, 0)) { diff --git a/crates/engine/src/tests/script_actions.rs b/crates/engine/src/tests/script_actions.rs index 4fbcd55751..1432b8671b 100644 --- a/crates/engine/src/tests/script_actions.rs +++ b/crates/engine/src/tests/script_actions.rs @@ -262,6 +262,31 @@ fn steps_act_on_the_artboard_active_as_they_run() { assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it"); } +/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none, +/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it. +#[test] +fn a_batch_steps_artboard_holds_for_its_steps_that_name_none() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + make_active(&mut s, 1); + let align = json!({"command": "object.align", "params": {"horizontal": "left", "to": "artboard"}}); + let mut own = align.clone(); + own["params"]["artboard"] = json!(1); + let batch = |artboard: u64, step: &Value| json!({"command": "command.batch", "params": {"artboard": artboard, "commands": [step]}}); + let actions = set(&[("First", vec![batch(0, &align)]), ("Past", vec![batch(9, &align)]), ("Own", vec![batch(0, &own)])]); + let left = |s: &Session| s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap().x0; + log_with(&mut s, "app.doScript('First', 'Set');", &actions); + assert_eq!(left(&s), was[0].x0, "the batch's artboard 0"); + log_with(&mut s, "app.doScript('Past', 'Set');", &actions); + assert_eq!(left(&s), was[2].x0, "past the last artboard, the last one"); + log_with(&mut s, "app.doScript('Own', 'Set');", &actions); + assert_eq!(left(&s), was[1].x0, "a step that names artboard 1 keeps it"); +} + /// The active artboard a step gets is the index it had as the run started: after a step deletes an /// artboard before it, the artboard now at that index, as the view shows it. #[test] @@ -269,7 +294,8 @@ fn steps_keep_the_active_artboards_index() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); let uid = s.active().unwrap().uid; - let add = |s: &Session| script::actions::on_active_artboard(s, &[(uid, 1)], "object.align", &json!({})); + let start = script::actions::Start { active: &[(uid, 1)], picks: None, batch: None }; + let add = |s: &Session| script::actions::on_active_artboard(s, &start, "object.align", &json!({})); assert_eq!(add(&s), json!({"artboard": 1})); s.execute("artboard.delete", &json!({"index": 0})).unwrap(); assert_eq!(add(&s), json!({"artboard": 1}), "the artboard now at index 1"); @@ -310,7 +336,8 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { let mut s = Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 3})).unwrap(); make_active(&mut s, 1); - let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &[], id, &json!({})); + let start = script::actions::Start { active: &[], picks: None, batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); assert_eq!(add(&s, "edit.pasteInPlace"), json!({"artboard": 1})); assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); @@ -323,3 +350,47 @@ fn paste_and_fit_steps_keep_the_artboard_tools_selection() { assert_eq!(add(&s, "object.align"), json!({"artboard": 1})); assert_eq!(add(&s, "shape.rectangle"), json!({})); } + +/// The Artboard tool's selection as `script.run` starts holds for the steps `app.doScript` plays, +/// though the run gives the tool fresh state: a paste step pastes on those artboards and a Fit to +/// Artwork Bounds step fits them. +#[test] +fn a_run_keeps_the_artboard_tools_selection_for_its_steps() { + // Three artboards with a rectangle on each, artboard 1 active and the Artboard tool holding 0 and 2. + let setup = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap(); + let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + let mut art = Vec::new(); + for b in &was { + let id = s.execute("shape.rectangle", &json!({"x": b.x0 + 10.0, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setStroke", &json!({"none": true})).unwrap(); + art.push(s.active().unwrap().doc.bounds_of(&[vectorcraft_doc::NodeId(id)], false).unwrap()); + } + s.execute("edit.copy", &json!({})).unwrap(); + make_active(&mut s, 1); + s.select_tool("artboard", crate::tooling::ViewInfo::default()).unwrap(); + s.set_tool_option("selected", &json!([0, 2])); + (s, was, art) + }; + let actions = set(&[("Paste", vec![json!({"command": "edit.pasteInPlace"})]), ("Fit", vec![json!({"command": "artboard.fitToArt"})])]); + let (mut s, ..) = setup(); + let before = objects(&s); + log_with(&mut s, "app.doScript('Paste', 'Set');", &actions); + assert_eq!(objects(&s), before + 2, "one copy on each selected artboard"); + let (mut s, was, art) = setup(); + log_with(&mut s, "app.doScript('Fit', 'Set');", &actions); + let boards: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect(); + assert_eq!(boards, [art[0], was[1], art[2]], "the selected artboards fit their art"); + // A kept artboard past the last one is left out; with fewer than two left, the active one applies. + let (mut s, ..) = setup(); + s.reset_tool(); + let uid = s.active().unwrap().uid; + let kept = (uid, vec![0, 2]); + let start = script::actions::Start { active: &[(uid, 1)], picks: Some(&kept), batch: None }; + let add = |s: &Session, id: &str| script::actions::on_active_artboard(s, &start, id, &json!({})); + assert_eq!(add(&s, "edit.pasteInBack"), json!({"artboards": [0, 2]})); + assert_eq!(add(&s, "artboard.fitToSelection"), json!({"index": 1})); + s.execute("artboard.delete", &json!({"index": 2})).unwrap(); + assert_eq!(add(&s, "artboard.fitToArt"), json!({"index": 1})); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index ef7c97e951..8bf497bafe 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -80,8 +80,8 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents getIsFileOpen \ - selection typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + getIsFileOpen loadAction loadAction= selection typename unloadAction unloadAction=", ), ("Documents.", "prototype"), ("Documents.prototype.", "add addDocument constructor getByName index length parent typename"), diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 9c0563b849..e77eb31143 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -589,15 +589,25 @@ pub(crate) fn has_stop(commands: &[Value]) -> bool { /// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel /// order, with its steps as playback runs them ([`Action::playback_steps`]) and each step's place in /// the action. An action that `actions` cannot hold (a step that is not a command, a name that is -/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +/// too long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out, and so +/// is every other action of its set with its name, so that a name two actions share is never one a +/// script can play. pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { + use std::collections::HashMap; use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, parse}; let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; if p.contains_key("actions") { return; } + let all = || app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))); + // How many actions of the panel have each set's name and action's name, and how many of them + // `actions` holds. + let mut named: HashMap<(&str, &str), (usize, usize)> = HashMap::new(); + for (set, a) in all() { + named.entry((set.name.as_str(), a.name.as_str())).or_default().0 += 1; + } let (mut list, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); - for (set, a) in app.ui.action_sets.iter().flat_map(|set| set.actions.iter().map(move |a| (set, a))) { + for (set, a) in all() { if list.len() >= MAX_ACTIONS { break; } @@ -636,10 +646,18 @@ pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Va } steps += count; bytes += size; + if let Some(n) = named.get_mut(&(set.name.as_str(), a.name.as_str())) { + n.1 += 1; + } if let Value::Array(mut one) = one { list.append(&mut one); } } + let partly = |e: &Value| { + let key = (e["set"].as_str().unwrap_or_default(), e["name"].as_str().unwrap_or_default()); + named.get(&key).is_some_and(|(panel, held)| held < panel) + }; + list.retain(|e| !partly(e)); p.insert("actions".into(), Value::Array(list)); } @@ -7542,6 +7560,27 @@ mod tests { assert_eq!(objects(&app), 2); } + /// A name two actions of a set share stays a name a script can't play when `actions` leaves one + /// of them out: the other is left out too. + #[test] + fn a_script_cant_play_a_name_two_actions_share() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + let rect = ("shape.rectangle".to_string(), json!({"x": 0, "y": 10, "width": 10, "height": 10})); + let good = Action::new("Twin", vec![rect.clone()]); + let odd = Action::new("Twin", vec![rect.clone(), ("select.none".to_string(), json!(5))]); + app.ui.action_sets.push(ActionSet::new("Mine", vec![good, odd, Action::new("Other", vec![rect])])); + let mut params = json!({}); + add_script_actions(&app, "script.run", &mut params); + let mine: Vec<_> = params["actions"].as_array().into_iter().flatten().filter(|a| a["set"] == "Mine").map(|a| a["name"].clone()).collect(); + assert_eq!(mine, [json!("Other")]); + app.session.script_frames = false; + let source = "try { app.doScript('Twin', 'Mine'); vc.log('ran'); } catch (e) { vc.log(e.message); }"; + let r = app.run("script.run", json!({"source": source, "name": "t.js"})).unwrap(); + assert_eq!(r["log"], json!(["the set “Mine” has no action “Twin”"])); + assert_eq!(app.session.active().map_or(0, |d| d.doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum::()), 0); + } + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 6b507eab99..0062ea6218 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2689,10 +2689,12 @@ app through the global object `vc`, and writes to the Script Console and runs ot Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one - past the end. While the Artboard tool has several artboards selected, a paste step and a Fit to Artwork Bounds step - act on those instead, as in the panel's playback. VectorCraft's own rules: the action and its set are matched by - their exact names, and a name that matches no action or more than one throws an error before any step runs, as does - an action with no included step. A stop, and a step whose command a script may not run or the engine does not have + past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to + Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that + names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's + own rules: the action and its set are matched by their exact names, and a name that matches no action or more than + one throws an error before any step runs, as does an action with no included step. When the app leaves an action + out of `actions`, it also leaves out every other action of that set with the same name. A stop, and a step whose command a script may not run or the engine does not have (a View menu step, or a step that plays an action or runs a script), throw an error that names the step before any step runs, as does such a command among the commands a Batch step (`action.batch`) plays on each file, so an action cannot play itself. From d82fe4e8d90b9d6a80632593fc820d009770d973 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:54:45 -0800 Subject: [PATCH 4/9] Scripts: nextFrame, previousFrame, story and document.stories for threaded type Text frames get nextFrame, previousFrame and story, and documents get stories, a Stories collection with one story for each thread and each type object in no thread. Assigning nextFrame or previousFrame links the last frame of one story to the first frame of another, and null breaks the link with each frame keeping its text; loops, links to the frame itself or into the middle of a story, point type, frames of another document and hidden or locked frames are refused with nothing changed. A story of two or more frames reads and writes its text across its frames in UTF-16 units, and areaText and pathText take baseFrame and postFix to thread the new frame to an existing one. The new command text.thread.setNeighbor {id, side, neighbor} links or breaks by id without a selection, for MCP, the CLI and vc.run. --- crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/engine/src/cmd/threads.rs | 115 +++ crates/engine/src/script/dom.rs | 1 + crates/engine/src/script/dom/text.rs | 34 +- crates/engine/src/script/dom/text/threads.rs | 786 ++++++++++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_threads.rs | 596 +++++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 34 +- docs/gaps.md | 6 +- docs/mcp.md | 41 +- docs/target-app-parity.md | 1 + 11 files changed, 1598 insertions(+), 18 deletions(-) create mode 100644 crates/engine/src/script/dom/text/threads.rs create mode 100644 crates/engine/src/tests/script_threads.rs 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`. From a5690d2d35485db131a6adb6be3c9c5c3136993c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:08:05 -0800 Subject: [PATCH 5/9] 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. --- crates/engine/src/script/dom/text/threads.rs | 74 +++++++++++++++----- crates/engine/src/tests/script_threads.rs | 27 ++++++- docs/mcp.md | 4 +- docs/roadmap.md | 2 +- docs/target-app-parity.md | 2 +- 5 files changed, 84 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index ee81129944..cfdb4119c6 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -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, 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 {} - 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| { + 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 { ("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)), diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 6d919a21d9..433cc041e7 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -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() { diff --git a/docs/mcp.md b/docs/mcp.md index 99d79dd67c..5db12d3918 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -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 diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..ab191ea587 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -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 ``/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 , 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 355a11543a..17698d2eb6 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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`. From 9c74e2f3ba6070c758971c5bc40cc6c824071f40 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:04:58 -0800 Subject: [PATCH 6/9] Scripts: the host name table lists only the members the host defines --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 448e558c32..e12077408e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -100,7 +100,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= stories swatches swatches= symbols symbols= textFrames textFrames= toString \ + rulerUnits saveAs saveAs= selection selection= stories swatches swatches= symbols symbols= textFrames toString \ typename views views= width", ), ("Layer.", "prototype"), From 46c3e4bcff3ede242e8ed32bec591a50e9778998 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:43:17 -0800 Subject: [PATCH 7/9] Scripts: text and thread tests read frames topmost first, as pageItems lists them --- crates/engine/src/script/dom/text/threads.rs | 2 +- crates/engine/src/tests/script_text.rs | 10 +-- crates/engine/src/tests/script_threads.rs | 74 ++++++++++---------- docs/mcp.md | 4 +- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/crates/engine/src/script/dom/text/threads.rs b/crates/engine/src/script/dom/text/threads.rs index cfdb4119c6..e96282ba93 100644 --- a/crates/engine/src/script/dom/text/threads.rs +++ b/crates/engine/src/script/dom/text/threads.rs @@ -14,7 +14,7 @@ //! - 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 +//! in the order of their first frames in `document.textFrames`, topmost first. `index` with a string finds the first story whose //! first frame has that name. //! - The text of a story of two or more frames is its frames' text in thread order. Its ranges keep //! their place through edits made through them, as a frame's ranges do, and are stale after any diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index a357ecfe40..e711768477 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -62,7 +62,7 @@ fn text_frames_add_point_area_and_path_type() { var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ vc.log(pt.typename); vc.log(pt instanceof TextFrame && pt instanceof PageItem);\ - vc.log(d.textFrames[3].contents); vc.log(d.textFrames[9] === undefined);\ + vc.log(d.textFrames[0].contents); vc.log(d.textFrames[9] === undefined);\ vc.log(at.orientation); vc.log(d.textFrames.parent.typename);", ); assert_eq!(out[0], json!(4)); @@ -492,16 +492,16 @@ fn collections_of_text_add_words_characters_and_paragraphs() { let (mut s, id) = doc_with("ab"); s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap(); let before = undo_steps(&s); - let out = log(&mut s, "var n = app.activeDocument.textFrames[1].words.add(''); vc.log([n.length, n.start]);"); + let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);"); assert_eq!(out, vec![json!([0, 5])]); for (call, want) in [ ("t.words.add(null)", "contents must be a string or a number"), ("t.words.add('x', t.words[0], 'after')", "insertionLocation must be"), ("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"), - ("t.words.add('x', app.activeDocument.textFrames[0])", "same text frame"), + ("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"), ("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"), ] { - let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[1]; {call};")); + let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};")); assert!(e.contains(want), "{call}: {e}"); } assert_eq!(undo_steps(&s), before); @@ -586,7 +586,7 @@ fn type_made_with_a_large_id_is_the_new_type() { fn text_members_refuse_objects_of_other_classes() { let (mut s, _) = doc_with("abc"); s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); - let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[1]);"); + let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextFrame.prototype, 'contents').get.call(app.activeDocument.pageItems[0]);"); assert!(e.contains("this is not a TextFrame"), "{e}"); let e = failure(&mut s, "Object.getOwnPropertyDescriptor(TextRange.prototype, 'contents').get.call(app.activeDocument.textFrames[0]);"); assert!(e.contains("this is not a TextRange"), "{e}"); diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index 433cc041e7..c8f5737dfc 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -73,14 +73,14 @@ fn stories_list_one_story_for_each_thread_and_each_frame_in_none() { area(&mut s, 400.0, 120.0, 40.0, "Alone"); let out = log( &mut s, - "var d = app.activeDocument, st = d.stories[0];\ + "var d = app.activeDocument, st = d.stories[1];\ vc.log(d.stories.length); vc.log(st.typename); vc.log(st.textFrames.length);\ vc.log(st.textFrames[0].nextFrame.previousFrame.contents === st.textFrames[0].contents);\ vc.log(st.textFrames[1].nextFrame === null && st.textFrames[0].previousFrame === null);\ - vc.log(d.stories[1].textFrames[0].contents); vc.log(d.stories[1].textFrames.length);\ + vc.log(d.stories[0].textFrames[0].contents); vc.log(d.stories[0].textFrames.length);\ d.textFrames.add(); vc.log(d.stories.length);\ vc.log(d.stories.parent.typename); vc.log(st.parent.typename); vc.log(d.stories.typename);\ - vc.log(d.textFrames[2].story.textFrames[0].contents);", + vc.log(d.textFrames[1].story.textFrames[0].contents);", ); assert_eq!( out, @@ -262,9 +262,9 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { 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];", + "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];\ + vc.log(app.activeDocument.stories.length); vc.log(t[1].previousFrame.contents); vc.log(t[2].story.textRange.contents);\ + t[2].nextFrame = t[1];", ); assert_eq!(out, vec![json!(2), json!("First story.Second."), json!("First story.Second.")]); assert_eq!(threads(&s), vec![vec![a, b]]); @@ -275,7 +275,7 @@ fn next_frame_joins_two_stories_in_one_undo_step_keeping_the_selection() { 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];"); + log(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[1];"); assert_eq!(threads(&s), vec![vec![b, a]]); assert_eq!(story(&s, &[b, a]), "Second.First story."); } @@ -287,9 +287,9 @@ fn null_breaks_the_link_and_each_frame_keeps_its_text() { 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;", + "var t = app.activeDocument.textFrames, st = t[0].story; t[0].previousFrame = null;\ + vc.log(app.activeDocument.stories.length); vc.log(st.textFrames.length); vc.log(t[1].nextFrame);\ + t[1].nextFrame = null;", ); assert_eq!(out, vec![json!(2), json!(1), json!(null)]); assert!(threads(&s).is_empty()); @@ -310,9 +310,9 @@ fn area_and_path_text_thread_the_new_frame_to_a_base_frame() { 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);\ + var after = d.textFrames.areaText(p[2], undefined, base);\ + var first = d.textFrames.areaText(p[1], TextOrientation.HORIZONTAL, base, false);\ + var last = d.textFrames.pathText(p[0], undefined, undefined, undefined, after, true);\ vc.log(base.story.textFrames.length); vc.log(base.previousFrame.kind); vc.log(after.nextFrame.kind); vc.log(d.stories.length);", ); assert_eq!(out, vec![json!(4), json!("TextType.AREATEXT"), json!("TextType.PATHTEXT"), json!(1)]); @@ -330,9 +330,9 @@ fn a_bad_base_frame_is_refused_before_a_frame_is_made() { 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!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0]);")).contains("only area type")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, p[0]);")).contains("baseFrame must be a TextFrame")); + assert!(failure(&mut s, &format!("{d} d.textFrames.areaText(p[0], undefined, d.textFrames[0], 'yes');")).contains("postFix")); assert_eq!((count(&s), undo_steps(&s)), (n, before)); } @@ -389,9 +389,9 @@ fn a_link_to_the_frame_itself_is_refused() { 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];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[3];"); assert!(m.contains("loop"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); assert!(m.contains("loop"), "{m}"); unchanged(&s, &ids, &before); } @@ -400,9 +400,9 @@ fn a_link_that_makes_a_loop_is_refused() { 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];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); assert!(m.contains("already has a previous frame"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].previousFrame = t[0];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].previousFrame = t[3];"); assert!(m.contains("already has a next frame"), "{m}"); unchanged(&s, &ids, &before); } @@ -411,13 +411,13 @@ fn a_link_into_the_middle_of_a_story_is_refused() { 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];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[0];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].previousFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].previousFrame = t[1];"); assert!(m.contains("only area type"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = 5;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = 5;"); assert!(m.contains("TypeError") && m.contains("TextFrame or null"), "{m}"); - let m = failure(&mut s, "app.activeDocument.textFrames[2].nextFrame = undefined;"); + let m = failure(&mut s, "app.activeDocument.textFrames[1].nextFrame = undefined;"); assert!(m.contains("TextFrame or null"), "{m}"); unchanged(&s, &ids, &before); } @@ -425,11 +425,11 @@ fn point_type_and_other_values_cannot_be_linked() { #[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;"); + log(&mut s, "app.activeDocument.textFrames[2].locked = true;"); let before = state(&s, &ids); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[1].nextFrame = t[2];"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[2].nextFrame = t[1];"); assert!(m.contains("hidden or locked"), "{m}"); - let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[0].nextFrame = null;"); + let m = failure(&mut s, "var t = app.activeDocument.textFrames; t[3].nextFrame = null;"); assert!(m.contains("hidden or locked"), "{m}"); unchanged(&s, &ids, &before); } @@ -441,12 +441,12 @@ fn a_frame_of_another_document_cannot_be_linked() { 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];"); + let m = failure(&mut s, "app.documents[0].textFrames[1].nextFrame = app.documents[1].textFrames[0];"); assert!(m.contains("different documents"), "{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)); }\ + "var d = app.documents[1], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ vc.log(p.typename); vc.log(d.textFrames.length);", ); assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]); @@ -457,16 +457,16 @@ fn a_frame_of_another_document_cannot_be_linked() { #[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;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.length;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], st = f.story; f.remove(); st.lines;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], st = f.story; f.remove(); st.lines;"); assert!(m.contains("Stale story"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], g = app.activeDocument.textFrames[1]; g.remove(); f.nextFrame = g;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], g = app.activeDocument.textFrames[0]; g.remove(); f.nextFrame = g;"); assert!(m.contains("Stale page item"), "{m}"); - let m = failure(&mut s, "var f = app.activeDocument.textFrames[0], r = f.story.textRange; f.remove(); r.contents;"); + let m = failure(&mut s, "var f = app.activeDocument.textFrames[1], r = f.story.textRange; f.remove(); r.contents;"); assert!(m.contains("Stale text range"), "{m}"); // A story read from a frame that stays follows it when its link is broken. - let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[1].story; t[0].nextFrame = null; vc.log(st.textFrames.length);"); + let out = log(&mut s, "var t = app.activeDocument.textFrames, st = t[0].story; t[1].nextFrame = null; vc.log(st.textFrames.length);"); assert_eq!(out, vec![json!(1)]); } @@ -481,7 +481,7 @@ fn stories_refuse_bad_keys_and_huge_numbers() { 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';"); + log(&mut s, "app.activeDocument.textFrames[1].name = 'Lead';"); assert_eq!(log(&mut s, "vc.log(app.activeDocument.stories.index('Lead').textFrames.length);"), vec![json!(2)]); } @@ -537,7 +537,7 @@ fn stories_of_threads_that_share_a_frame_keep_their_own_text() { 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 out = log(&mut s, "var t = app.activeDocument.textFrames; vc.log(t[1].story.length); vc.log(t[0].story.length);"); let (ab, bc) = (story(&s, &[a, b]).encode_utf16().count(), story(&s, &[b, c]).encode_utf16().count()); assert_ne!(ab, bc); assert_eq!(out, vec![json!(ab), json!(bc)]); diff --git a/docs/mcp.md b/docs/mcp.md index d9ca3ba49e..772917dad0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2912,8 +2912,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 + `Document.stories` lists one story for each type object in no thread and one for each thread, in the order of + their first frames in `Document.textFrames`, topmost first, and `index` with a string finds the first story whose first frame has that name. A frame that a stored thread lists twice is in its story once. A `Story` is the story of the frame it was read from, as that frame is threaded now, and throws `Stale story` once that frame is deleted. The text of a story of one frame is that frame's text, with its ranges. The text of a longer story is its From a2e04d98e0850305caa2fb50470ac8314546b5d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:51:03 -0800 Subject: [PATCH 8/9] Scripts: a script run after the startup scripts plays the Actions panel's actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With Run Startup Scripts on, File › Scripts runs the chosen script as `script.startup.run`'s `then`, and the app gave the Actions panel's actions only to `script.run`'s own parameters. `app.doScript` in that script then found no action set. The app now gives `then` the panel's actions as well, unless the caller gave its own. --- crates/ui-egui/src/panels/actions/playback.rs | 18 ++++++++++++------ .../src/panels/actions/tests_playback.rs | 13 +++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index fccf301699..bff0bd1d4d 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -39,14 +39,20 @@ fn playback_steps(action: &Action) -> Vec { .collect() } -/// For command `id` `script.run`: gives its `params` the panel's actions as `actions`, which the -/// script's `app.doScript` plays, unless the caller gave them: every action of every set, in panel -/// order, with its steps as playback runs them ([`playback_steps`]) and each step's place in the -/// action. An action that `actions` cannot hold (a step that is not a command, a name that is too -/// long, or one past the limits of [`vectorcraft_engine::script::actions`]) is left out. +/// For command `id` `script.run`, or the script of `script.startup.run`'s `then`: gives its +/// `params` the panel's actions as `actions`, which the script's `app.doScript` plays, unless the +/// caller gave them: every action of every set, in panel order, with its steps as playback runs +/// them ([`playback_steps`]) and each step's place in the action. An action that `actions` cannot +/// hold (a step that is not a command, a name that is too long, or one past the limits of +/// [`vectorcraft_engine::script::actions`]) is left out. pub(crate) fn add_script_actions(app: &VectorcraftApp, id: &str, params: &mut Value) { use vectorcraft_engine::script::actions::{MAX_ACTIONS, MAX_ACTIONS_BYTES, MAX_ALL_STEPS, Playable, parse}; - let Some(p) = params.as_object_mut().filter(|_| id == "script.run") else { return }; + let target = match id { + "script.run" => Some(params), + "script.startup.run" => params.get_mut("then"), + _ => None, + }; + let Some(p) = target.and_then(Value::as_object_mut) else { return }; if p.contains_key("actions") { return; } diff --git a/crates/ui-egui/src/panels/actions/tests_playback.rs b/crates/ui-egui/src/panels/actions/tests_playback.rs index 2b9a8225b5..f566eb22fc 100644 --- a/crates/ui-egui/src/panels/actions/tests_playback.rs +++ b/crates/ui-egui/src/panels/actions/tests_playback.rs @@ -674,6 +674,19 @@ fn a_script_plays_the_panels_actions() { assert_eq!(objects(&app), 2); } +/// The script that `script.startup.run` runs after the startup scripts (its `then`) plays the +/// panel's actions too, as File › Scripts runs a script with Run Startup Scripts on. +#[test] +fn the_script_after_the_startup_scripts_plays_the_panels_actions() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + push_set(&mut app, "Mine", vec![action("Draw", &[("shape.rectangle", json!({"x": 0, "y": 10, "width": 10, "height": 10}))])]); + app.session.script_frames = false; + let then = json!({"source": "try { app.doScript('Draw', 'Mine'); vc.log('ok'); } catch (e) { vc.log(e.message); }", "name": "t.js"}); + let r = app.run("script.startup.run", json!({"reason": "menu", "then": then})).unwrap(); + assert_eq!(r["then"]["log"], json!(["ok"]), "{r}"); +} + /// The steps a script's `app.doScript` plays act on the view's active artboard, as the panel's /// playback does: Align to Artboard in a recorded batch, and Fit to Selected Art. #[test] From 9fb14228c13a6094e15c866fc3c857c3e433c9d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:54:37 -0800 Subject: [PATCH 9/9] Scripts: the cross-document thread test reads app.documents active document first app.documents now lists the active document first, so after file.new the new document is documents[0] and the document with the three frames is documents[1]. The test picks each document by that order. --- crates/engine/src/tests/script_threads.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_threads.rs b/crates/engine/src/tests/script_threads.rs index c8f5737dfc..00139a4eda 100644 --- a/crates/engine/src/tests/script_threads.rs +++ b/crates/engine/src/tests/script_threads.rs @@ -441,12 +441,12 @@ fn a_frame_of_another_document_cannot_be_linked() { 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[1].nextFrame = app.documents[1].textFrames[0];"); + let m = failure(&mut s, "app.documents[1].textFrames[1].nextFrame = app.documents[0].textFrames[0];"); assert!(m.contains("different documents"), "{m}"); let out = log( &mut s, - "var d = app.documents[1], p = d.pageItems[0];\ - try { d.textFrames.areaText(p, undefined, app.documents[0].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ + "var d = app.documents[0], p = d.pageItems[0];\ + try { d.textFrames.areaText(p, undefined, app.documents[1].textFrames[1]); } catch (e) { vc.log(String(e.message)); }\ vc.log(p.typename); vc.log(d.textFrames.length);", ); assert_eq!(out, vec![json!("baseFrame: the frame is in another document"), json!("PathItem"), json!(1)]);