From 3ef896191383d4201f17da9b9925f4b237aa1d48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 13:34:22 -0800 Subject: [PATCH 01/20] 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 02/20] 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 03/20] 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 69448d0c2387ca69d22019ef8cee6eeb8591c5e6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:16:56 -0800 Subject: [PATCH 04/20] Scripts: character and paragraph styles for scripts document.characterStyles and document.paragraphStyles list a document's styles, the Normal style first, and add, find and remove them. Each CharacterStyle and ParagraphStyle has a name, its attributes, applyTo with clearingOverrides, and remove; setting an attribute redefines the style through charStyle.setAttrs or paraStyle.setAttrs. A text range's characterStyles and paragraphStyles list the styles its text is in. Style names are trimmed and must have 1 to 256 characters and no control characters, one run names at most 4,096 styles, and a style object throws Stale style once its style is removed or renamed by a command. ParagraphStyle.characterAttributes is not available yet. charStyle.load, paraStyle.load and textStyle.loadAll refuse a file larger than 64 MB without reading it in full. --- crates/engine/src/cmd/textstyles.rs | 12 +- crates/engine/src/cmd/textstyles/tests.rs | 18 + crates/engine/src/script/dom.rs | 6 + crates/engine/src/script/dom/text.rs | 13 +- crates/engine/src/script/dom/text/styles.rs | 715 ++++++++++++++++++++ crates/engine/src/script/mod.rs | 3 + crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_styles.rs | 331 +++++++++ docs/mcp.md | 27 +- docs/target-app-parity.md | 3 +- 10 files changed, 1121 insertions(+), 8 deletions(-) create mode 100644 crates/engine/src/script/dom/text/styles.rs create mode 100644 crates/engine/src/tests/script_styles.rs diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index cde1456589..3b57c2e067 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -148,8 +148,11 @@ macro_rules! style_cmds { }; } +/// The largest document `charStyle.load`, `paraStyle.load` and `textStyle.loadAll` read, in bytes. +pub const MAX_LOAD_BYTES: usize = 64 << 20; + /// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`. -const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; +const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats; at most 64 MB) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind"; pub fn specs() -> Vec { let mut v = style_cmds!( @@ -1266,12 +1269,17 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { _ => "textStyle.loadAll".to_string(), }; let path = str_param(p, "path"); + let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file(path)?, + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, (None, Some(text), _) => text.as_bytes().to_vec(), + (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; + if bytes.len() > MAX_LOAD_BYTES { + return Err(too_large()); + } let file = str_param(p, "name").or(path).unwrap_or("Styles"); let src = super::fileio::load(file, &bytes).map_err(|e| bad(c, e.to_string()))?; if src.preview_only { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index e8f57aa14f..1f8511d7ac 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -830,6 +830,24 @@ fn load_all_styles_loads_both_kinds_in_one_step() { assert_eq!(s.doc().unwrap().doc, before); } +/// A file or `dataBase64` larger than 64 MB loads nothing and is not read past the limit. +#[test] +fn loading_refuses_a_file_larger_than_64_mb() { + let (mut s, _) = session_with_text("Title"); + let dir = std::env::temp_dir().join(format!("vc-load-styles-big-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Big.vectorcraft"); + std::fs::File::create(&path).unwrap().set_len(MAX_LOAD_BYTES as u64 + 1).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let r = s.execute("charStyle.load", &json!({"path": path.to_string_lossy()})); + std::fs::remove_dir_all(&dir).ok(); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); + let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + assert_eq!(s.doc().unwrap().doc, before); +} + /// A loaded character style whose size, scale, leading, shift, warichu Line Gap or stroke width is /// out of the range `charStyle.new` takes is skipped. #[test] diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index bef4c60707..87a6310ec3 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -581,6 +581,11 @@ fn on_doc( Ok(v) } +/// Marks stale the style objects whose styles a command the run ran removed or renamed. +pub(super) fn after_command(h: &Host) { + text::styles::after_command(h); +} + /// Runs `id` with `params` on the item's document, its selection kept. fn edit_item(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result { on_doc(h, item.doc.uid, true, |h| command(h, id, params)) @@ -1868,6 +1873,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("textFrames", text::doc_text_frames(l)), ("selection", property(l, doc_selection, doc_set_selection)), ]); + document.extend(text::styles::doc_members(l)); document.extend( ["layers", "artboards", "pathItems", "groupItems", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] .into_iter() diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index c3ca9d1dbe..0366dec5dd 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 styles; + /// 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,8 @@ 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>>, + /// The styles the run's style objects name. + styles: styles::StyleState, } fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> { @@ -1504,6 +1508,7 @@ pub(super) fn classes(l: &Link) -> Vec { ("remove", method(l, range_remove)), ]); range.extend(attr_members(l)); + range.extend(styles::range_members(l)); range.extend( [ "lines", @@ -1511,8 +1516,6 @@ pub(super) fn classes(l: &Link) -> Vec { "textRanges", "story", "kerning", - "characterStyles", - "paragraphStyles", "textSelection", "changeCaseTo", "select", @@ -1537,7 +1540,7 @@ 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 mut out = vec![ class("TextFrame", Some("PageItem"), frame, None), class("TextRange", None, range, None), part("Characters"), @@ -1586,7 +1589,9 @@ pub(super) fn classes(l: &Link) -> Vec { ]), None, ), - ] + ]; + out.extend(styles::classes(l)); + out } #[cfg(test)] diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs new file mode 100644 index 0000000000..f2e140bd45 --- /dev/null +++ b/crates/engine/src/script/dom/text/styles.rs @@ -0,0 +1,715 @@ +//! Character and paragraph styles in the script object model: `document.characterStyles` and +//! `document.paragraphStyles`, each `CharacterStyle` and `ParagraphStyle`, and the styles the text +//! of a `TextRange` uses, as the help pages +//! , +//! , +//! , +//! and +//! describe them. +//! +//! VectorCraft's own rules, which the help pages do not state: +//! - A document's collection lists its Normal style first, then its other styles in the order the +//! panel lists them. +//! - A style object names its style for the rest of the run, also after the script renames it +//! through `name`. Once the style is removed, or renamed or removed other than through the object +//! model, or its document is closed, every member throws `Stale style`; a style added later under +//! the same name is another style. +//! - A style name is trimmed, and must then be 1 to 256 characters long with no control +//! characters. +//! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the +//! style does not set. Setting one redefines the style: text in the style takes the new value +//! where it had the style's old one and keeps its other changes. +//! - `applyTo(text, clearingOverrides)` takes a text range, a text frame, or the characters, words +//! or paragraphs of one, in the style's document. A character style styles exactly that text and +//! changes nothing on an empty range; a paragraph style styles every paragraph the text touches. +//! `clearingOverrides` left out is false; true resets the text to the Normal style first. +//! - A range's `characterStyles` and `paragraphStyles` list each style its characters or +//! paragraphs are in once, in the order the text first uses it, with the Normal style for text in +//! no other style. They do not add or remove styles. +//! - `remove()` and `removeAll()` never remove a Normal style. Text in a removed style keeps its +//! look and is in the Normal style after. +//! - A script loads the styles of another document with `vc.run('charStyle.load', {path: ...})`, +//! `paraStyle.load` or `textStyle.loadAll`, which read only a file the script may read. + +use std::cell::RefCell; +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_doc::{CharStyle, Shared, TextObject, TextStyleDef}; +use vectorcraft_geom::Point; +use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostMember, host_ref}; + +use super::{ + ATTRS, Answer, Attr, Doc, Host, Link, NOT_FOUND, PARA_ATTRS, ParaAttr, Span, arg, attr_param, class, command, doc_of, doc_ref, float, font_ref, + function, get, handle_of, item_of, method, named, num, on_doc, para_param, para_range, property, range_ref, resolve, span_of, styles_in, text, + text_of, this_range, typename_of, usize_of, whole_span, with_doc, +}; +use crate::DocState; +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA, style_attrs}; + +/// The error of a style object whose style is gone. +pub const STALE_STYLE: &str = "Stale style"; +/// The longest style name, in characters, after trimming. +pub const MAX_STYLE_NAME: usize = 256; +/// The most styles one run's style objects name. +pub const MAX_HELD: usize = 4096; + +/// A style that a run's style objects name: its document, its kind and its name now. +struct Slot { + uid: u64, + para: bool, + name: String, + live: bool, +} + +/// A document's uid and its character and paragraph style lists when the slots were last checked. +type Seen = (u64, Shared>, Shared>); + +/// The styles a run's style objects name; an object holds its slot's number. +#[derive(Default)] +pub(super) struct StyleState { + slots: RefCell>, + seen: RefCell>, +} + +/// Marks stale each style object whose style the command just run removed or renamed, so a style +/// removed and made again under its name by later commands is another style. A document whose +/// style lists did not change is not checked again. +pub(in crate::script) fn after_command(h: &Host) { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + if !slots.iter().any(|s| s.live) { + return; + } + let s = h.session.borrow(); + let mut seen = h.dom.text.styles.seen.borrow_mut(); + seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); + for st in s.documents() { + let same = seen.iter().any(|(uid, c, p)| *uid == st.uid && Shared::ptr_eq(c, &st.doc.char_styles) && Shared::ptr_eq(p, &st.doc.para_styles)); + if same { + continue; + } + seen.retain(|(uid, ..)| *uid != st.uid); + seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { + slot.live = has_style(st, slot.para, &slot.name); + } + } + for slot in slots.iter_mut().filter(|x| x.live) { + if !s.documents().iter().any(|d| d.uid == slot.uid) { + slot.live = false; + } + } +} + +fn normal(para: bool) -> &'static str { + if para { NORMAL_PARA } else { NORMAL_CHAR } +} + +fn cmd(para: bool, verb: &str) -> String { + format!("{}.{verb}", if para { "paraStyle" } else { "charStyle" }) +} + +fn style_class(para: bool) -> &'static str { + if para { "ParagraphStyle" } else { "CharacterStyle" } +} + +fn list_class(para: bool) -> &'static str { + if para { "ParagraphStyles" } else { "CharacterStyles" } +} + +fn defs(st: &DocState, para: bool) -> &Vec { + if para { &st.doc.para_styles } else { &st.doc.char_styles } +} + +/// The document's style names of a kind, the Normal style first. +fn names(st: &DocState, para: bool) -> Vec { + let mut out = vec![normal(para).to_string()]; + out.extend(defs(st, para).iter().map(|d| d.name.clone()).filter(|n| n != normal(para))); + out +} + +fn has_style(st: &DocState, para: bool, name: &str) -> bool { + name == normal(para) || defs(st, para).iter().any(|d| d.name == name) +} + +fn stale() -> HostError { + HostError::Error(STALE_STYLE.into()) +} + +/// The style object for the style `name` of the document `uid`: the same slot as every other +/// object naming it in this run. +fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + Some(i) => i, + None => { + if slots.len() >= MAX_HELD { + return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + } + slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.len() - 1 + } + }; + Ok(host_ref(style_class(para), &[float(h.run), float(uid), float(i as u64)])) +} + +/// A style a style object names. +struct Style { + doc: Doc, + para: bool, + slot: usize, + name: String, +} + +/// The style `d` names, when it is an object of one of `classes` (with the kind each names). +fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result { + let found = classes.iter().find_map(|(c, para)| handle_of(d, c).map(|handle| (handle, *para))); + let Some((handle, para)) = found else { + return Err(HostError::Type(format!("this is not a {}", classes.first().map_or("CharacterStyle", |c| c.0)))); + }; + let [run, uid, slot] = handle.as_slice() else { return Err(stale()) }; + let doc = super::super::find_doc(h, *run, *uid).ok_or_else(stale)?; + let slot = usize_of(*slot).ok_or_else(stale)?; + let mut slots = h.dom.text.styles.slots.borrow_mut(); + let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; + if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + s.live = false; + return Err(stale()); + } + Ok(Style { doc, para, slot, name: s.name.clone() }) +} + +fn this_style(h: &Host, a: &[Data]) -> std::result::Result { + style_of(h, arg(a, 0), &[("CharacterStyle", false), ("ParagraphStyle", true)]) +} + +/// Marks the slots of the styles `names` of the document `uid` as removed. +fn forget(h: &Host, uid: u64, para: bool, names: &[String]) { + for s in h.dom.text.styles.slots.borrow_mut().iter_mut() { + if s.uid == uid && s.para == para && names.contains(&s.name) { + s.live = false; + } + } +} + +/// A style name a script gave, trimmed. +fn style_name(v: &Data) -> std::result::Result { + let Data::String(s) = v else { return Err(HostError::Type("a style name must be a string".into())) }; + if s.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + let t = s.trim(); + if t.is_empty() { + return Err(HostError::Range("a style name must not be empty".into())); + } + if t.chars().count() > MAX_STYLE_NAME { + return Err(HostError::Range(format!("a style name must be at most {MAX_STYLE_NAME} characters"))); + } + if t.chars().any(char::is_control) { + return Err(HostError::Range("a style name must not hold control characters".into())); + } + Ok(t.to_string()) +} + +/// Runs the style command `verb` of the kind on the document of `doc`. +fn run(h: &Host, doc: Doc, para: bool, verb: &str, params: &Value) -> std::result::Result { + on_doc(h, doc.uid, true, |h| command(h, &cmd(para, verb), params)) +} + +// ---- CharacterStyle and ParagraphStyle ---- + +fn style_name_get(h: &Host, a: &[Data]) -> Answer { + Ok(text(this_style(h, a)?.name)) +} + +/// `name = …`: renames the style; the Normal style keeps its name. +fn style_name_set(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let to = style_name(arg(a, 1))?; + if to == style.name { + return Ok(Data::Undefined); + } + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be renamed", style.name))); + } + if with_doc(h, style.doc, |_, st| has_style(st, style.para, &to)) { + return Err(HostError::Error(format!("a style named {to} already exists"))); + } + run(h, style.doc, style.para, "rename", &json!({"name": style.name, "to": to}))?; + forget(h, style.doc.uid, style.para, std::slice::from_ref(&to)); + if let Some(s) = h.dom.text.styles.slots.borrow_mut().get_mut(style.slot) { + s.name = to; + s.live = true; + } + Ok(Data::Undefined) +} + +fn style_parent(h: &Host, a: &[Data]) -> Answer { + Ok(doc_ref(h, this_style(h, a)?.doc.uid)) +} + +fn style_typename(h: &Host, a: &[Data]) -> Answer { + Ok(text(style_class(this_style(h, a)?.para))) +} + +fn attributes(h: &Host, a: &[Data], class: &str) -> Answer { + let style = this_style(h, a)?; + Ok(host_ref(class, &[float(h.run), float(style.doc.uid), float(style.slot as u64)])) +} + +fn style_character_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "CharacterStyleAttributes") +} + +fn style_paragraph_attributes(h: &Host, a: &[Data]) -> Answer { + attributes(h, a, "ParagraphStyleAttributes") +} + +/// `remove()`: deletes the style; its text keeps its look and is in the Normal style after. +fn style_remove(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + if style.name == normal(style.para) { + return Err(HostError::Error(format!("{} cannot be removed", style.name))); + } + run(h, style.doc, style.para, "delete", &json!({"name": style.name}))?; + forget(h, style.doc.uid, style.para, &[style.name]); + Ok(Data::Undefined) +} + +/// The text a style is applied to: a text range, a text frame, or the characters, words or +/// paragraphs of one. +fn target_span(h: &Host, d: &Data) -> std::result::Result { + if handle_of(d, "TextFrame").is_some() { + return Ok(whole_span(h, item_of(h, d)?)?.1); + } + const TEXT: [&str; 4] = ["TextRange", "Characters", "Words", "Paragraphs"]; + if !TEXT.iter().any(|c| handle_of(d, c).is_some()) { + return Err(HostError::Type("applyTo takes a TextRange or a TextFrame".into())); + } + span_of(h, d, &TEXT) +} + +/// `applyTo(textItem, clearingOverrides?)`. +fn style_apply_to(h: &Host, a: &[Data]) -> Answer { + let style = this_style(h, a)?; + let target = target_span(h, arg(a, 1))?; + let clear = match arg(a, 2) { + Data::Undefined => false, + Data::Bool(b) => *b, + _ => return Err(HostError::Type("clearingOverrides must be true or false".into())), + }; + if target.item.doc.uid != style.doc.uid { + return Err(HostError::Error("the text is in another document than the style".into())); + } + let (index, s, e, _) = resolve(h, target)?; + h.charge_call(16 + (e - s) as u64)?; + let (start, end) = if style.para { + let (_, ba, bb) = para_range(&index, s, e); + (ba, bb) + } else { + if s == e { + return Ok(Data::Undefined); + } + (index.byte(s, false), index.byte(e, true)) + }; + let p = json!({"name": style.name, "clearOverrides": clear, "id": target.item.id.0, "start": start, "end": end}); + run(h, style.doc, style.para, "apply", &p)?; + Ok(Data::Undefined) +} + +// ---- the attributes of a style ---- + +/// The style attribute each `text.setRangeStyle` parameter `attr_param` gives sets. +const CHAR_KEYS: [(&str, &str); 11] = [ + ("size", "size"), + ("leading", "leading"), + ("tracking", "tracking"), + ("baselineShift", "baseline_shift"), + ("hScale", "h_scale"), + ("vScale", "v_scale"), + ("rotation", "rotation"), + ("underline", "underline"), + ("strikethrough", "strikethrough"), + ("font", "font_family"), + ("style", "font_style"), +]; + +/// The script's `Justification` members and the alignments a paragraph style stores. +const JUSTIFY: [(&str, &str); 7] = [ + ("LEFT", "Left"), + ("CENTER", "Center"), + ("RIGHT", "Right"), + ("FULLJUSTIFYLASTLINELEFT", "JustifyLeft"), + ("FULLJUSTIFYLASTLINECENTER", "JustifyCenter"), + ("FULLJUSTIFYLASTLINERIGHT", "JustifyRight"), + ("FULLJUSTIFY", "JustifyAll"), +]; + +/// The style an attributes object belongs to and the attributes it sets. +fn attrs_of(h: &Host, a: &[Data], para: bool) -> std::result::Result<(Style, Map), HostError> { + let class = if para { "ParagraphStyleAttributes" } else { "CharacterStyleAttributes" }; + let style = style_of(h, arg(a, 0), &[(class, para)])?; + let attrs = with_doc(h, style.doc, |_, st| style_attrs(&st.doc, para, &style.name)).ok_or_else(stale)?; + Ok((style, attrs)) +} + +fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { + let n = |k: &str| m.get(k).and_then(Value::as_f64).map_or(Data::Undefined, num); + let b = |k: &str| m.get(k).and_then(Value::as_bool).map_or(Data::Undefined, Data::Bool); + match attr { + Attr::Size => n("size"), + Attr::Leading => n("leading"), + Attr::AutoLeading => match m.get("leading") { + Some(Value::Null) => Data::Bool(true), + Some(v) if v.is_number() => Data::Bool(false), + _ => Data::Undefined, + }, + Attr::Tracking => n("tracking"), + Attr::BaselineShift => n("baseline_shift"), + Attr::HorizontalScale => n("h_scale"), + Attr::VerticalScale => n("v_scale"), + Attr::Rotation => n("rotation"), + Attr::Underline => b("underline"), + Attr::StrikeThrough => b("strikethrough"), + Attr::TextFont => match m.get("font_family").and_then(Value::as_str) { + Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")), + None => Data::Undefined, + }, + } +} + +fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { + let (_, m) = attrs_of(h, a, false)?; + Ok(char_value(h, attr, &m)) +} + +/// Redefines the style with `attrs`, unless they are what it has. +fn redefine(h: &Host, style: &Style, old: &Map, attrs: Map) -> Answer { + if attrs == *old { + return Ok(Data::Undefined); + } + run(h, style.doc, style.para, "setAttrs", &json!({"name": style.name, "attrs": attrs}))?; + Ok(Data::Undefined) +} + +fn write_char(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, false)?; + // `autoLeading = false` keeps the leading auto leading gives the style's size in a paragraph + // with the default justification. + let base = CharStyle::default(); + let size = old.get("size").and_then(Value::as_f64).unwrap_or(base.size); + let leading = old.get("leading").and_then(Value::as_f64); + let sample = CharStyle { size, leading, ..base }; + let t = TextObject::point(Point::default(), "", sample.clone()); + let (param, _) = attr_param(h, attr, name, arg(a, 1), (&t, &sample, 0))?; + let mut attrs = old.clone(); + for (k, v) in param.as_object().into_iter().flatten() { + let Some((_, key)) = CHAR_KEYS.iter().find(|(p, _)| *p == k.as_str()) else { continue }; + let v = if *key == "leading" && v == "auto" { Value::Null } else { v.clone() }; + attrs.insert((*key).to_string(), v); + } + redefine(h, &style, &old, attrs) +} + +fn para_key(attr: ParaAttr) -> &'static str { + match attr { + ParaAttr::Justification => "justify", + ParaAttr::FirstLineIndent => "first_line_indent", + ParaAttr::LeftIndent => "left_indent", + ParaAttr::RightIndent => "right_indent", + ParaAttr::SpaceBefore => "space_before", + ParaAttr::SpaceAfter => "space_after", + } +} + +fn read_para(h: &Host, a: &[Data], attr: ParaAttr) -> Answer { + let (_, m) = attrs_of(h, a, true)?; + let v = m.get(para_key(attr)); + Ok(match attr { + ParaAttr::Justification => match v.and_then(Value::as_str) { + Some("Auto") => text("Justification.LEFT"), + Some(s) => JUSTIFY.iter().find(|(_, j)| *j == s).map_or(Data::Undefined, |(k, _)| text(format!("Justification.{k}"))), + None => Data::Undefined, + }, + _ => v.and_then(Value::as_f64).map_or(Data::Undefined, num), + }) +} + +fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer { + let (style, old) = attrs_of(h, a, true)?; + let (_, _, wants) = para_param(attr, name, arg(a, 1))?; + let value = match (&wants, attr) { + (Data::String(s), ParaAttr::Justification) => { + let m = s.strip_prefix("Justification.").unwrap_or(s); + let found = JUSTIFY.iter().find(|(k, _)| *k == m).map(|(_, j)| *j); + json!(found.ok_or_else(|| HostError::Type("justification must be a Justification value".into()))?) + } + (Data::Number(n), _) => json!(n), + _ => return Err(HostError::Type(format!("{name} must be a finite number"))), + }; + let mut attrs = old.clone(); + attrs.insert(para_key(attr).to_string(), value); + redefine(h, &style, &old, attrs) +} + +/// The body of a member that captures what it reads or sets. +type Body = Rc Answer>; + +/// Members whose getter and setter each charge the call, as [`function`] does. +fn charged(link: &Link, g: impl Fn(&Host, &[Data]) -> Answer + 'static, s: impl Fn(&Host, &[Data]) -> Answer + 'static) -> HostMember { + let wrap = |f: Body| -> HostFunction { + let l = link.clone(); + Rc::new(move |a: Vec| { + let h = super::super::current(&l)?; + h.charge_call(16 + a.iter().map(super::super::data_size).sum::())?; + f(&h, &a) + }) + }; + HostMember::Property { get: wrap(Rc::new(g)), set: wrap(Rc::new(s)) } +} + +fn char_members(link: &Link) -> Vec<(String, HostMember)> { + ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_char(h, a, attr), move |h, a| write_char(h, a, attr, name)))) + .collect() +} + +fn para_members(link: &Link) -> Vec<(String, HostMember)> { + PARA_ATTRS + .iter() + .map(|&(name, attr)| (name.to_string(), charged(link, move |h, a| read_para(h, a, attr), move |h, a| write_para(h, a, attr, name)))) + .collect() +} + +// ---- CharacterStyles and ParagraphStyles ---- + +/// What a collection of styles lists: a document's styles, or those a text range uses. +enum Of { + Doc(Doc), + Range(Span), +} + +fn list_of(h: &Host, d: &Data) -> std::result::Result<(Of, bool), HostError> { + let para = match (handle_of(d, "CharacterStyles"), handle_of(d, "ParagraphStyles")) { + (Some(_), _) => false, + (_, Some(_)) => true, + _ => return Err(HostError::Type("this is not a CharacterStyles".into())), + }; + let class = list_class(para); + let len = handle_of(d, class).map_or(0, |v| v.len()); + Ok((if len == 2 { Of::Doc(doc_of(h, d, class)?) } else { Of::Range(span_of(h, d, &[class])?) }, para)) +} + +/// The document and the names of the styles a collection lists. +fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec), HostError> { + match of { + Of::Doc(doc) => { + let names = with_doc(h, *doc, |_, st| names(st, para)); + h.charge_call(names.len() as u64)?; + Ok((*doc, names)) + } + Of::Range(r) => { + let (index, s, e, _) = resolve(h, *r)?; + let used = with_doc(h, r.item.doc, |_, st| { + let t = text_of(st, r.item.id).ok_or_else(|| HostError::Error(super::STALE_ITEM.into()))?; + let used: Vec> = if para { + let (paras, _, _) = para_range(&index, s, e); + paras.map(|i| t.para_at(i).style_name.clone()).collect() + } else { + styles_in(t, index.byte(s, false), index.byte(e, true))?.into_iter().map(|(c, _)| c.style_name).collect() + }; + h.charge_call(used.len() as u64)?; + let mut out: Vec = Vec::new(); + for n in used { + let n = n.filter(|n| has_style(st, para, n)).unwrap_or_else(|| normal(para).to_string()); + if !out.contains(&n) { + out.push(n); + } + } + if out.is_empty() { + out.push(normal(para).to_string()); + } + Ok::<_, HostError>(out) + })?; + Ok((r.item.doc, used)) + } + } +} + +fn list_length(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + Ok(num(float(listed(h, &of, para)?.1.len() as u64))) +} + +fn list_parent(h: &Host, a: &[Data]) -> Answer { + let (of, _) = list_of(h, arg(a, 0))?; + match of { + Of::Doc(doc) => Ok(doc_ref(h, doc.uid)), + Of::Range(r) => { + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, "TextRange")) + } + } +} + +fn list_at(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) }; + let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) }; + let found = match &of { + Of::Doc(doc) => with_doc(h, *doc, |_, st| match i { + 0 => Some(normal(para).to_string()), + _ => defs(st, para).iter().map(|d| &d.name).filter(|n| *n != normal(para)).nth(i - 1).cloned(), + }) + .map(|n| (*doc, n)), + Of::Range(_) => { + let (doc, names) = listed(h, &of, para)?; + names.get(i).cloned().map(|n| (doc, n)) + } + }; + match found { + Some((doc, name)) => style_ref(h, doc.uid, para, &name), + None => Ok(Data::Undefined), + } +} + +fn list_by_name(h: &Host, a: &[Data]) -> Answer { + let (of, para) = list_of(h, arg(a, 0))?; + let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) }; + if name.len() > super::super::MAX_TEXT_BYTES { + return Err(HostError::Range("the name is too long".into())); + } + let (doc, names) = listed(h, &of, para)?; + match names.iter().find(|n| *n == name) { + Some(n) => style_ref(h, doc.uid, para, n), + None => Err(HostError::Error(NOT_FOUND.into())), + } +} + +fn list_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => list_by_name(h, a), + Data::Number(_) => match list_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a document's collection; a range's collection cannot be changed. +fn changed_doc(h: &Host, a: &[Data]) -> std::result::Result<(Doc, bool), HostError> { + match list_of(h, arg(a, 0))? { + (Of::Doc(doc), para) => Ok((doc, para)), + (Of::Range(_), _) => Err(HostError::Error("the styles of a text range cannot be added or removed".into())), + } +} + +/// `add(name)`: a new style that sets no attributes. +fn list_add(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let name = style_name(arg(a, 1))?; + if with_doc(h, doc, |_, st| has_style(st, para, &name)) { + return Err(HostError::Error(format!("a style named {name} already exists"))); + } + run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; + // An object of a removed style of this name stays stale. + forget(h, doc.uid, para, std::slice::from_ref(&name)); + style_ref(h, doc.uid, para, &name) +} + +/// `removeAll()`: deletes every style but the Normal style, in one command. +fn list_remove_all(h: &Host, a: &[Data]) -> Answer { + let (doc, para) = changed_doc(h, a)?; + let gone: Vec = with_doc(h, doc, |_, st| names(st, para)).into_iter().skip(1).collect(); + if gone.is_empty() { + return Ok(Data::Undefined); + } + run(h, doc, para, "delete", &json!({"names": gone}))?; + forget(h, doc.uid, para, &gone); + Ok(Data::Undefined) +} + +fn doc_char_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("CharacterStyles", &[float(h.run), float(doc.uid)])) +} + +fn doc_para_styles(h: &Host, a: &[Data]) -> Answer { + let doc = doc_of(h, arg(a, 0), "Document")?; + Ok(host_ref("ParagraphStyles", &[float(h.run), float(doc.uid)])) +} + +fn range_styles(h: &Host, a: &[Data], para: bool) -> Answer { + let r = this_range(h, a)?; + let (_, s, e, stamp) = resolve(h, r)?; + Ok(range_ref(h, r.item, s, e, stamp, list_class(para))) +} + +fn range_char_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, false) +} + +fn range_para_styles(h: &Host, a: &[Data]) -> Answer { + range_styles(h, a, true) +} + +/// `document.characterStyles` and `document.paragraphStyles`. +pub(in crate::script) fn doc_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, doc_char_styles)), ("paragraphStyles", get(l, doc_para_styles))]) +} + +/// `TextRange.characterStyles` and `TextRange.paragraphStyles`. +pub(super) fn range_members(l: &Link) -> Vec<(String, HostMember)> { + named(vec![("characterStyles", get(l, range_char_styles)), ("paragraphStyles", get(l, range_para_styles))]) +} + +/// The style classes. +pub(super) fn classes(l: &Link) -> Vec { + let style = |para: bool| { + let mut members = named(vec![ + ("typename", get(l, style_typename)), + ("name", property(l, style_name_get, style_name_set)), + ("parent", get(l, style_parent)), + ("applyTo", method(l, style_apply_to)), + ("remove", method(l, style_remove)), + ]); + if para { + members.push(("paragraphAttributes".into(), get(l, style_paragraph_attributes))); + members.push(super::super::later(l, "ParagraphStyle", "characterAttributes")); + } else { + members.push(("characterAttributes".into(), get(l, style_character_attributes))); + } + class(style_class(para), None, members, None) + }; + let list = |para: bool| { + let name = list_class(para); + class( + name, + None, + named(vec![ + ("typename", typename_of(name)), + ("length", get(l, list_length)), + ("parent", get(l, list_parent)), + ("index", method(l, list_index)), + ("getByName", method(l, list_by_name)), + ("add", method(l, list_add)), + ("removeAll", method(l, list_remove_all)), + ]), + Some(function(l, list_at)), + ) + }; + let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + chars.extend(char_members(l)); + let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + paras.extend(para_members(l)); + vec![ + style(false), + style(true), + list(false), + list(true), + class("CharacterStyleAttributes", None, chars, None), + class("ParagraphStyleAttributes", None, paras, None), + ] +} diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index d228ff848f..00d2c50167 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,6 +1317,9 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; + if r.is_ok() { + dom::after_command(host); + } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index cd2a81daeb..572caa8cf2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -178,6 +178,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_styles; mod script_text; mod scripts; mod select_effects; diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs new file mode 100644 index 0000000000..085ecfbbb9 --- /dev/null +++ b/crates/engine/src/tests/script_styles.rs @@ -0,0 +1,331 @@ +//! Character and paragraph styles in the script object model. + +use serde_json::{Value, json}; +use vectorcraft_doc::{TextObject, TextStyleDef}; + +use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +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() +} + +/// A 400 × 300 pt document with point type holding `text`. +fn doc_with(text: &str) -> (Session, NodeId) { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = s.execute("text.create", &json!({"x": 20, "y": 100, "text": text, "size": 12})).unwrap()["id"].as_u64().unwrap(); + (s, NodeId(id)) +} + +fn text_of(s: &Session, id: NodeId) -> TextObject { + match &s.active().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each run's text, style name, size and underline. +fn runs(s: &Session, id: NodeId) -> Vec<(String, Option, f64, bool)> { + text_of(s, id).runs.iter().map(|r| (r.text.clone(), r.style.style_name.clone(), r.style.size, r.style.underline)).collect() +} + +fn char_names(s: &Session) -> Vec { + s.active().unwrap().doc.char_styles.iter().map(|d| d.name.clone()).collect() +} + +const DOC: &str = "var d = app.activeDocument, cs = d.characterStyles, ps = d.paragraphStyles, tf = d.textFrames[0];"; + +#[test] +fn style_collections_list_the_normal_style_first_and_add_find_and_remove() { + let (mut s, _) = doc_with("Hello"); + let before = undo_steps(&s); + let out = log( + &mut s, + &format!( + "{DOC} vc.log([cs.length, ps.length, cs[0].name, ps[0].name, cs.typename, cs[0].typename, ps[0].typename]);\ + var b = cs.add('Body'); var p = ps.add('Lead');\ + vc.log([cs.length, cs[1].name, cs.getByName('Body').name, cs.index(1).name, cs.index('Body').name, b.parent.typename]);\ + vc.log([ps.length, ps.getByName('Lead').name, cs[5] === undefined]);\ + cs.add('Other'); cs.removeAll(); ps.removeAll();\ + vc.log([cs.length, ps.length, cs[0].name]);" + ), + ); + assert_eq!(out[0], json!([1, 1, NORMAL_CHAR, NORMAL_PARA, "CharacterStyles", "CharacterStyle", "ParagraphStyle"])); + assert_eq!(out[1], json!([2, "Body", "Body", "Body", "Body", "Document"])); + assert_eq!(out[2], json!([2, "Lead", true])); + assert_eq!(out[3], json!([1, 1, NORMAL_CHAR])); + assert_eq!(undo_steps(&s), before + 1); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs.getByName('Nope');", "Not found"), + ("cs.index(4);", "Not found"), + ("cs.add('Body'); cs.add('Body');", "already exists"), + ("cs[0].remove();", "cannot be removed"), + ("ps[0].name = 'Mine';", "cannot be renamed"), + ("cs.getByName(5);", "string"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!((undo_steps(&s), char_names(&s)), (undo, Vec::::new())); +} + +/// Names are trimmed; an empty name, one past 256 characters and one with a control character +/// are refused with nothing changed. +#[test] +fn style_names_are_trimmed_and_checked() { + let (mut s, _) = doc_with("Hello"); + let out = log(&mut s, &format!("{DOC} vc.log(cs.add(' Lead ').name); vc.log(cs.add('{}').name.length);", "x".repeat(256))); + assert_eq!(out, [json!("Lead"), json!(256)]); + let undo = undo_steps(&s); + let long = "x".repeat(257); + for (src, says) in [ + ("cs.add(' ');".to_string(), "empty"), + (format!("cs.add('{long}');"), "256 characters"), + ("cs.add('a\\u0007b');".to_string(), "control characters"), + ("ps.add('tab\\there');".to_string(), "control characters"), + ("cs.getByName('Lead').name = 'x\\ny';".to_string(), "control characters"), + ("cs.add(5);".to_string(), "string"), + (format!("cs.getByName('{}');", "y".repeat(5000)), "too long"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + assert_eq!(char_names(&s).len(), 2); + // Path characters are kept as part of the name; a style name never names a file. + let out = log(&mut s, &format!("{DOC} vc.log(cs.add('../a/b\\\\c:*?').name);")); + assert_eq!(out, [json!("../a/b\\c:*?")]); + assert_eq!(char_names(&s).last().map(String::as_str), Some("../a/b\\c:*?")); +} + +/// A style attribute that is not a finite number in range is refused with nothing changed. +#[test] +fn style_attributes_refuse_values_that_are_not_finite_or_in_range() { + let (mut s, _) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X'); ps.add('P');")); + let undo = undo_steps(&s); + for (src, says) in [ + ("cs[1].characterAttributes.size = NaN;", "finite number"), + ("cs[1].characterAttributes.size = Infinity;", "finite number"), + ("cs[1].characterAttributes.size = 1e9;", "0.1 to 1296"), + ("cs[1].characterAttributes.leading = 1e300;", "0.1 to 5000"), + ("cs[1].characterAttributes.tracking = -1e9;", "tracking"), + ("ps[1].paragraphAttributes.leftIndent = NaN;", "finite"), + ("ps[1].paragraphAttributes.spaceBefore = 1e12;", "1296"), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(undo_steps(&s), undo); + let attrs = |s: &Session| { + s.active().unwrap().doc.char_styles.iter().chain(s.active().unwrap().doc.para_styles.iter()).map(|d| d.attrs.len()).sum::() + }; + assert_eq!(attrs(&s), 0); +} + +/// A style object follows its style through a rename made with it; after the style is removed, +/// with the object or with a command, every member throws, and a new style of that name does not +/// bring it back. +#[test] +fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { + let (mut s, id) = doc_with("Hello"); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.add('A'); a.applyTo(tf.textRange); a.name = ' B '; vc.log([a.name, cs[1].name, a === cs.getByName('B')]);\ + a.name = 'B'; vc.log(cs.length);" + ), + ); + assert_eq!(out, [json!(["B", "B", true]), json!(2)]); + assert_eq!(runs(&s, id)[0].1.as_deref(), Some("B")); + for remove in ["a.remove();", "vc.run('charStyle.delete', {name: 'B'});", "cs.removeAll();"] { + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); {remove} cs.add('B'); a.name;")); + assert!(e.contains("Stale style"), "{remove}: {e}"); + } + // A style removed and made again by commands is another style. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('charStyle.delete', {{name: 'B'}}); vc.run('charStyle.new', {{name: 'B', attrs: {{}}}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // A style renamed by a command is stale too, and its text keeps its look after a removal. + let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); + assert!(e.contains("Stale style"), "{e}"); + let e = + failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.characterAttributes.size;")); + assert!(e.contains("Stale style"), "{e}"); + let size = runs(&s, id)[0].2; + log(&mut s, &format!("{DOC} var a = cs.getByName('B'); a.characterAttributes.size = 40; a.remove();")); + assert_eq!(runs(&s, id)[0].1, None); + assert_ne!(runs(&s, id)[0].2, size); + assert_eq!(runs(&s, id)[0].2, 40.0); +} + +/// A character style styles exactly the range; without clearing overrides the range keeps its +/// own underline, and with them it goes back to the Normal style first. +#[test] +fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { + let (mut s, id) = doc_with("Hello world"); + let before = undo_steps(&s); + log( + &mut s, + &format!("{DOC} var w = tf.words[0]; w.underline = true; var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo(w);"), + ); + assert_eq!(runs(&s, id), [("Hello".into(), Some("Big".into()), 30.0, true), (" world".into(), None, 12.0, false)]); + assert_eq!(undo_steps(&s), before + 1); + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf.words[0], true);")); + assert_eq!(runs(&s, id)[0], ("Hello".into(), Some("Big".into()), 30.0, false)); + // A whole frame, and an empty range, which changes nothing. + log(&mut s, &format!("{DOC} cs.getByName('Big').applyTo(tf); cs[0].applyTo(tf.characters[0]);")); + assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); +} + +/// A paragraph style styles every paragraph the text touches, and only those. +#[test] +fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { + let (mut s, id) = doc_with("one\ntwo\nthree"); + let out = log( + &mut s, + &format!( + "{DOC} var c = ps.add('Centered'); var a = c.paragraphAttributes;\ + vc.log([a.justification === undefined, a.spaceBefore === undefined, a.typename]);\ + a.justification = Justification.CENTER; a.spaceBefore = 6;\ + vc.log([a.justification, a.spaceBefore]); c.applyTo(tf.paragraphs[1]);\ + vc.log(tf.paragraphs[1].paragraphAttributes.justification);" + ), + ); + assert_eq!(out, [json!([true, true, "ParagraphAttributes"]), json!(["Justification.CENTER", 6]), json!("Justification.CENTER")]); + let t = text_of(&s, id); + let names: Vec<_> = (0..3).map(|i| t.para_at(i).style_name.clone()).collect(); + assert_eq!(names, [None, Some("Centered".to_string()), None]); + assert_eq!(t.para_at(1).space_before, 6.0); + assert_eq!(t.para_at(2).space_before, 0.0); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.justification = 'middle';")); + assert!(e.contains("Justification"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.getByName('Centered').paragraphAttributes.spaceAfter = 5000;")); + assert!(e.contains("1296"), "{e}"); +} + +/// A style's character attributes read `undefined` until set; setting one restyles the text in +/// the style but not a value the text changed itself. +#[test] +fn style_attributes_redefine_the_text_in_the_style() { + let (mut s, id) = doc_with("ab cd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), a = x.characterAttributes;\ + vc.log([a.size === undefined, a.autoLeading === undefined, a.textFont === undefined, a.typename]);\ + a.size = 20; x.applyTo(tf.textRange); tf.words[1].size = 9; a.size = 24; a.autoLeading = true; a.underline = true;\ + vc.log([a.size, a.autoLeading, a.underline]);" + ), + ); + assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); + assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); + // Turning auto leading off keeps the leading auto leading gave the style's size. + let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + assert_eq!(out, [json!([false, 288])]); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); + assert!(e.contains("0.1 to 1296"), "{e}"); + let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.textFont = 'Arial';")); + assert!(e.contains("TextFont"), "{e}"); + let e = failure(&mut s, &format!("{DOC} ps.add('P').characterAttributes;")); + assert!(e.contains("not available yet"), "{e}"); +} + +/// A range lists each style its text uses once, in order, with the Normal style for unstyled +/// text, and its lists cannot add or remove styles. +#[test] +fn a_range_lists_the_styles_its_text_uses() { + let (mut s, _) = doc_with("aa bb cc\ndd"); + let out = log( + &mut s, + &format!( + "{DOC} var x = cs.add('X'), y = cs.add('Y'); y.applyTo(tf.words[2]); x.applyTo(tf.words[1]); x.applyTo(tf.words[3]);\ + ps.add('P').applyTo(tf.paragraphs[1]);\ + function names(l) {{ var o = []; for (var i = 0; i < l.length; i++) o.push(l[i].name); return o; }}\ + vc.log(names(tf.textRange.characterStyles)); vc.log(names(tf.words[1].characterStyles));\ + vc.log(names(tf.textRange.paragraphStyles)); vc.log(names(tf.paragraphs[0].paragraphStyles));\ + vc.log([tf.words[1].characterStyles[0] === x, tf.words[1].characterStyles.getByName('X').name,\ + tf.textRange.characterStyles.parent.typename]);" + ), + ); + assert_eq!(out[0], json!([NORMAL_CHAR, "X", "Y"])); + assert_eq!(out[1], json!(["X"])); + assert_eq!(out[2], json!([NORMAL_PARA, "P"])); + assert_eq!(out[3], json!([NORMAL_PARA])); + assert_eq!(out[4], json!([true, "X", "TextRange"])); + for src in ["tf.textRange.characterStyles.add('Z');", "tf.textRange.paragraphStyles.removeAll();"] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains("cannot be added or removed"), "{src}"); + } +} + +/// `applyTo` refuses what is not text, a `clearingOverrides` that is not a boolean, text of another +/// document, and a range whose text changed, with nothing changed. +#[test] +fn apply_to_refuses_bad_arguments_with_nothing_changed() { + let (mut s, id) = doc_with("Hello"); + log(&mut s, &format!("{DOC} cs.add('X');")); + let runs_before = runs(&s, id); + for (src, says) in [ + ("cs[1].applyTo(5);".to_string(), "TextRange"), + ("cs[1].applyTo(tf.textRange, 'yes');".to_string(), "clearingOverrides"), + ("cs[1].applyTo(cs);".to_string(), "TextRange"), + (format!("var r = tf.textRange; vc.run('text.setText', {{id: {}, text: 'Help'}}); cs[1].applyTo(r);", id.0), "Stale text range"), + ( + "var o = app.documents.add(); var t = o.textFrames.add(); t.contents = 'Other'; cs[1].applyTo(t.textRange);".to_string(), + "another document", + ), + ] { + assert!(failure(&mut s, &format!("{DOC} {src}")).contains(says), "{src}"); + } + assert_eq!(runs(&s, id), runs_before); +} + +/// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn a_run_names_at_most_4096_styles() { + let (mut s, _) = doc_with("Hello"); + let mut d = (*s.active().unwrap().doc).clone(); + let defs: Vec = (0..4100).map(|i| TextStyleDef { name: format!("S{i}"), attrs: Default::default() }).collect(); + d.char_styles = defs.into(); + s.doc_mut().unwrap().doc = std::sync::Arc::new(d); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; vc.log(cs[0] === undefined); vc.log(cs.length);")); + assert_eq!(out, [json!(false), json!(4101)]); + let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); + assert!(e.contains("4096 styles"), "{e}"); +} + +/// A script loads styles from a file only where it may read files; a file outside that is refused. +#[test] +fn a_script_loads_styles_only_from_a_file_it_may_read() { + let (mut s, _) = doc_with("Hello"); + let dir = std::env::temp_dir().join(format!("vc-script-styles-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("Other.vectorcraft"); + let mut other = Session::new(); + other.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + other.execute("charStyle.new", &json!({"name": "Loaded", "attrs": {"size": 30}})).unwrap(); + std::fs::write(&path, vectorcraft_format::save(&other.active().unwrap().doc, false)).unwrap(); + let p = path.to_string_lossy().replace('\\', "/"); + let e = failure(&mut s, &format!("vc.run('charStyle.load', {{path: '{p}'}});")); + std::fs::remove_dir_all(&dir).ok(); + assert!(e.contains("access denied"), "{e}"); + assert!(char_names(&s).is_empty()); +} diff --git a/docs/mcp.md b/docs/mcp.md index b875fee563..801933b011 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2738,6 +2738,31 @@ app through the global object `vc`, and writes to the Script Console and runs ot `Stale text font`. Members the help pages list that are not here, such as `TextFrame.lines`, `TextFrame.story` and `TextRange.changeCaseTo`, throw an error that says they are not available yet, and `start`, `end`, `length` and `orientation` cannot be set yet. +- `Document.characterStyles` and `Document.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, + https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/) list the document's styles with `length`, `[i]`, + `index(key)`, `getByName(name)`, `add(name)` (`charStyle.new` or `paraStyle.new` with no attributes) and + `removeAll()` (`charStyle.delete` or `paraStyle.delete` of every style but the Normal style). A `CharacterStyle` + (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/) has `name` (`charStyle.rename`), `parent`, + `characterAttributes`, `applyTo(text, clearingOverrides?)` (`charStyle.apply`) and `remove()` (`charStyle.delete`); + a `ParagraphStyle` (https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/) has the same members with + `paragraphAttributes` and the `paraStyle` commands. A style's attributes are those of a text range's + `characterAttributes` and `paragraphAttributes`, with the same ranges, and setting one runs `charStyle.setAttrs` or + `paraStyle.setAttrs`. `TextRange.characterStyles` and `TextRange.paragraphStyles` + (https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/) list the styles the range's text is in, with `length`, + `[i]`, `index(key)` and `getByName(name)`. A script loads styles from another document with `vc.run` and + `charStyle.load`, `paraStyle.load` or `textStyle.loadAll`, from a file the script may read. + VectorCraft's own rules: a document's list starts with `[Normal Character Style]` or `[Normal Paragraph Style]`, + followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. + An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the + style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the + style's document; a character style on an empty range changes nothing, and a paragraph style styles every + paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove + styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made + through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not + available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and `$.writeln(...values)` does the same and ends the line. Each call counts as a host call. - `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global @@ -13086,7 +13111,7 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f6a957cad0..eedc6224f8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1025,7 +1025,8 @@ 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. Stories, threading, lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`. + - Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.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 a2063cea756b84dbefd454384ac569f4643785eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 15:55:21 -0800 Subject: [PATCH 05/20] Scripts: a style change that is put back keeps its style object A removal or rename whose result cannot reach the script is put back, and style objects now follow a command only once it is kept. A failed atomic object-model call puts style objects back with the documents. --- crates/engine/src/script/dom.rs | 17 +++++++--- crates/engine/src/script/dom/text/styles.rs | 35 +++++++++++++++++++++ crates/engine/src/script/mod.rs | 7 +++-- crates/engine/src/tests/script_styles.rs | 29 ++++++++++++++++- 4 files changed, 79 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87a6310ec3..c02d65dfbd 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -113,15 +113,22 @@ fn atomically(h: &Host, f: impl FnOnce(&Host) -> std::result::Result, + seen: Vec, +} + +/// The style objects' state now, for [`put_back`] when the savepoint taken with it is restored. +pub(in crate::script) fn mark(h: &Host) -> Mark { + let styles = &h.dom.text.styles; + let slots = styles.slots.borrow().iter().map(|s| (s.name.clone(), s.live)).collect(); + Mark { slots, seen: styles.seen.borrow().clone() } +} + +/// Puts the style objects back as they were at `mark`, after the documents were put back to the +/// savepoint taken with it. A slot added since then stays live only while its document has the +/// style and no older live slot names it. +pub(in crate::script) fn put_back(h: &Host, mark: Mark) { + let styles = &h.dom.text.styles; + let mut slots = styles.slots.borrow_mut(); + let kept = mark.slots.len(); + for (slot, (name, live)) in slots.iter_mut().zip(mark.slots) { + slot.name = name; + slot.live = live; + } + let s = h.session.borrow(); + for i in kept..slots.len() { + let (older, newer) = slots.split_at_mut(i); + let Some(slot) = newer.first_mut() else { break }; + let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + } + *styles.seen.borrow_mut() = mark.seen; +} + fn normal(para: bool) -> &'static str { if para { NORMAL_PARA } else { NORMAL_CHAR } } diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 00d2c50167..e537ab8ef7 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1317,9 +1317,6 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( let mut s = session.borrow_mut(); step(&mut s, host, &id, ¶ms) }; - if r.is_ok() { - dom::after_command(host); - } // Only commands that exist are timed, so the table holds at most one row per command. if let (Some(started), Some(spec)) = (started, crate::find_command(&id)) { let nanos = started.elapsed().as_nanos(); @@ -1349,6 +1346,10 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( return Err(HostError::Abort(HISTORY_LOST.to_string())); } } + // Style objects follow only a command that is kept. + if crossed.is_ok() { + dom::after_command(host); + } crossed.map(|data| (data, value)) } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 085ecfbbb9..f30e66a7e6 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{TextObject, TextStyleDef}; use crate::cmd::textstyles::{NORMAL_CHAR, NORMAL_PARA}; +use crate::script::TEST_RESULT_BYTES; use crate::*; fn run(s: &mut Session, source: &str) -> Result { @@ -177,6 +178,29 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// A removal or rename whose result cannot cross to the script is put back, and the style's object +/// still names the style after it. +#[test] +fn a_style_change_that_is_put_back_keeps_the_style_object() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {}})).unwrap(); + TEST_RESULT_BYTES.with(|b| b.set(Some(1))); + let r = run( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + try {{ a.remove(); }} catch (e) {{ vc.log(e.name); }}\ + try {{ vc.run('charStyle.delete', {{name: 'B'}}); }} catch (e) {{ vc.log(e.name); }}\ + try {{ a.name = 'C'; }} catch (e) {{ vc.log(e.name); }}\ + vc.log([a.name, a === cs.getByName('B'), cs.length]);" + ), + ); + TEST_RESULT_BYTES.with(|b| b.set(None)); + let r = r.unwrap(); + assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", ["B", true, 2]]), "{r}"); + assert!(char_names(&s).contains(&"B".to_string()), "{:?}", char_names(&s)); +} + /// A character style styles exactly the range; without clearing overrides the range keeps its /// own underline, and with them it goes back to the Normal style first. #[test] @@ -239,7 +263,10 @@ fn style_attributes_redefine_the_text_in_the_style() { assert_eq!(out, [json!([true, true, true, "CharacterAttributes"]), json!([24, true, true])]); assert_eq!(runs(&s, id), [("ab ".into(), Some("X".into()), 24.0, true), ("cd".into(), Some("X".into()), 9.0, true)]); // Turning auto leading off keeps the leading auto leading gave the style's size. - let out = log(&mut s, &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);")); + let out = log( + &mut s, + &format!("{DOC} var a = cs.getByName('X').characterAttributes; a.autoLeading = false; vc.log([a.autoLeading, Math.round(a.leading * 10)]);"), + ); assert_eq!(out, [json!([false, 288])]); let e = failure(&mut s, &format!("{DOC} cs.getByName('X').characterAttributes.size = 0;")); assert!(e.contains("0.1 to 1296"), "{e}"); From de11e1e7555d02e6cd2dc513ae6bbc8b6b2a46b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 18:47:00 -0800 Subject: [PATCH 06/20] Scripts: style objects made before File > Revert go stale A style object kept working after file.revert when the file read back held a style with the same name. Each style object now keeps the document's revert count, as text ranges do, and one made before a revert throws Stale style. The range style lists follow the per-paragraph entries of the text model, and the host name table lists the style classes. --- crates/engine/src/script/dom/text/styles.rs | 21 ++++++---- crates/engine/src/tests/script_styles.rs | 22 ++++++++++ .../tests/it/script_host_vs_scriptcheck.rs | 41 +++++++++++++++---- docs/mcp.md | 3 +- 4 files changed, 69 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index adb71dd6cf..841d006ac6 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -12,8 +12,8 @@ //! panel lists them. //! - A style object names its style for the rest of the run, also after the script renames it //! through `name`. Once the style is removed, or renamed or removed other than through the object -//! model, or its document is closed, every member throws `Stale style`; a style added later under -//! the same name is another style. +//! model, or its document is closed or reverted with File › Revert, every member throws +//! `Stale style`; a style added later under the same name is another style. //! - A style name is trimmed, and must then be 1 to 256 characters long with no control //! characters. //! - A style's `characterAttributes` and `paragraphAttributes` read `undefined` for an attribute the @@ -54,9 +54,11 @@ pub const MAX_STYLE_NAME: usize = 256; /// The most styles one run's style objects name. pub const MAX_HELD: usize = 4096; -/// A style that a run's style objects name: its document, its kind and its name now. +/// A style that a run's style objects name: its document and the document's revert count then, its +/// kind and its name now. struct Slot { uid: u64, + reverts: u64, para: bool, name: String, live: bool, @@ -91,7 +93,7 @@ pub(in crate::script) fn after_command(h: &Host) { seen.retain(|(uid, ..)| *uid != st.uid); seen.push((st.uid, st.doc.char_styles.clone(), st.doc.para_styles.clone())); for slot in slots.iter_mut().filter(|x| x.live && x.uid == st.uid) { - slot.live = has_style(st, slot.para, &slot.name); + slot.live = slot.reverts == st.reverts && has_style(st, slot.para, &slot.name); } } for slot in slots.iter_mut().filter(|x| x.live) { @@ -131,7 +133,7 @@ pub(in crate::script) fn put_back(h: &Host, mark: Mark) { let (older, newer) = slots.split_at_mut(i); let Some(slot) = newer.first_mut() else { break }; let named = older.iter().any(|o| o.live && o.uid == slot.uid && o.para == slot.para && o.name == slot.name); - slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && has_style(st, slot.para, &slot.name)); + slot.live = !named && s.documents().iter().any(|st| st.uid == slot.uid && st.reverts == slot.reverts && has_style(st, slot.para, &slot.name)); } *styles.seen.borrow_mut() = mark.seen; } @@ -174,14 +176,15 @@ fn stale() -> HostError { /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { + let reverts = h.session.borrow().documents().iter().find(|d| d.uid == uid).map_or(0, |d| d.reverts); let mut slots = h.dom.text.styles.slots.borrow_mut(); - let i = match slots.iter().position(|s| s.live && s.uid == uid && s.para == para && s.name == name) { + let i = match slots.iter().position(|s| s.live && s.uid == uid && s.reverts == reverts && s.para == para && s.name == name) { Some(i) => i, None => { if slots.len() >= MAX_HELD { return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); } - slots.push(Slot { uid, para, name: name.to_string(), live: true }); + slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 } }; @@ -207,7 +210,7 @@ fn style_of(h: &Host, d: &Data, classes: &[(&str, bool)]) -> std::result::Result let slot = usize_of(*slot).ok_or_else(stale)?; let mut slots = h.dom.text.styles.slots.borrow_mut(); let s = slots.get_mut(slot).filter(|s| s.live && s.uid == doc.uid && s.para == para).ok_or_else(stale)?; - if !with_doc(h, doc, |_, st| has_style(st, para, &s.name)) { + if !with_doc(h, doc, |_, st| st.reverts == s.reverts && has_style(st, para, &s.name)) { s.live = false; return Err(stale()); } @@ -552,7 +555,7 @@ fn listed(h: &Host, of: &Of, para: bool) -> std::result::Result<(Doc, Vec = Vec::new(); diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index f30e66a7e6..759e41eae1 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -326,6 +326,28 @@ fn apply_to_refuses_bad_arguments_with_nothing_changed() { } /// A run names at most 4,096 styles; reading past that throws instead of growing without bound. +#[test] +fn style_objects_made_before_file_revert_go_stale_even_when_the_style_is_back() { + let (mut s, _) = doc_with("Hello"); + s.execute("charStyle.new", &json!({"name": "B", "attrs": {"size": 30}})).unwrap(); + let path = std::env::temp_dir().join(format!("vc-styles-revert-{}.vectorcraft", std::process::id())); + s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); + let out = log( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B');\ + vc.run('shape.rectangle', {{x: 1, y: 1, width: 5, height: 5}}); vc.run('file.revert', {{}});\ + var cs2 = app.activeDocument.characterStyles;\ + try {{ vc.log(a.name); }} catch (e) {{ vc.log(e.message); }}\ + vc.log(cs2.getByName('B').name); vc.log(cs2.getByName('B') === a);" + ), + ); + let _ = std::fs::remove_file(&path); + assert!(out[0].as_str().is_some_and(|m| m.contains("Stale style")), "{out:?}"); + assert_eq!(out[1], json!("B"), "a style object made after the revert names the reverted style"); + assert_eq!(out[2], json!(false)); +} + #[test] fn a_run_names_at_most_4096_styles() { let (mut s, _) = doc_with("Hello"); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index b23788236e..4e066e4831 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -96,10 +96,10 @@ const INSIDE: &[(&str, &str)] = &[ ("Document.", "prototype"), ( "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 \ - views views= width", + "activeLayer activeLayer= artboards artboards= characterStyles close close= constructor convertCoordinate \ + documentColorSpace groupItems groupItems= height layers layers= name pageItems paragraphStyles parent pathItems \ + pathItems= rulerOrigin rulerOrigin= rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols \ + symbols= textFrames typename views views= width", ), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name typename"), @@ -131,8 +131,9 @@ const INSIDE: &[(&str, &str)] = &[ ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), ( "", - "CharacterAttributes Characters Justification ParagraphAttributes Paragraphs TextFont TextFonts TextFrame TextFrames \ - TextOrientation TextRange TextType Words", + "CharacterAttributes CharacterStyle CharacterStyleAttributes CharacterStyles Characters Justification \ + ParagraphAttributes ParagraphStyle ParagraphStyleAttributes ParagraphStyles Paragraphs TextFont TextFonts TextFrame \ + TextFrames TextOrientation TextRange TextType Words", ), ("TextFrames.", "prototype"), ("TextFrames.prototype.", "add areaText constructor getByName index length parent pathText pointText removeAll typename"), @@ -150,11 +151,11 @@ const INSIDE: &[(&str, &str)] = &[ ( "TextRange.prototype.", "autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \ - characterOffset= characterStyles characterStyles= characters constructor contents contents= deSelect deSelect= \ + characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \ duplicate duplicate= end end= getLocalCharOverridesJSON getLocalCharOverridesJSON= getLocalParaOverridesJSON \ 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= \ + paragraphStyles paragraphs parent remove rotation rotation= select select= size size= start start= \ story story= strikeThrough strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= \ tracking tracking= typename underline underline= verticalScale verticalScale= words", ), @@ -177,6 +178,30 @@ const INSIDE: &[(&str, &str)] = &[ "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", ), + ("CharacterStyles.", "prototype"), + ("CharacterStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("CharacterStyle.", "prototype"), + ("CharacterStyle.prototype.", "applyTo characterAttributes constructor name name= parent remove typename"), + ("CharacterStyleAttributes.", "prototype"), + ( + "CharacterStyleAttributes.prototype.", + "autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \ + rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \ + underline= verticalScale verticalScale=", + ), + ("ParagraphStyles.", "prototype"), + ("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"), + ("ParagraphStyle.", "prototype"), + ( + "ParagraphStyle.prototype.", + "applyTo characterAttributes characterAttributes= constructor name name= paragraphAttributes parent remove typename", + ), + ("ParagraphStyleAttributes.", "prototype"), + ( + "ParagraphStyleAttributes.prototype.", + "constructor firstLineIndent firstLineIndent= justification justification= leftIndent leftIndent= rightIndent \ + rightIndent= spaceAfter spaceAfter= spaceBefore spaceBefore= typename", + ), ("TextFonts.", "prototype"), ("TextFonts.prototype.", "constructor getByName index length parent typename"), ("TextFont.", "prototype"), diff --git a/docs/mcp.md b/docs/mcp.md index 801933b011..411ef4ba07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2760,7 +2760,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made - through `name`; after the style is removed, renamed another way or its document closed, it throws `Stale style`. + through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws + `Stale style`. One run names at most 4,096 styles. `ParagraphStyle.characterAttributes` throws an error that says it is not available yet. - `$.write(...values)` writes the values to the Script Console with no separator, each as `String(value)` gives it, and From c7671c615b5df2ad0f607368fd36d06b8b36a6f8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 21:02:47 -0800 Subject: [PATCH 07/20] Scripts: style objects see a style a batch removes and adds again - A style object goes stale when the steps of one `command.batch` remove its style and add another under the same name, as it does when separate `vc.run` calls do. The session notes each batch step's style lists while a script runs, and the style objects check each of them. - `add(name)` with all 4,096 style slots of the run taken throws before it adds the style; with one slot left it adds it. - `typename` of a removed style's `characterAttributes` or `paragraphAttributes` throws `Stale style`, as its other members do. - The style load commands refuse `data` over 64 MB without copying it. - docs/mcp.md states the 64 MB limit for `data` and decoded `dataBase64`; docs/gaps.md G6 and the docs/roadmap.md M13 row list the script text and style members. --- crates/engine/src/cmd/textstyles.rs | 8 ++--- crates/engine/src/cmd/textstyles/tests.rs | 3 ++ crates/engine/src/lib.rs | 4 +++ crates/engine/src/script/dom/text/styles.rs | 37 ++++++++++++++++++--- crates/engine/src/script/mod.rs | 22 ++++++++++++ crates/engine/src/session/documents.rs | 1 + crates/engine/src/session/execute.rs | 3 ++ crates/engine/src/tests/script_styles.rs | 21 ++++++++++++ docs/gaps.md | 2 +- docs/mcp.md | 3 +- docs/roadmap.md | 2 +- 11 files changed, 94 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index 3b57c2e067..3b64929cc2 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -1270,11 +1270,11 @@ fn load(s: &mut Session, p: &Value, kinds: &[Kind]) -> Result { }; let path = str_param(p, "path"); let too_large = || bad(c, format!("the file is larger than {} MB", MAX_LOAD_BYTES >> 20)); - let bytes = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { - (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?, - (None, Some(text), _) => text.as_bytes().to_vec(), + let bytes: std::borrow::Cow<[u8]> = match (path, str_param(p, "data"), str_param(p, "dataBase64")) { + (Some(path), ..) => super::fileio::read_file_head(path, MAX_LOAD_BYTES + 1)?.into(), + (None, Some(text), _) => text.as_bytes().into(), (None, None, Some(b64)) if b64.len() > MAX_LOAD_BYTES / 3 * 4 + 4 => return Err(too_large()), - (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?, + (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))?.into(), _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), }; if bytes.len() > MAX_LOAD_BYTES { diff --git a/crates/engine/src/cmd/textstyles/tests.rs b/crates/engine/src/cmd/textstyles/tests.rs index 1f8511d7ac..f2d2354000 100644 --- a/crates/engine/src/cmd/textstyles/tests.rs +++ b/crates/engine/src/cmd/textstyles/tests.rs @@ -845,6 +845,9 @@ fn loading_refuses_a_file_larger_than_64_mb() { let b64 = "A".repeat(MAX_LOAD_BYTES / 3 * 4 + 8); let r = s.execute("paraStyle.load", &json!({"dataBase64": b64})); assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); + let text = " ".repeat(MAX_LOAD_BYTES + 1); + let r = s.execute("textStyle.loadAll", &json!({"data": text})); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("larger than 64 MB")), "{r:?}"); assert_eq!(s.doc().unwrap().doc, before); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index e2e6430f1e..335c83eebb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,6 +309,10 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, + /// The style lists each step of a batch a script runs left in a document whose lists it + /// changed: its uid, revert count, and character and paragraph style lists + /// ([`script::note_style_lists`]). + pub(crate) script_style_trail: Vec, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 841d006ac6..2b40d92bcd 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -75,13 +75,20 @@ pub(super) struct StyleState { } /// Marks stale each style object whose style the command just run removed or renamed, so a style -/// removed and made again under its name by later commands is another style. A document whose -/// style lists did not change is not checked again. +/// removed and made again under its name by later commands, or by later steps of the same batch, +/// is another style. A document whose style lists did not change is not checked again. pub(in crate::script) fn after_command(h: &Host) { + let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } + for (uid, reverts, c, p) in &trail { + for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { + let list = if slot.para { p } else { c }; + slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + } + } let s = h.session.borrow(); let mut seen = h.dom.text.styles.seen.borrow_mut(); seen.retain(|(uid, ..)| s.documents().iter().any(|d| d.uid == *uid)); @@ -173,6 +180,10 @@ fn stale() -> HostError { HostError::Error(STALE_STYLE.into()) } +fn held_too_many() -> HostError { + HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run")) +} + /// The style object for the style `name` of the document `uid`: the same slot as every other /// object naming it in this run. fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { @@ -182,7 +193,7 @@ fn style_ref(h: &Host, uid: u64, para: bool, name: &str) -> Answer { Some(i) => i, None => { if slots.len() >= MAX_HELD { - return Err(HostError::Range(format!("a script can name at most {MAX_HELD} styles in one run"))); + return Err(held_too_many()); } slots.push(Slot { uid, reverts, para, name: name.to_string(), live: true }); slots.len() - 1 @@ -416,6 +427,18 @@ fn char_value(h: &Host, attr: Attr, m: &Map) -> Data { } } +/// The `typename` of a style's `characterAttributes`, which throws once the style is gone. +fn attrs_typename_char(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, false)?; + Ok(text("CharacterAttributes")) +} + +/// The `typename` of a style's `paragraphAttributes`, which throws once the style is gone. +fn attrs_typename_para(h: &Host, a: &[Data]) -> Answer { + attrs_of(h, a, true)?; + Ok(text("ParagraphAttributes")) +} + fn read_char(h: &Host, a: &[Data], attr: Attr) -> Answer { let (_, m) = attrs_of(h, a, false)?; Ok(char_value(h, attr, &m)) @@ -651,6 +674,10 @@ fn list_add(h: &Host, a: &[Data]) -> Answer { if with_doc(h, doc, |_, st| has_style(st, para, &name)) { return Err(HostError::Error(format!("a style named {name} already exists"))); } + // The new style needs a slot of its own: a run that names as many styles as it may adds none. + if h.dom.text.styles.slots.borrow().len() >= MAX_HELD { + return Err(held_too_many()); + } run(h, doc, para, "new", &json!({"name": name, "attrs": {}}))?; // An object of a removed style of this name stays stale. forget(h, doc.uid, para, std::slice::from_ref(&name)); @@ -738,9 +765,9 @@ pub(super) fn classes(l: &Link) -> Vec { Some(function(l, list_at)), ) }; - let mut chars = named(vec![("typename", typename_of("CharacterAttributes"))]); + let mut chars = named(vec![("typename", get(l, attrs_typename_char))]); chars.extend(char_members(l)); - let mut paras = named(vec![("typename", typename_of("ParagraphAttributes"))]); + let mut paras = named(vec![("typename", get(l, attrs_typename_para))]); paras.extend(para_members(l)); vec![ style(false), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index e537ab8ef7..18e24f1c36 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,6 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); + s.script_style_trail.clear(); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1353,6 +1354,27 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( crossed.map(|data| (data, value)) } +/// A document's uid, revert count, and character and paragraph style lists. +pub(crate) type StyleLists = + (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); + +/// After a step of a batch a script runs: notes the style lists of each document whose lists or +/// revert count the step changed, so the style objects see a style the batch removed and made +/// again under its name as another style ([`dom::after_command`]). +pub(crate) fn note_style_lists(s: &mut Session) { + for st in &s.docs { + let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); + let same = last.is_some_and(|(_, reverts, c, p)| { + *reverts == st.reverts + && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) + && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) + }); + if !same { + s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); + } + } +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..52852308e3 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,6 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), + script_style_trail: Vec::new(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/session/execute.rs b/crates/engine/src/session/execute.rs index 046c480079..f0eabe06dd 100644 --- a/crates/engine/src/session/execute.rs +++ b/crates/engine/src/session/execute.rs @@ -84,6 +84,9 @@ impl Session { self.execute_spec(spec, id, params) }; self.reading = outer; + if self.script_in_run && self.depth > 0 && r.is_ok() { + crate::script::note_style_lists(self); + } r } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 759e41eae1..860aecfa81 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -165,6 +165,19 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // So is a style removed and made again by the steps of one batch. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.delete', params: {{name: 'B'}}}}, \ + {{command: 'charStyle.new', params: {{name: 'B', attrs: {{}}}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); + // The attributes object of a removed style throws for its typename too. + let e = + failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); + assert!(e.contains("Stale style"), "{e}"); // A style renamed by a command is stale too, and its text keeps its look after a removal. let e = failure(&mut s, &format!("{DOC} var a = cs.getByName('B'); vc.run('charStyle.rename', {{name: 'B', to: 'C'}}); a.name;")); assert!(e.contains("Stale style"), "{e}"); @@ -359,6 +372,14 @@ fn a_run_names_at_most_4096_styles() { assert_eq!(out, [json!(false), json!(4101)]); let e = failure(&mut s, &format!("{DOC} for (var i = 0; i < 4097; i++) cs[i].name;")); assert!(e.contains("4096 styles"), "{e}"); + // `add` with every slot taken adds no style; with one slot left it adds the style. + let out = log( + &mut s, + &format!("{DOC} for (var i = 0; i < 4096; i++) cs[i]; try {{ cs.add('New'); }} catch (e) {{ vc.log(e.message); }} vc.log(cs.length);"), + ); + assert_eq!(out, [json!("a script can name at most 4096 styles in one run"), json!(4101)]); + let out = log(&mut s, &format!("{DOC} for (var i = 0; i < 4095; i++) cs[i]; vc.log(cs.add('New').name); vc.log(cs.length);")); + assert_eq!(out, [json!("New"), json!(4102)]); } /// A script loads styles from a file only where it may read files; a file outside that is refused. diff --git a/docs/gaps.md b/docs/gaps.md index 47a1680f6e..561946b6d0 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **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 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, its character and paragraph styles, 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 411ef4ba07..0495483d8e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13112,7 +13112,8 @@ uses, in panel order and never the Normal style, and the panel highlights them; (Load Character Styles… and Load Paragraph Styles… in the panel menus, where `ui.loadCharStyles` and `ui.loadParaStyles` pick the file) copy the styles of that kind from another document VectorCraft opens (`path`, `data` or `dataBase64`), and `textStyle.loadAll` (Load All Styles…, `ui.loadAllStyles`) copies both kinds, each in one undo -step. A file larger than 64 MB is refused without being read in full. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of +step. A file larger than 64 MB is refused without being read in full. The 64 MB limit also applies to `data` and to the +decoded bytes of `dataBase64`; a `dataBase64` string too long to decode to 64 MB or less is refused before it is decoded. The swatches and patterns the styles paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, come along as Paste brings those of pasted type; a global or spot color whose name the document gives another color is the document's. A loaded style that is the same as the style of its name, or of its name with a number (`Body 2`), is not added again; any other is added under a free name. The diff --git a/docs/roadmap.md b/docs/roadmap.md index 3ddf3459a4..99e740189c 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 their attributes, its character and paragraph styles, and the installed fonts; the rest of the script document model (layers, artboards, paths, stories and threads of type, 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 | From 997375be0d2190f956d304d8452f7ea4b9e2daf3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 21 Nov 2026 22:27:14 -0800 Subject: [PATCH 08/20] Scripts: a batch keeps one copy of the style lists for its style objects While a script runs a `command.batch`, the session kept the style lists of every step that changed them, so each such step also made the next edit copy the whole list. The session now keeps one copy of each open document's lists, as the last step left them, and records the names of the styles a step removed or renamed and the documents a step reverted. The style objects check those names, so a style that a batch removes and makes again, or renames and names back, is still a different style. --- crates/engine/src/lib.rs | 7 +- crates/engine/src/script/dom/text/styles.rs | 13 ++-- crates/engine/src/script/mod.rs | 73 ++++++++++++++++----- crates/engine/src/session/documents.rs | 2 +- crates/engine/src/tests/script_styles.rs | 23 +++++++ 5 files changed, 93 insertions(+), 25 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 335c83eebb..0cffcac358 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -309,10 +309,9 @@ pub struct Session { pub script_frames: bool, /// Each open document's highest next id a run has seen, by [`DocState::uid`]. pub(crate) script_high_water: std::collections::HashMap, - /// The style lists each step of a batch a script runs left in a document whose lists it - /// changed: its uid, revert count, and character and paragraph style lists - /// ([`script::note_style_lists`]). - pub(crate) script_style_trail: Vec, + /// The styles the steps of a batch a script runs removed or renamed and the documents they + /// reverted ([`script::note_style_lists`]). + pub(crate) script_style_trail: script::StyleTrail, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, /// Write recovery copies of the unsaved documents before a run, and don't start without them. diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index 2b40d92bcd..fd896918a9 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -76,17 +76,20 @@ pub(super) struct StyleState { /// Marks stale each style object whose style the command just run removed or renamed, so a style /// removed and made again under its name by later commands, or by later steps of the same batch, -/// is another style. A document whose style lists did not change is not checked again. +/// is another style. A document whose style lists did not change is not checked again. A live +/// slot's style was in its document's list when the command started, so a step that removed or +/// renamed it is in the trail's removed names. pub(in crate::script) fn after_command(h: &Host) { let trail = std::mem::take(&mut h.session.borrow_mut().script_style_trail); let mut slots = h.dom.text.styles.slots.borrow_mut(); if !slots.iter().any(|s| s.live) { return; } - for (uid, reverts, c, p) in &trail { - for slot in slots.iter_mut().filter(|x| x.live && x.uid == *uid) { - let list = if slot.para { p } else { c }; - slot.live = slot.reverts == *reverts && (slot.name == normal(slot.para) || list.iter().any(|d| d.name == slot.name)); + for slot in slots.iter_mut().filter(|x| x.live) { + if trail.reverted.contains(&slot.uid) + || (!trail.gone.is_empty() && slot.name != normal(slot.para) && trail.gone.contains(&(slot.uid, slot.para, slot.name.clone()))) + { + slot.live = false; } } let s = h.session.borrow(); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 18e24f1c36..e89bf94c06 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1236,7 +1236,7 @@ fn note_ids(s: &mut Session) { /// it, for a result that cannot cross to the script. fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value, u64, u64, Option)> { raise_ids(s); - s.script_style_trail.clear(); + s.script_style_trail = StyleTrail::start(s); let mutating = waits_for_tool_edit(id); // Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id)); @@ -1274,6 +1274,7 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value Ok((v, objects, bytes, save)) } Err(e) => { + s.script_style_trail = StyleTrail::default(); if let Some(save) = save && !save.restore(s) { @@ -1350,6 +1351,8 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( // Style objects follow only a command that is kept. if crossed.is_ok() { dom::after_command(host); + } else { + session.borrow_mut().script_style_trail = StyleTrail::default(); } crossed.map(|data| (data, value)) } @@ -1358,23 +1361,63 @@ fn command_value(host: &Host, id: &str, params: &Value) -> std::result::Result<( pub(crate) type StyleLists = (u64, u64, vectorcraft_doc::Shared>, vectorcraft_doc::Shared>); -/// After a step of a batch a script runs: notes the style lists of each document whose lists or -/// revert count the step changed, so the style objects see a style the batch removed and made -/// again under its name as another style ([`dom::after_command`]). -pub(crate) fn note_style_lists(s: &mut Session) { - for st in &s.docs { - let last = s.script_style_trail.iter().rev().find(|(uid, ..)| *uid == st.uid); - let same = last.is_some_and(|(_, reverts, c, p)| { - *reverts == st.reverts - && vectorcraft_doc::Shared::ptr_eq(c, &st.doc.char_styles) - && vectorcraft_doc::Shared::ptr_eq(p, &st.doc.para_styles) - }); - if !same { - s.script_style_trail.push((st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())); - } +/// What the steps of a command a script runs did to the documents' style lists +/// ([`note_style_lists`]): each open document's lists as the last step left them, the styles a step +/// removed or renamed (a document's uid, whether it is a paragraph style, and the name), and the +/// documents a step reverted. +#[derive(Default)] +pub(crate) struct StyleTrail { + lists: Vec, + pub(crate) gone: std::collections::HashSet<(u64, bool, String)>, + pub(crate) reverted: Vec, +} + +impl StyleTrail { + /// A trail that starts from the documents' style lists now. + fn start(s: &Session) -> Self { + let lists = s.docs.iter().map(|st| (st.uid, st.reverts, st.doc.char_styles.clone(), st.doc.para_styles.clone())).collect(); + StyleTrail { lists, ..Default::default() } } } +/// After a step of a batch a script runs: notes the styles the step removed or renamed and the +/// documents it reverted, so the style objects see a style the batch removed and made again under +/// its name as another style ([`dom::after_command`]). The trail keeps one copy of each open +/// document's lists, however many steps change them. +pub(crate) fn note_style_lists(s: &mut Session) { + let trail = &mut s.script_style_trail; + trail.lists.retain(|(uid, ..)| s.docs.iter().any(|d| d.uid == *uid)); + for st in &s.docs { + let (c, p) = (&st.doc.char_styles, &st.doc.para_styles); + let Some(last) = trail.lists.iter_mut().find(|(uid, ..)| *uid == st.uid) else { + trail.lists.push((st.uid, st.reverts, c.clone(), p.clone())); + continue; + }; + if last.1 != st.reverts { + if !trail.reverted.contains(&st.uid) { + trail.reverted.push(st.uid); + } + } else { + for (para, old, new) in [(false, &last.2, c), (true, &last.3, p)] { + if vectorcraft_doc::Shared::ptr_eq(old, new) { + continue; + } + let names: std::collections::HashSet<&str> = new.iter().map(|d| d.name.as_str()).collect(); + for d in old.iter().filter(|d| !names.contains(d.name.as_str())) { + trail.gone.insert((st.uid, para, d.name.clone())); + } + } + } + *last = (st.uid, st.reverts, c.clone(), p.clone()); + } +} + +/// How many sets of style lists the steps of a batch keep ([`note_style_lists`]). +#[cfg(test)] +pub(crate) fn retained_style_lists(s: &Session) -> usize { + s.script_style_trail.lists.len() +} + /// A bounded snapshot of the active document, or `null` with none open. A snapshot past the limits /// of a crossing throws a `RangeError`. fn vc_document(host: &Host) -> std::result::Result { diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 52852308e3..c448541a23 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -165,7 +165,7 @@ impl Session { script_runs: 0, script_frames: false, script_high_water: Default::default(), - script_style_trail: Vec::new(), + script_style_trail: Default::default(), script_in_run: false, script_copy_first: cfg!(target_arch = "wasm32"), } diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 860aecfa81..12bded346f 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -174,6 +174,15 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { ), ); assert!(e.contains("Stale style"), "{e}"); + // And a style a batch renames and then names back. + let e = failure( + &mut s, + &format!( + "{DOC} var a = cs.getByName('B'); vc.run('command.batch', {{commands: [{{command: 'charStyle.rename', params: {{name: 'B', to: 'C'}}}}, \ + {{command: 'charStyle.rename', params: {{name: 'C', to: 'B'}}}}]}}); a.name;" + ), + ); + assert!(e.contains("Stale style"), "{e}"); // The attributes object of a removed style throws for its typename too. let e = failure(&mut s, &format!("{DOC} var t = cs.getByName('B').characterAttributes; vc.log(t.typename); cs.getByName('B').remove(); t.typename;")); @@ -191,6 +200,20 @@ fn a_renamed_style_keeps_its_object_and_a_removed_style_is_stale() { assert_eq!(runs(&s, id)[0].2, 40.0); } +/// The steps of one batch a script runs keep one copy of a document's style lists, however many of +/// them change the lists. +#[test] +fn the_steps_of_a_batch_keep_one_copy_of_the_style_lists() { + let (mut s, _) = doc_with("Hello"); + let commands: Vec = (0..20).map(|i| json!({"command": "charStyle.new", "params": {"name": format!("S{i}"), "attrs": {}}})).collect(); + s.script_in_run = true; + let r = s.execute("command.batch", &json!({"commands": commands})); + s.script_in_run = false; + r.unwrap(); + assert_eq!(char_names(&s).len(), 20); + assert_eq!(crate::script::retained_style_lists(&s), 1); +} + /// A removal or rename whose result cannot cross to the script is put back, and the style's object /// still names the style after it. #[test] From 8e23d74985eb178d8a43f79c3fe73f252580e54b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:20 -0800 Subject: [PATCH 09/20] Scripts: textFrames.removeAll() refuses type on a locked artboard textFrames.removeAll() now stops with the same error as pageItems.removeAll() and PageItem.remove() when a type object sits on a locked artboard, and deletes nothing. --- crates/engine/src/script/dom.rs | 2 +- crates/engine/src/script/dom/text.rs | 13 ++++++++++--- crates/engine/src/tests/script_dom.rs | 17 +++++++++++++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index c02d65dfbd..b1dab0816e 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1561,7 +1561,7 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer { } /// The error of `remove()` and `removeAll()` for an object on a locked artboard. -const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; +pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard"; /// The error of `move` and `duplicate` given an object of another document. pub const CROSS_DOCUMENT: &str = "Cross-document placement is not available"; diff --git a/crates/engine/src/script/dom/text.rs b/crates/engine/src/script/dom/text.rs index 0366dec5dd..e1386310d3 100644 --- a/crates/engine/src/script/dom/text.rs +++ b/crates/engine/src/script/dom/text.rs @@ -1215,19 +1215,26 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer { in_path(h, a, true, &[2, 3, 5, 6]) } -/// `removeAll()`: deletes every type object in one command; a hidden or locked one stops it first. +/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a +/// locked artboard, stops it first. fn frames_remove_all(h: &Host, a: &[Data]) -> Answer { let doc = frames_doc(h, a)?; - let (ids, refused) = with_doc(h, doc, |_, st| { + let (ids, refused, on_locked) = with_doc(h, doc, |_, st| { let ids = frame_ids(h, st); let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable); let refused: Vec = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect(); - (ids, refused) + let locks = st.doc.locked_artboards(); + let on_locked: Vec = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect(); + (ids, refused, on_locked) }); if !refused.is_empty() { let list = refused.iter().map(u64::to_string).collect::>().join(", "); return Err(HostError::Error(format!("cannot delete hidden or locked type: {list}"))); } + if !on_locked.is_empty() { + let list = on_locked.iter().map(u64::to_string).collect::>().join(", "); + return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD))); + } if !ids.is_empty() { on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})))?; } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 26632b7055..35baf42e88 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -997,6 +997,23 @@ fn remove_and_remove_all_refuse_art_on_a_locked_artboard() { assert_eq!(out, vec![json!(0)]); } +#[test] +fn text_frames_remove_all_refuses_type_on_a_locked_artboard() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap()); + s.edit("Lock Artboard", |d, _| { + d.artboards[0].locked = true; + Ok(()) + }) + .unwrap(); + let steps = undo_steps(&s); + let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();"); + assert!(e.contains(&format!("cannot delete objects on a locked artboard: {}", t.0)), "{e}"); + assert!(s.active().unwrap().doc.node(t).is_some()); + assert_eq!(undo_steps(&s), steps); +} + #[test] fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); From 9c636b9036c2b9cce38da4a0d96d37a763776d92 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 10/20] Scripts: a character style applied to an empty frame styles text set later CharacterStyle.applyTo returned early on any empty range, so on an empty text frame it never reached charStyle.apply, which restyles the stored runs of empty text. It now passes an empty frame through and keeps the no-op only for an empty range inside text. --- crates/engine/src/script/dom/text/styles.rs | 3 ++- crates/engine/src/tests/script_styles.rs | 10 ++++++++++ docs/mcp.md | 5 +++-- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/script/dom/text/styles.rs b/crates/engine/src/script/dom/text/styles.rs index fd896918a9..87bfde4f27 100644 --- a/crates/engine/src/script/dom/text/styles.rs +++ b/crates/engine/src/script/dom/text/styles.rs @@ -359,7 +359,8 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer { let (_, ba, bb) = para_range(&index, s, e); (ba, bb) } else { - if s == e { + // An empty range inside text changes nothing; empty text takes the style on its runs. + if s == e && index.len() > 0 { return Ok(Data::Undefined); } (index.byte(s, false), index.byte(e, true)) diff --git a/crates/engine/src/tests/script_styles.rs b/crates/engine/src/tests/script_styles.rs index 12bded346f..df96906aec 100644 --- a/crates/engine/src/tests/script_styles.rs +++ b/crates/engine/src/tests/script_styles.rs @@ -256,6 +256,16 @@ fn apply_to_styles_a_range_and_clearing_overrides_resets_it() { assert_eq!(runs(&s, id), [("H".into(), None, 30.0, false), ("ello world".into(), Some("Big".into()), 30.0, false)]); } +/// A character style applied to an empty frame styles the text set in it later. +#[test] +fn a_character_style_applied_to_an_empty_frame_styles_text_set_later() { + for target in ["tf", "tf.textRange"] { + let (mut s, id) = doc_with(""); + log(&mut s, &format!("{DOC} var big = cs.add('Big'); big.characterAttributes.size = 30; big.applyTo({target}); tf.contents = 'Hi';")); + assert_eq!(runs(&s, id), [("Hi".into(), Some("Big".into()), 30.0, false)], "{target}"); + } +} + /// A paragraph style styles every paragraph the text touches, and only those. #[test] fn a_paragraph_style_styles_the_paragraphs_the_text_touches() { diff --git a/docs/mcp.md b/docs/mcp.md index 0495483d8e..b302b7ee18 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2756,8 +2756,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot followed by the panel's order. A name is trimmed and must then have 1 to 256 characters and no control characters. An attribute a style does not set reads `undefined`, and setting one changes text in the style where it had the style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the - style's document; a character style on an empty range changes nothing, and a paragraph style styles every - paragraph the text touches. `clearingOverrides` left out is false. A range lists each style once, in the order + style's document; a character style on an empty range inside text changes nothing, on empty text it styles the + text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left + out is false. A range lists each style once, in the order its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws From d261130741b46e71eed594bb95eb23edbac6fb14 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 03:42:21 -0800 Subject: [PATCH 11/20] i18n: translate the 64 MB style file limit in every complete catalog The error for a styles file over the load limit reads "the file is larger than 64 MB". Most complete catalogs translate it through their `the file is larger than {_1} MB` row; ca, el, fi, id and vi have no such row, so each gets an exact row next to its 1 MB one. A test checks the message in every complete-message language. --- crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 14 ++++++++++++++ crates/ui-egui/src/i18n/vi.tsv | 1 + 6 files changed, 19 insertions(+) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..635746fe75 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7549,6 +7549,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg the file holds no preferences el fitxer no conté cap preferència @msg `{key}` names a folder, which preferences files leave out `{key}` indica una carpeta, i els fitxers de preferències no inclouen carpetes @msg the file is larger than 1 MB el fitxer ocupa més d’1 MB +@msg the file is larger than 64 MB el fitxer ocupa més de 64 MB @msg give `path` or `data` indiqueu `path` o `data` @msg `{key}` must be an object `{key}` ha de ser un objecte @msg `prefs.import` runs on its own, not as a batch step `prefs.import` s’executa sol, no com a pas d’un lot diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..e2f3ebce06 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5729,6 +5729,7 @@ digits Malayalam Μαλαγιάλαμ @msg the file holds no preferences το αρχείο δεν περιέχει προτιμήσεις @msg `{key}` names a folder, which preferences files leave out το `{key}` ορίζει φάκελο, και τα αρχεία προτιμήσεων δεν περιέχουν φακέλους @msg the file is larger than 1 MB το αρχείο είναι μεγαλύτερο από 1 MB +@msg the file is larger than 64 MB το αρχείο είναι μεγαλύτερο από 64 MB @msg give `path` or `data` δώστε `path` ή `data` @msg `{key}` must be an object το `{key}` πρέπει να είναι αντικείμενο @msg `prefs.import` runs on its own, not as a batch step το `prefs.import` εκτελείται μόνο του, όχι ως βήμα δέσμης diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..d791677d24 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -6012,6 +6012,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg the file holds no preferences tiedostossa ei ole asetuksia @msg `{key}` names a folder, which preferences files leave out `{key}` nimeää kansion, eikä asetustiedostoissa ole kansioita @msg the file is larger than 1 MB tiedosto on suurempi kuin 1 Mt +@msg the file is larger than 64 MB tiedosto on suurempi kuin 64 Mt @msg give `path` or `data` anna `path` tai `data` @msg `{key}` must be an object `{key}` on oltava objekti @msg `prefs.import` runs on its own, not as a batch step `prefs.import` ajetaan yksinään, ei erän vaiheena diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..ed4341007e 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -6090,6 +6090,7 @@ imageTrace Outline Kontur @msg the file holds no preferences file tidak berisi preferensi @msg `{key}` names a folder, which preferences files leave out `{key}` menunjuk folder, dan file preferensi tidak menyertakan folder @msg the file is larger than 1 MB file lebih besar dari 1 MB +@msg the file is larger than 64 MB berkas lebih besar dari 64 MB @msg give `path` or `data` berikan `path` atau `data` @msg `{key}` must be an object `{key}` harus berupa objek @msg `prefs.import` runs on its own, not as a batch step `prefs.import` dijalankan sendiri, bukan sebagai langkah batch diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..fb428adbd9 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -3860,6 +3860,20 @@ fn warped_type_note_is_translated() { } } +/// The error for a character or paragraph styles file over the 64 MB load limit is translated in +/// every complete catalog, through an exact row or the `the file is larger than {_1} MB` template. +#[test] +fn styles_file_size_limit_is_translated() { + assert_eq!(vectorcraft_engine::cmd::textstyles::MAX_LOAD_BYTES, 64 << 20); + let error = "the file is larger than 64 MB"; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, error); + assert_ne!(shown, error, "{code}"); + assert!(shown.contains("64"), "{code}: {shown}"); + } +} + /// The notes a CDR import adds to its warnings are translated in every complete catalog. /// They are constants, which the scan of message literals doesn't see. #[test] diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..d58bfa4bc4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -6461,6 +6461,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg the file holds no preferences tệp không chứa tùy chọn nào @msg `{key}` names a folder, which preferences files leave out `{key}` chỉ định một thư mục, và tệp tùy chọn không chứa thư mục @msg the file is larger than 1 MB tệp lớn hơn 1 MB +@msg the file is larger than 64 MB tệp lớn hơn 64 MB @msg give `path` or `data` hãy cung cấp `path` hoặc `data` @msg `{key}` must be an object `{key}` phải là một đối tượng @msg `prefs.import` runs on its own, not as a batch step `prefs.import` chạy riêng, không phải là một bước trong lô From ecc4d9cd7489ee58078dafe310bbb264148943ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:04:35 -0800 Subject: [PATCH 12/20] Tests: text frame tests index page items topmost first pageItems and textFrames now list the topmost object first, so the tests pick the rectangle and the open path by their new indices. --- crates/engine/src/tests/script_text.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_text.rs b/crates/engine/src/tests/script_text.rs index 36dff46fa0..f22853d4e7 100644 --- a/crates/engine/src/tests/script_text.rs +++ b/crates/engine/src/tests/script_text.rs @@ -56,8 +56,8 @@ fn text_frames_add_point_area_and_path_type() { let out = log( &mut s, "var d = app.activeDocument, p = d.pageItems;\ - var area = d.textFrames.areaText(p[0]); area.contents = 'Area';\ - var path = d.textFrames.pathText(p[1]); path.contents = 'Path';\ + var area = d.textFrames.areaText(p[1]); area.contents = 'Area';\ + var path = d.textFrames.pathText(p[0]); path.contents = 'Path';\ var pt = d.textFrames.add(); pt.contents = 'Point';\ var at = d.textFrames.pointText([30, 40]); at.contents = 'At';\ vc.log(d.textFrames.length); vc.log([area.kind, path.kind, pt.kind]);\ @@ -67,7 +67,7 @@ fn text_frames_add_point_area_and_path_type() { ); assert_eq!(out[0], json!(4)); assert_eq!(out[1], json!(["TextType.AREATEXT", "TextType.PATHTEXT", "TextType.POINTTEXT"])); - assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("At"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); + assert_eq!(out[2..], [json!("TextFrame"), json!(true), json!("Area"), json!(true), json!("TextOrientation.HORIZONTAL"), json!("Document")]); assert_eq!(undo_steps(&s), before + 1); // A path of another kind, or no path, is refused. assert!(failure(&mut s, "app.activeDocument.textFrames.areaText(app.activeDocument.textFrames[0]);").contains("PathItem")); @@ -476,7 +476,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}"); From a2e04d98e0850305caa2fb50470ac8314546b5d3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 22:51:03 -0800 Subject: [PATCH 13/20] 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 908f8c5cb59cfdd86405018ead042c9fe4beeb70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 01:42:13 -0800 Subject: [PATCH 14/20] Image Trace: Flat Logo keeps gray bands along black when the gray is named some levels off With a gray named 6 to 20 levels off the color its flat areas have, a gray band 3 or 4 pixels wide along black, with edges blurred by 0.6 pixels, traced as black and white: no band pixel came within PURE of the named gray, so the run rule and the sharp-edge halt in across_edge never kept the gray. unmix now takes the colors of each class's flat areas (area_colors). For a class with a flat area PURE or more from its named color, pixels within PURE of one of those colors also count as the class's pixels for the LINE run rule. The sharp-edge halt stops at a pixel near one of those colors, or at a pixel within PURE of the named color whose previous pixel on the path is too, so a strip at the named color 2 or more pixels wide keeps its gray while single edge pixels near the named color do not. The halt is checked before the walk counts a pixel as past the class, since a pixel of the area's color can lie past the named color on the line. On the band test images (gray 230, 200 and 128 named 6 or 12 levels off, 3 and 4 pixel bands beside a flat square of the gray), 0 to 33 band samples of 48 or 64 traced gray before, and 40 to 61 after. Images whose classes have no flat area off their named color trace as before. --- crates/trace/src/logo/tests.rs | 35 ++++++++ crates/trace/src/logo/unmix.rs | 146 +++++++++++++++++++++++++++++---- 2 files changed, 164 insertions(+), 17 deletions(-) diff --git a/crates/trace/src/logo/tests.rs b/crates/trace/src/logo/tests.rs index 00b05b350c..3fbe8c3cac 100644 --- a/crates/trace/src/logo/tests.rs +++ b/crates/trace/src/logo/tests.rs @@ -1111,6 +1111,41 @@ fn a_soft_gray_band_along_black_traces_as_black_and_white() { assert!((36..=42).contains(&blur_three), "bands 4 px wide blurred by 3 px: {blur_three} of 192 samples traced gray"); } +/// A gray band 3 or 4 pixels wide along a black disc, with edges blurred by 0.6 pixels and a flat +/// square of the same gray elsewhere, keeps at least 4 of every 5 samples gray when the gray is named +/// 6 or 12 levels lighter or darker than the band's color, as it does when the gray is named exactly: +/// the pixels of the square's color count as pixels of the gray. +#[test] +fn a_gray_band_along_black_keeps_its_gray_when_named_some_levels_off_its_flat_areas() { + const INK: [u8; 3] = [4, 4, 3]; + for gray in [230u8, 200, 128] { + for off in [-12i16, -6, 6, 12] { + let Ok(named) = u8::try_from(i16::from(gray) + off) else { continue }; + for wide in [3u8, 4] { + let img = render(120, 60, 0.6, |x, y| { + let band = (40.0..43.0 + f64::from(wide)).contains(&x) && (20.0..36.0).contains(&y); + let square = (80.0..110.0).contains(&x) && (15.0..45.0).contains(&y); + Some(if (x - 25.0).hypot(y - 28.0) <= 18.0 { + INK + } else if band || square { + [gray; 3] + } else { + WHITE + }) + }); + let res = trace(&img, &black_gray_white([named; 3])); + let kept = (0..wide) + .flat_map(|c| (20..36).map(move |y| Point::new(43.5 + f64::from(c), f64::from(y) + 0.5))) + .filter(|&at| top_color(&res, at) == Some([named; 3])) + .count(); + let all = 16 * usize::from(wide); + assert!(5 * kept >= 4 * all, "gray {gray} named {named}, {wide} px band: {kept} of {all} samples traced gray"); + assert_eq!(top_color(&res, Point::new(95.0, 30.0)), Some([named; 3]), "gray {gray} named {named}: the square"); + } + } + } +} + /// A soft-edged gray spoke two or three pixels wide running straight out of a black disc, blurred /// by 1 or 1.5 pixels, loses 3 or 4 of its 16 samples nearest the disc and keeps the rest. Blurred /// by 2 pixels, a spoke three pixels wide loses 2 or 3 of them, and one two pixels wide traces as diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 048c8fac71..576986e83c 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -27,12 +27,12 @@ const NEARBY: usize = 6; const WALK: usize = 5; /// A pixel whose neighbors are all this close to it (in 0..1 premultiplied RGBA) lies in a flat area. const FLAT: f64 = 1.5 / 255.0; -/// How many joined pixels within [`PURE`] of one class are taken as art of that class, such as a -/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. -/// A straight edge whose anti-aliased pixels come within `PURE` of -/// a class gives the same pixels as a line of that class, and keeps the class too. A one-pixel line -/// between two classes that is shorter, falls between pixels or is blurred is read as a blend of -/// those two classes. +/// How many joined pixels within [`PURE`] of one class (or of the colors of its flat areas, for a +/// class named some levels off them, [`area_colors`]) are taken as art of that class, such as a +/// one-pixel line. The edge pixels of a curve that come within `PURE` of a class join in far fewer. A +/// straight edge whose anti-aliased pixels come within `PURE` of a class gives the same pixels as a +/// line of that class, and keeps the class too. A one-pixel line between two classes that is shorter, +/// falls between pixels or is blurred is read as a blend of those two classes. const LINE: usize = 2 * NEARBY + 1; struct Subset { @@ -209,24 +209,33 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] // ([`flat_classes`], [`RowDistances::around`]); the other mix lies as near as the steps that // `across_edge` counts when those are fewer. For the best mix, // the classes held by flat areas between two classes count as well ([`between_classes`]). A - // pixel within `PURE` of a class that is joined to at least [`LINE`] such pixels of that class + // pixel of a class (within `PURE` of it, or of the colors of its flat areas when it is named some + // levels off them, [`area_colors`]) that is joined to at least [`LINE`] such pixels of that class // (itself included) keeps it ([`pure_runs`]), as a one-pixel line of gray between black and white. let flat = flat_classes(pix, &stands_for, width, height); let between = between_classes(pix, &flat, &mixed, width, height); - let runs = pure_runs(&pure, width, height); + let colors = area_colors(pix, classes, &flat, &between); + let of_class = (!colors.iter().all(Vec::is_empty)).then(|| { + pure.iter() + .zip(pix) + .map(|(&q, px)| q.or_else(|| (0..k).find(|&c| colors.get(c).is_some_and(|cs| near_area_color(px, cs))))) + .collect::>() + }); + let of_class = of_class.as_deref().unwrap_or(&pure); + let runs = pure_runs(of_class, width, height); let mut flat_rows = RowDistances::new(|j| [flat.get(j).copied().flatten(), None], width, height, k); let mut between_rows = (!between.is_empty()).then(|| RowDistances::new(|j| between.get(j).copied().unwrap_or([None; 2]), width, height, k)); let mut dist = vec![NEARBY + 1; k]; let mut kept = vec![NEARBY + 1; k]; for (i, key) in tied { - if pure.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) { + if of_class.get(i).copied().flatten().is_some() && runs.get(i).is_some_and(|&r| r >= LINE) { continue; } let Some(mixes) = mixed.get(&key) else { continue }; let edges: Vec<(&Weights, usize)> = mixes .tied .iter() - .filter_map(|m| across_edge(pix, (&flat, &stands_for), (width, height), i, classes, &mixes.best, m).map(|r| (m, r))) + .filter_map(|m| across_edge(pix, (&flat, &stands_for, &colors), (width, height), i, classes, &mixes.best, m).map(|r| (m, r))) .collect(); if edges.is_empty() { continue; @@ -258,7 +267,10 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// `other` gets past the class left out within [`WALK`] steps through the eight neighbors, and so /// does one that keeps going toward the other. When the first step of one path comes to a pixel /// that stands for its class of `other` (the edge on that side is sharp), the other path stops at -/// a pixel within [`PURE`] of the class left out that it comes to before it gets past that class. +/// a pixel of the class left out that it comes to before it gets past that class: a pixel within +/// [`PURE`] of it, or, for a class named some levels off the colors of its flat areas +/// ([`area_colors`]), within `PURE` of one of those colors, or within `PURE` of the class as named +/// together with the pixel before it. /// For a class left out that lies beyond both classes of `other` on that line, the pixel has a /// neighbor on each side of that class, or a neighbor on each side of the pixel itself, none past /// the class of `other` nearer the class left out, and a chain of neighbors from the pixel to that @@ -279,7 +291,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] /// path does not come to such a pixel, and when a class left out lies beyond both classes of `other`. fn across_edge( pix: &[Px], - (flat, stands_for): (&[Option], &[Option]), + (flat, stands_for, colors): (&[Option], &[Option], &AreaColors), (width, height): (usize, usize), i: usize, classes: &[[f64; 4]], @@ -356,11 +368,19 @@ fn across_edge( } false }; - // Whether pixel `j` comes within `PURE` of class `c`. - let within = |j: usize, c: usize| { + // Whether pixel `j` comes within `PURE` of class `c` as named. + let named = |j: usize, c: usize| { let (Some(q), Some(cv)) = (pix.get(j), classes.get(c)) else { return false }; (0..4).map(|k| (f64::from(q[k]) - cv[k]).powi(2)).sum::().sqrt() < PURE }; + // Whether pixel `j`, reached from pixel `prev`, is a pixel of class `c`: within `PURE` of it, or, + // for a class named some levels off the colors of its flat areas ([`area_colors`]), within `PURE` + // of one of those colors, or within `PURE` of the class as named with `prev` too (the class as + // named lies across at least two pixels there, which the pixels of a black-to-white edge do not). + let within = |prev: usize, j: usize, c: usize| match colors.get(c) { + Some(cs) if !cs.is_empty() => pix.get(j).is_some_and(|q| near_area_color(q, cs)) || (named(prev, c) && named(j, c)), + _ => named(j, c), + }; // The neighbor of pixel `j` near the line that lies farthest toward `a` (`toward` -1) or `b` // (`toward` 1), with its place. let next = |j: usize, toward: f64| around(j).filter_map(|n| at(n).map(|tn| (n, tn))).max_by(|p, q| (p.1 * toward).total_cmp(&(q.1 * toward))); @@ -368,19 +388,22 @@ fn across_edge( // pixel before (the first step is taken whatever `i` itself is). `None` when it does not get more // than `PURE` past `tc` in [`WALK`] steps; otherwise the steps to the first pixel past it that // stands for `class` (`stands_for`), or `NEARBY + 1`. With `halt`, the path also ends at a pixel - // within `PURE` of that class that it comes to before it gets past `tc`. + // of that class ([`within`]) that it comes to before it gets past `tc`. let walk = |toward: f64, tc: f64, class: usize, halt: Option| { let (mut cur, mut t) = (i, f64::NEG_INFINITY * toward); let mut past = false; for step in 1..=WALK { + let prev = cur; match next(cur, toward) { Some((j, tj)) if (tj - t) * toward > 0.0 => (cur, t) = (j, tj), _ => break, } - past = past || (t - tc) * toward * len > PURE; - if !past && halt.is_some_and(|h| within(cur, h)) { + // (A pixel of a flat area's color can lie past `tc` itself, when the class is named some + // levels off that color: the path stops there when it was not past `tc` before.) + if !past && halt.is_some_and(|h| within(prev, cur, h)) { break; } + past = past || (t - tc) * toward * len > PURE; if past && stands_for.get(cur).copied().flatten() == Some(class) { return Some(step); } @@ -484,6 +507,39 @@ fn between_classes(pix: &[Px], flat: &[Option], mixed: &HashMap<[u32; 4], held } +/// For each class with a flat area [`PURE`] or more from it (as when it is named some levels off its +/// color), the colors of its flat areas, each at least `PURE / 2` from the others: the flat areas that +/// stand for it (`flat`) and those whose mix holds it most (`between`, [`between_classes`]). Empty for +/// a class whose flat areas all come within `PURE` of it. +fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between: &[[Option; 2]]) -> Vec> { + let mut colors: Vec> = vec![Vec::new(); classes.len()]; + let mut off_named = vec![false; classes.len()]; + for (i, px) in pix.iter().enumerate() { + let Some(c) = flat.get(i).copied().flatten().or_else(|| between.get(i).and_then(|b| b[0])) else { continue }; + let (Some(cv), Some(seen), Some(off)) = (classes.get(c), colors.get_mut(c), off_named.get_mut(c)) else { continue }; + *off = *off || (0..4).map(|j| (f64::from(px[j]) - cv[j]).powi(2)).sum::().sqrt() >= PURE; + if !seen.iter().any(|q| distance(px, q) < PURE / 2.0) { + seen.push(*px); + } + } + for (seen, off) in colors.iter_mut().zip(off_named) { + if !off { + seen.clear(); + } + } + colors +} + +/// Whether `px` comes within [`PURE`] of one of `colors`. +fn near_area_color(px: &Px, colors: &[Px]) -> bool { + colors.iter().any(|q| distance(px, q) < PURE) +} + +/// How far apart two pixels are (in 0..1 premultiplied RGBA). +fn distance(a: &Px, b: &Px) -> f64 { + (0..4).map(|j| (f64::from(a[j]) - f64::from(b[j])).powi(2)).sum::().sqrt() +} + /// For each of `k` classes, how far along each row the nearest pixel holding that class (`at`, the /// classes pixel `j` holds) lies from each pixel, up to `NEARBY + 1` when none lies within /// [`NEARBY`]. A row is worked out when it is first asked for, so a few pixels cost a few rows. @@ -612,6 +668,9 @@ fn in_flat_area(pix: &[Px], width: usize, height: usize, x: usize, y: usize) -> /// Each class's weight in a pixel's mix. type Weights = Vec<(usize, f32)>; +/// For each class, the colors of its flat areas that lie [`PURE`] or more from it ([`area_colors`]). +type AreaColors = [Vec]; + /// A mix tried for a pixel: its squared error with its penalty, the penalty, and its classes with /// their weights (the first `n`). #[derive(Clone, Copy)] @@ -803,6 +862,59 @@ mod tests { } } + #[test] + fn a_column_as_light_as_a_class_keeps_it_beside_a_flat_area_some_levels_off_it() { + // As above, with a flat area of the gray some levels darker than it is named to the right of + // the white: a column of `LINE` rows at the named value is still gray art. + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + let mut pix = Vec::new(); + for _ in 0..LINE { + pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]); + pix.push([0.9, 0.9, 0.9, 1.0]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]); + } + let (pl, _, _) = unmix(&pix, 16, LINE, &classes); + for y in 0..LINE { + assert_eq!(pl[0][y * 16 + 5], 1.0, "gray in row {y}"); + assert!(pl[0][y * 16 + 13] > 0.9, "the flat area in row {y}"); + } + } + + #[test] + fn a_short_strip_as_light_as_a_class_traces_the_same_beside_a_flat_area_some_levels_off_it() { + // Three rows of flat black, a strip 1 to 3 pixels wide at the gray's value and flat white: with + // a flat area of the gray some levels darker than it is named to the right of the white, the + // strip's pixels take the same mixes as without it (a strip 2 or 3 pixels wide stays gray). + let classes = vec![[0.9, 0.9, 0.9, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]; + for wide in [1usize, 2, 3] { + let rows = |area: bool| { + let mut pix = Vec::new(); + for _ in 0..3 { + pix.extend([[0.0f32, 0.0, 0.0, 1.0]; 5]); + pix.extend(vec![[0.9f32, 0.9, 0.9, 1.0]; wide]); + pix.extend([[1.0f32, 1.0, 1.0, 1.0]; 5]); + if area { + pix.extend([[0.87f32, 0.87, 0.87, 1.0]; 5]); + } + } + pix + }; + let w = 10 + wide; + let (alone, _, _) = unmix(&rows(false), w, 3, &classes); + let (beside, _, _) = unmix(&rows(true), w + 5, 3, &classes); + for y in 0..3 { + for x in 0..w { + let mix = |pl: &[Vec], w: usize| pl.iter().take(3).map(|p| p[y * w + x]).collect::>(); + assert_eq!(mix(&beside, w + 5), mix(&alone, w), "{wide} px strip: the mix at ({x}, {y})"); + } + } + if wide > 1 { + assert_eq!(beside[0][w + 5 + 5], 1.0, "{wide} px strip: gray"); + } + } + } + #[test] fn an_edge_pixel_takes_no_class_beyond_both_classes_beside_it() { // A pale ground, a gray and a charcoal on one line: a row of flat gray, one edge pixel halfway From 8cf95b7f45ca1437425d891fc7d4694a9ba2d655 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:17:43 -0800 Subject: [PATCH 15/20] Image Trace: Flat Logo keeps every flat-area color of an off-named class area_colors kept a flat-area color only when no stored color lay within PURE / 2 of it, while near_area_color matches within PURE. A color dropped that way took its PURE neighborhood with it: with flat areas of 222 then 223 under a class named 228, 228, 227, a pixel of 225 lies within PURE of 223 but not of 222, and lost its class membership. Keep every distinct flat-area color per class instead, and add a unit test for that case. --- crates/trace/src/logo/unmix.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 576986e83c..01ef0ce2e5 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -508,17 +508,18 @@ fn between_classes(pix: &[Px], flat: &[Option], mixed: &HashMap<[u32; 4], } /// For each class with a flat area [`PURE`] or more from it (as when it is named some levels off its -/// color), the colors of its flat areas, each at least `PURE / 2` from the others: the flat areas that +/// color), the distinct colors of its flat areas: the flat areas that /// stand for it (`flat`) and those whose mix holds it most (`between`, [`between_classes`]). Empty for /// a class whose flat areas all come within `PURE` of it. fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between: &[[Option; 2]]) -> Vec> { let mut colors: Vec> = vec![Vec::new(); classes.len()]; let mut off_named = vec![false; classes.len()]; + let mut kept: HashSet<(usize, [u32; 4])> = HashSet::new(); for (i, px) in pix.iter().enumerate() { let Some(c) = flat.get(i).copied().flatten().or_else(|| between.get(i).and_then(|b| b[0])) else { continue }; let (Some(cv), Some(seen), Some(off)) = (classes.get(c), colors.get_mut(c), off_named.get_mut(c)) else { continue }; *off = *off || (0..4).map(|j| (f64::from(px[j]) - cv[j]).powi(2)).sum::().sqrt() >= PURE; - if !seen.iter().any(|q| distance(px, q) < PURE / 2.0) { + if kept.insert((c, px.map(f32::to_bits))) { seen.push(*px); } } @@ -1018,6 +1019,21 @@ mod tests { } } + #[test] + fn every_flat_area_color_keeps_its_whole_neighborhood() { + // A class named 228, 228, 227 and flat areas of 222 then 223: a pixel of 225 lies within + // `PURE` of 223 but not of 222, so it counts as art of the class only when 223 is kept. + let level = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0]; + let classes = vec![[228.0 / 255.0, 228.0 / 255.0, 227.0 / 255.0, 1.0], [0.0, 0.0, 0.0, 1.0]]; + let pix = vec![level(222.0), level(222.0), level(223.0), level(223.0)]; + let flat = vec![Some(0); pix.len()]; + let between = vec![[None; 2]; pix.len()]; + let colors = area_colors(&pix, &classes, &flat, &between); + assert_eq!(colors[0].len(), 2, "{:?}", colors[0]); + assert!(near_area_color(&level(225.0), &colors[0])); + assert!(!near_area_color(&level(225.0), &colors[0][..1])); + } + #[test] fn weights_sum_to_one() { let pix = vec![[0.2, 0.1, 0.5, 0.8], [0.9, 0.0, 0.05, 0.95]]; From e2ac712ad23fa1738ba3d63944689ae2209de9b2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:57:54 -0800 Subject: [PATCH 16/20] Place: Replace keeps a distorted image's corners for a raster file File > Place with Replace refused an image changed by Perspective Distort or Free Distort. When the placed file is a raster image or a DCS file, the new image now takes the old image's corners in one undo step: its pixels fill them, its transform is the old one scaled to the new pixel size (as Update Links scales it), the clipping path a PSD, PSB or DCS file names is drawn through the corners, and a PSD file's slices cover their part of the pixels where the corners put it. Vector and document files are still refused; text is placed by the bounds as before. --- .../engine/src/cmd/fileio/tests_psdslices.rs | 24 +++++ crates/engine/src/cmd/links.rs | 2 +- crates/engine/src/cmd/place.rs | 87 ++++++++++++++++--- crates/engine/src/tests/dcs.rs | 27 ++++++ crates/engine/src/tests/links.rs | 41 +++++++++ crates/engine/src/tests/xform.rs | 3 +- docs/mcp.md | 10 ++- docs/target-app-parity.md | 2 +- 8 files changed, 180 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdslices.rs b/crates/engine/src/cmd/fileio/tests_psdslices.rs index cc210ffa2a..ded0f137b3 100644 --- a/crates/engine/src/cmd/fileio/tests_psdslices.rs +++ b/crates/engine/src/cmd/fileio/tests_psdslices.rs @@ -456,6 +456,30 @@ fn placed_embedded_files_bring_their_slices_with_the_art_in_one_undo_step() { } } +/// A file placed with Replace over an image changed by Perspective Distort or Free Distort takes +/// its corners, and its slices cover what the corners put their part of the pixels on. +#[test] +fn slices_placed_over_a_distorted_image_follow_its_corners() { + let f = with_resource(&psd(false), 1050, &v6(&[user("a", [0, 0, 10, 10])], &[])); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + s.execute("file.place", &json!({"name": "a.png", "dataBase64": b64(&png), "at": [100, 100]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [160, 104], [150, 140], [96, 136]]})).unwrap(); + let r = s.execute("file.place", &json!({"name": "poster.psd", "dataBase64": b64(&f), "replace": true})).unwrap(); + assert_eq!(r["slices"].as_array().map(Vec::len), Some(1), "{r}"); + let d = &s.doc().unwrap().doc; + let image = d.node(vectorcraft_doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + assert!(image.is_distorted_image()); + let vectorcraft_doc::NodeKind::Image(im) = &image.kind else { panic!("an image") }; + // The top left quarter of the 20 × 20 px canvas. + let (w, h) = (f64::from(im.width) / 2.0, f64::from(im.height) / 2.0); + let want = image.image_map().unwrap().map_rect_bbox(Rect::new(0.0, 0.0, w, h)).unwrap(); + let got = slices(&s)[0].0; + let near = |a: f64, b: f64| (a - b).abs() < 1e-6; + assert!(near(got.x0, want.x0) && near(got.y0, want.y0) && near(got.x1, want.x1) && near(got.y1, want.y1), "{got:?} vs {want:?}"); +} + #[test] fn linked_files_are_placed_without_their_slices() { let dir = std::env::temp_dir().join(format!("vc-psd-slices-{}", std::process::id())); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 5a77b6d780..22a3c2112e 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1308,7 +1308,7 @@ fn refill_distorted( /// `path` with its anchors and handles mapped through `map` as a distort maps a path's points /// (`xform::Projective::apply`): a point on the map's horizon is mapped as if a billionth in front /// of it, and one past it to the far side. `None` when a point maps to no finite page point. -fn warped(path: &PathData, map: &Homography) -> Option { +pub(super) fn warped(path: &PathData, map: &Homography) -> Option { let [[a, b, c], [d, e, f], [g, h, i]] = map.0; let apply = |p: vectorcraft_geom::Point| { let w = g * p.x + h * p.y + i; diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index d1c86a4f62..07ccb01f57 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -57,7 +57,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_color::Paint; use vectorcraft_doc::{Appearance, Document, ImageObject, LinkInfo, Node, NodeId, NodeKind, PageBox, Scaling, SliceOptions, SymbolBoxes}; -use vectorcraft_geom::{Affine, Point, Rect, shapes}; +use vectorcraft_geom::{Affine, Homography, Point, Rect, shapes}; use vectorcraft_pdf::CropTo; use super::fileio::{self, Format, RasterImage}; @@ -88,7 +88,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given, and an EPS file, a PostScript file or a PostScript .ai at path, showing the art false gives; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; an image changed by Perspective Distort or Free Distort keeps its corners, which a raster image or a DCS file's image fills, with its file's clipping path drawn through them, and other files but text are refused; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password), importer?: \"plugin.\" (an importer plug-in whose manifest sets place, see document.formats: it reads the file, which must have an extension it lists, also one a built-in format reads; without importer, a file no built-in format reads, by its content or its extension, is read by the first such importer by id that lists its extension; it is given the file, at most 128 MiB, with _context.mode \"place\", and its objects, guides left out, are placed as one group named after the file, in the order it returned them, embedded whatever link says), params?: {…} (the importer's own parameters, see plugin.info)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), @@ -687,6 +687,60 @@ fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Nod } } +/// What Replace does when the image it measures, `old`, is distorted and the art placed is a +/// raster image or a DCS file's image (`art`): the transform that puts the new pixels on `old`'s +/// transform scaled to their size, as Update Links scales it, the corners the new image takes, and +/// the map from the art's natural box to the page through those corners, which a PSD file's slices +/// follow. `None` for other art, for an image with no pixels, and for corners the new pixels can't +/// fill ([`Node::set_image_corners`]). +fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homography)> { + let NodeKind::Image(im) = &old.kind else { return None }; + let q = old.image_quad()?; + let (pixels, width, height) = match art { + Art::Image(img, _) => { + let (sx, sy) = pt_per_px(img.ppi); + (Affine::scale_non_uniform(sx, sy), img.width, img.height) + } + Art::Dcs(a) => (a.xf, a.img.width, a.img.height), + _ => return None, + }; + if width == 0 || height == 0 || pixels.determinant().abs() <= 1e-12 { + return None; + } + let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height)); + let new = ImageObject { key: String::new(), width, height, xf, link: None, placement: Default::default(), pixels: None }; + let mut probe = Node::new(old.id, NodeKind::Image(Box::new(new))); + probe.set_image_corners(q).ok()?; + let page = probe.image_map()?.checked_then_after(&Homography::from_affine(pixels.inverse()))?; + Some((xf * pixels.inverse(), q, page)) +} + +/// Placed raster `node` (an image, or an image in a clip group of its file's clipping path, as +/// [`build`] makes them) with the image's corners at `q`: the pixels fill them, and the clipping +/// path is drawn through them as the pixels are. `None` when the corners can't hold the image. +fn with_corners(mut node: Node, q: [Point; 4]) -> Option { + match &mut node.kind { + NodeKind::Image(_) => node.set_image_corners(q).ok()?, + NodeKind::Group { children, clip: true } => { + let [path, image] = &mut children[..] else { return None }; + let image = Arc::make_mut(image); + let NodeKind::Image(im) = &image.kind else { return None }; + if im.xf.determinant().abs() <= 1e-12 { + return None; + } + // The clipping path in the image's pixels, which its transform placed on the page. + let to_pixels = im.xf.inverse(); + image.set_image_corners(q).ok()?; + let map = image.image_map()?; + let NodeKind::Path { path: p, .. } = &mut Arc::make_mut(path).kind else { return None }; + p.transform(to_pixels); + *p = super::links::warped(p, &map)?; + } + _ => return None, + } + Some(node) +} + /// `rect` fitted with `natural`'s aspect, centred. fn fit(natural: Rect, r: Rect) -> Affine { let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b); @@ -846,18 +900,22 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { loaded.natural = Rect::from_origin_size(Point::ORIGIN, size); } let natural = loaded.natural; - // Replace keeps the transform of the image it measures (`replace_measured`), which a - // distortion's corners do not follow. Type, and any other object it measures, is placed by the - // bounds of what it replaces, so a distorted image there is not refused. + // Replace keeps the transform of the image it measures (`replace_measured`). When that image + // is distorted, a raster placed in its place takes its corners ([`distorted_replace`]); other + // art is refused. Type, and any other object it measures, is placed by the bounds of what it + // replaces, so a distorted image there is not refused. + let mut distorted = None; if let Some(o) = old_node && !is_text { let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..))); if image.is_distorted_image() { - return Err(super::xform::distorted_image_error(PLACE, image.id)); + let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?; + distorted = Some((image.id, fit)); } } let m = match (old_node, rect) { + (Some(_), _) if let Some((_, (m, ..))) = distorted => m, (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))), (None, Some(r)) => fit(natural, r), // Its artboard's bottom-left corner on the target's. @@ -876,13 +934,19 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { if let Art::Dcs(a) = &loaded.art { warnings.extend(dcs::swatch_notes(&st.doc, &a.spots)); } - // A PSD file's slices move and scale with its art; one that would leave the canvas is left out. + // A PSD file's slices move and scale with its art, through a distorted image's corners when + // it takes them; one that would leave the canvas is left out. let read_count = read_slices.len(); let slices: Slices = read_slices .into_iter() .filter_map(|(r, o)| { - let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); - let placed = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)); + let placed = match distorted { + Some((_, (_, _, page))) => page.map_rect_bbox(r)?, + None => { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|c| m * c); + corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |acc, c| acc.union_pt(*c)) + } + }; super::slices::slice_rect_ok(placed).then_some((placed, o)) }) .collect(); @@ -892,7 +956,10 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")), } let (id, size, slice_ids) = s.edit("Place", |d, sel| { - let node = transformed(build(d, loaded, link), m); + let mut node = transformed(build(d, loaded, link), m); + if let Some((old_image, (_, q, _))) = distorted { + node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?; + } let size = node.geometric_bounds_with(&d.symbol_boxes()).unwrap_or_default(); let (into, index) = match old { Some(old) => { diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index a8e37ff812..32dd882f32 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -267,6 +267,33 @@ fn update_and_relink_draw_the_files_clipping_path_through_a_distorted_images_cor assert_eq!(node(&s).image_corners().unwrap(), corners); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a DCS file puts +/// the file's image between the corners and draws its clipping path through them. +#[test] +fn place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners() { + let dir = temp_dir("replace-distorted-clip"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let png = crate::tests_links::png(4, 4, [255, 0, 0]); + let r = s.execute("file.place", &json!({ "name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100] })).unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("object.distort", &json!({ "corners": [[100, 100], [160, 104], [150, 140], [96, 136]] })).unwrap(); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({ "path": path, "replace": true })).unwrap(); + let group = NodeId(r["ids"][0].as_u64().unwrap()); + let id = NodeId(r["image"].as_u64().unwrap()); + let node = s.doc().unwrap().doc.node(id).unwrap().clone(); + assert!(node.is_distorted_image()); + assert_eq!(node.image_corners().unwrap(), corners); + let NodeKind::Group { children, clip: true } = &s.doc().unwrap().doc.node(group).unwrap().kind else { panic!("a clipping group") }; + let NodeKind::Path { path, clipping: true, .. } = &children[0].kind else { panic!("a clipping path") }; + let anchors: Vec<_> = path.anchors().map(|(_, _, a)| a.p).collect(); + // The left half of the 2 × 2 pixels, where the corners put it. + let map = node.image_map().unwrap(); + let want = [(0.0, 0.0), (1.0, 0.0), (1.0, 2.0), (0.0, 2.0)].map(|(x, y)| map.apply(vectorcraft_geom::Point::new(x, y)).unwrap()); + assert!(anchors.len() == want.len() && want.iter().all(|w| anchors.iter().any(|a| a.distance(*w) < 1e-6)), "{anchors:?} vs {want:?}"); +} + #[test] fn update_link_clips_an_image_whose_file_gained_a_clipping_path() { let dir = temp_dir("update-gained-clip"); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 6391c4f3db..405bb12a37 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -812,6 +812,47 @@ fn relink_embed_and_unembed_keep_a_distorted_images_corners() { assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); } +/// Place with Replace of a distorted image by an image file keeps its corners, in one undo step: +/// the new file's pixels fill them, the new image is linked to that file, and its transform is the +/// old image's scaled to the new pixel size. Undo brings the old image back between the same +/// corners. +#[test] +fn place_with_replace_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-place-replace"); + let (photo, other) = (dir.file("photo.png"), dir.file("other.png")); + write(&photo, &png(20, 10, RED)); + write(&other, &png(60, 20, BLUE)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // Around the artboard's center, where `centre_colour` looks. + s.execute("object.distort", &json!({"corners": [[150, 100], [250, 110], [260, 200], [140, 190]]})).unwrap(); + let node = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).cloned(); + let before = node(&s, id).unwrap().image_corners().unwrap(); + let old_xf = image(&s, id).xf; + let undo_len = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = undo_len(&s); + + let r = s.execute("file.place", &json!({"path": other, "replace": true})).unwrap(); + let new = NodeId(r["ids"][0].as_u64().unwrap()); + assert_eq!(undo_len(&s), undo + 1); + assert!(node(&s, id).is_none(), "the old image is replaced"); + let n = node(&s, new).unwrap(); + assert!(n.is_distorted_image()); + assert_eq!(n.image_corners().unwrap(), before); + let im = image(&s, new); + assert_eq!((im.width, im.height), (60, 20)); + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(other.as_str())); + let want = old_xf * vectorcraft_geom::Affine::scale_non_uniform(20.0 / 60.0, 10.0 / 20.0); + assert!(im.xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{:?} against {want:?}", im.xf); + assert!(near(centre_colour(&s.doc().unwrap().doc), BLUE)); + + s.execute("edit.undo", &json!({})).unwrap(); + assert!(node(&s, new).is_none()); + assert_eq!(node(&s, id).unwrap().image_corners().unwrap(), before); + assert!(near(centre_colour(&s.doc().unwrap().doc), RED)); +} + /// Unembed into a folder keeps a distorted image's corners, in one undo step. #[test] fn unembed_to_a_folder_keeps_a_distorted_images_corners() { diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 3c9a7a84cc..1c175c03bb 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -1045,9 +1045,10 @@ fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { ("imageTrace.make", json!({})), ("object.createObjectMosaic", json!({})), ("object.mesh.create", json!({})), + // Vector art has no pixels to put between the corners. ( "file.place", - json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}), + json!({"replace": true, "name": "b.svg", "dataBase64": vectorcraft_format::base64_encode(b"")}), ), ] { let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); diff --git a/docs/mcp.md b/docs/mcp.md index 8cb939c506..ada6d14cb4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8493,9 +8493,13 @@ the corners where they are records none. Image info (`image.info`) gives a disto Info (`links.info`) gives its scale and rotation there. Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Create Object Mosaic -(`object.createObjectMosaic`) and Place with Replace (`file.place` with `replace`) of anything but a text file refuse a -distorted image with an error that names the distortion; Place with Replace does not refuse a clipping group that holds -a distorted image of a DCS file's plates. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is +(`object.createObjectMosaic`) and Place with Replace (`file.place` with `replace`) of a file that is not text, a raster +image or a DCS file refuse a distorted image with an error that names the distortion; Place with Replace does not +refuse a clipping group that holds a distorted image of a DCS file's plates. Place with Replace of a distorted image by +a raster image or a DCS file puts the new image's pixels between the old image's corners, in one undo step; the new +image's transform is the old one scaled to the new pixel size, the clipping path a PSD, PSB or DCS file names is +drawn through the corners, and each slice a PSD or PSB file brings in covers the box around its part of the pixels +where the corners put it. Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that error. Update Links (`links.update`) and Relink (`links.relink`) put the file's pixels between a distorted image's corners, without applying its Placement Options or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 75efe3bf2e..f9b09a6352 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1299,7 +1299,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links and Relink put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn, as the `.ai` writers do for an image nested 8 deep in opacity masks, symbols, live objects and pattern tiles, or in a legacy `.ai` in symbols and live objects, not counting ordinary groups and layers, and leave out an image nested deeper; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image and the placed file is not text, a raster image or a DCS file, so it does not refuse when the replaced object is a DCS file's plates); Update Links, Relink and Place with Replace of a raster image or a DCS file put the file's pixels between its corners, with the file's clipping path drawn through them, and Embed and Unembed keep them; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `links::relink_embed_and_unembed_keep_a_distorted_images_corners`, `links::unembed_to_a_folder_keeps_a_distorted_images_corners`, `links::place_with_replace_keeps_a_distorted_images_corners`, `dcs::place_with_replace_draws_the_files_clipping_path_through_a_distorted_images_corners`, `cmd::fileio::tests_psdslices::slices_placed_over_a_distorted_image_follow_its_corners`, `links::embed_reads_a_distorted_images_file_between_its_corners`, `links::relink_of_all_instances_keeps_the_corners_of_distorted_images_in_symbols`, `cmd::fileio::tests_psdread::relink_follows_the_clipping_path_of_a_distorted_psd`, `cmd::fileio::tests_psdread::unembed_keeps_the_clipping_path_of_a_distorted_psd`, `cmd::links::tests::points_past_the_horizon_are_mapped_as_a_distort_maps_them`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`, `ai_editing::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`, `legacy_ai::tests::a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). From a49f3041e552d24c422df79c52903401b54e8e64 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:27:38 -0800 Subject: [PATCH 17/20] Image Trace: Flat Logo looks up flat-area colors by cell Keeping every distinct flat-area color made each lookup scan the whole list, so an image with many slowly varying flat colors cost pixels times colors. Each class's colors now sit in cells 2 * PURE wide on each channel, and a lookup checks the pixel's cell and the 15 neighbors on the sides it lies nearer. A test compares the lookup with a scan of every stored color. --- crates/trace/src/logo/unmix.rs | 86 ++++++++++++++++++++++++++++++---- 1 file changed, 78 insertions(+), 8 deletions(-) diff --git a/crates/trace/src/logo/unmix.rs b/crates/trace/src/logo/unmix.rs index 01ef0ce2e5..59b6594c04 100644 --- a/crates/trace/src/logo/unmix.rs +++ b/crates/trace/src/logo/unmix.rs @@ -215,7 +215,7 @@ pub(crate) fn unmix(pix: &[Px], width: usize, height: usize, classes: &[[f64; 4] let flat = flat_classes(pix, &stands_for, width, height); let between = between_classes(pix, &flat, &mixed, width, height); let colors = area_colors(pix, classes, &flat, &between); - let of_class = (!colors.iter().all(Vec::is_empty)).then(|| { + let of_class = (!colors.iter().all(FlatColors::is_empty)).then(|| { pure.iter() .zip(pix) .map(|(&q, px)| q.or_else(|| (0..k).find(|&c| colors.get(c).is_some_and(|cs| near_area_color(px, cs))))) @@ -511,8 +511,8 @@ fn between_classes(pix: &[Px], flat: &[Option], mixed: &HashMap<[u32; 4], /// color), the distinct colors of its flat areas: the flat areas that /// stand for it (`flat`) and those whose mix holds it most (`between`, [`between_classes`]). Empty for /// a class whose flat areas all come within `PURE` of it. -fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between: &[[Option; 2]]) -> Vec> { - let mut colors: Vec> = vec![Vec::new(); classes.len()]; +fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between: &[[Option; 2]]) -> Vec { + let mut colors: Vec = vec![FlatColors::default(); classes.len()]; let mut off_named = vec![false; classes.len()]; let mut kept: HashSet<(usize, [u32; 4])> = HashSet::new(); for (i, px) in pix.iter().enumerate() { @@ -532,8 +532,56 @@ fn area_colors(pix: &[Px], classes: &[[f64; 4]], flat: &[Option], between } /// Whether `px` comes within [`PURE`] of one of `colors`. -fn near_area_color(px: &Px, colors: &[Px]) -> bool { - colors.iter().any(|q| distance(px, q) < PURE) +fn near_area_color(px: &Px, colors: &FlatColors) -> bool { + colors.near(px) +} + +/// The colors of one class's flat areas, kept in cells `2 * PURE` wide on each channel, so a color +/// within [`PURE`] of a pixel lies in the pixel's cell or, on each channel, the next cell on the side +/// the pixel lies nearer: 16 cells in all. +#[derive(Clone, Default)] +struct FlatColors { + cells: HashMap<[i32; 4], Vec>, +} + +impl FlatColors { + fn cell(px: &Px) -> [i32; 4] { + px.map(|v| (f64::from(v) / (2.0 * PURE)).floor() as i32) + } + + fn push(&mut self, px: Px) { + self.cells.entry(Self::cell(&px)).or_default().push(px); + } + + fn is_empty(&self) -> bool { + self.cells.is_empty() + } + + fn clear(&mut self) { + self.cells.clear(); + } + + /// Whether one of the colors lies within [`PURE`] of `px`. + fn near(&self, px: &Px) -> bool { + if self.cells.is_empty() { + return false; + } + let at = Self::cell(px); + // On each channel, -1 or +1: the neighboring cell on the side of the cell's middle the pixel lies. + let side = [0, 1, 2, 3].map(|j| { + let pos = f64::from(px[j]) / (2.0 * PURE) - f64::from(at[j]); + if pos < 0.5 { -1 } else { 1 } + }); + (0..16usize).any(|n| { + let mut key = at; + for (j, k) in key.iter_mut().enumerate() { + if (n >> j) & 1 == 1 { + *k = k.saturating_add(side[j]); + } + } + self.cells.get(&key).is_some_and(|qs| qs.iter().any(|q| distance(px, q) < PURE)) + }) + } } /// How far apart two pixels are (in 0..1 premultiplied RGBA). @@ -670,7 +718,7 @@ fn in_flat_area(pix: &[Px], width: usize, height: usize, x: usize, y: usize) -> type Weights = Vec<(usize, f32)>; /// For each class, the colors of its flat areas that lie [`PURE`] or more from it ([`area_colors`]). -type AreaColors = [Vec]; +type AreaColors = [FlatColors]; /// A mix tried for a pixel: its squared error with its penalty, the penalty, and its classes with /// their weights (the first `n`). @@ -1029,9 +1077,31 @@ mod tests { let flat = vec![Some(0); pix.len()]; let between = vec![[None; 2]; pix.len()]; let colors = area_colors(&pix, &classes, &flat, &between); - assert_eq!(colors[0].len(), 2, "{:?}", colors[0]); + assert_eq!(colors[0].cells.values().map(Vec::len).sum::(), 2); assert!(near_area_color(&level(225.0), &colors[0])); - assert!(!near_area_color(&level(225.0), &colors[0][..1])); + let mut only_222 = FlatColors::default(); + only_222.push(level(222.0)); + assert!(!near_area_color(&level(225.0), &only_222)); + } + + #[test] + fn flat_colors_find_what_a_scan_of_every_color_finds() { + let at = |r: f32, g: f32, b: f32, a: f32| [r / 255.0, g / 255.0, b / 255.0, a / 255.0]; + let stored: Vec = (0..40u8).map(|n| at(f32::from(n) * 6.3, 255.0 - f32::from(n) * 2.9, f32::from(n % 7) * 3.1, 255.0)).collect(); + let mut index = FlatColors::default(); + for &q in &stored { + index.push(q); + } + assert!(stored.iter().all(|q| index.near(q))); + for r in (0..=255u8).step_by(3) { + for g in [0.0f32, 100.0, 140.0, 200.0, 254.0] { + for b in [0.0f32, 2.0, 5.0, 9.0, 18.0] { + let px = at(f32::from(r), g, b, 255.0); + let scan = stored.iter().any(|q| distance(&px, q) < PURE); + assert_eq!(index.near(&px), scan, "{px:?}"); + } + } + } } #[test] From dfa6fb6f549d47c565854bf34c7e3ce0fe6c4437 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 05:09:36 -0800 Subject: [PATCH 18/20] Place: Replace keeps a distorted image's corners for a DCS file and a tiny image Replace of a clipped PSD file's distorted image by a DCS file now measures the image in the clip group, as it does for a raster file, so the DCS file's image takes the corners instead of losing them. The checks that the new image's transform can be inverted now use a scale-relative test (Homography::affine_is_invertible) in place of an absolute determinant limit of 1e-12. A tiny distorted image replaced by a file with many more pixels gets a valid transform with a determinant below that limit, which Replace refused before. --- crates/engine/src/cmd/fileio/tests_psdread.rs | 47 +++++++++++++++++++ crates/engine/src/cmd/place.rs | 17 +++---- crates/engine/src/tests.rs | 2 +- crates/engine/src/tests/dcs.rs | 2 +- 4 files changed, 58 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/fileio/tests_psdread.rs b/crates/engine/src/cmd/fileio/tests_psdread.rs index 37f4b132b5..1d6bd59fd1 100644 --- a/crates/engine/src/cmd/fileio/tests_psdread.rs +++ b/crates/engine/src/cmd/fileio/tests_psdread.rs @@ -602,6 +602,53 @@ fn relink_and_update_follow_the_clipping_path_of_a_linked_psd() { assert_eq!(clip_group(&s.doc().unwrap().doc, group), (squared, true, NodeId(image)), "links.update reads the clipping path again"); } +/// Place with Replace of an image changed by Perspective Distort or Free Distort by a clipped PSD +/// file with many more pixels keeps its corners when the image is tiny: the new image's transform +/// is the old one scaled down to the new pixel size, which is invertible however small it is. +#[test] +fn replacing_a_tiny_distorted_image_by_a_large_clipped_psd_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-tiny-distorted"); + let plane = vec![255u8; 2000 * 2000]; + let zero = vec![0u8; 2000 * 2000]; + let big = psd(1, 3, (2000, 2000), 8, 3, &[], &triangle_resources(), &[], &raw(&[&plane, &zero, &zero])); + let cut = write_file(&dir, "big.psd", &big); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let png = crate::tests_links::png(4, 4, [0, 0, 255]); + let r = s + .execute("file.place", &json!({"name": "a.png", "dataBase64": vectorcraft_format::base64_encode(&png), "rect": [100, 100, 0.001, 0.001]})) + .unwrap(); + let old = NodeId(r["ids"][0].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [old.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[100, 100], [100.001, 100.0001], [100.0009, 100.001], [99.9998, 100.0008]]})).unwrap(); + assert!(s.doc().unwrap().doc.node(old).unwrap().is_distorted_image(), "the old image is distorted"); + let corners = s.doc().unwrap().doc.node(old).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "replace": true})).unwrap(); + let image = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(image.is_distorted_image()); + assert_eq!(image.image_corners().unwrap(), corners); +} + +/// Place with Replace of a clipped PSD file's image changed by Perspective Distort or Free Distort +/// by a DCS file keeps the image's corners: the DCS file's image fills them. +#[test] +fn replacing_a_distorted_clipped_psd_by_a_dcs_file_keeps_its_corners() { + let dir = vectorcraft_testkit::TempDir::new("psd-replace-distorted-dcs"); + let cut = write_file(&dir, "cut.psd", &red_psd(&triangle_resources())); + let dcs = write_file(&dir, "pic.eps", &crate::tests::dcs::two_plates()); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 100, "height": 50})).unwrap(); + let r = s.execute("file.place", &json!({"path": cut, "at": [50, 25]})).unwrap(); + let (group, image) = (NodeId(r["ids"][0].as_u64().unwrap()), NodeId(r["image"].as_u64().unwrap())); + s.execute("select.set", &json!({"ids": [group.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [100, 8], [90, 50], [6, 44]]})).unwrap(); + let corners = s.doc().unwrap().doc.node(image).unwrap().image_corners().unwrap(); + let r = s.execute("file.place", &json!({"path": dcs, "replace": true})).unwrap(); + let new = s.doc().unwrap().doc.node(NodeId(r["image"].as_u64().unwrap())).unwrap().clone(); + assert!(new.is_distorted_image(), "the DCS file's image takes the corners"); + assert_eq!(new.image_corners().unwrap(), corners); +} + /// links.relink follows the clipping path of a linked PSD file for an image changed by Perspective /// Distort or Free Distort too: the new file's clipping path is mapped through the image's corners, /// a clip group of the old file's clipping path loses it when the new file names none, and a later diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 07ccb01f57..95dba28b5b 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -655,7 +655,7 @@ fn at_param(p: &Value) -> Result> { /// The transform that puts new art with the natural box `natural` where `old` is: an image's scale /// and rotation relative to its 100% size (its resolution's) and its centre are kept (with -/// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by +/// `image_xf`), also for an image alone in a clip group when the new art is a raster or DCS image, clipped by /// its file's clipping path or not (`new_image`); other objects keep their centre. fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine { let image = replace_measured(d, old, new_image); @@ -663,7 +663,7 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes))); let full = Affine::scale_non_uniform(sx, sy); let centre = full * Point::new(im.width as f64 / 2.0, im.height as f64 / 2.0); - if im.xf.determinant().abs() > 1e-12 { + if Homography::affine_is_invertible(im.xf) { return im.xf * full.inverse() * Affine::translate(centre - natural.center()); } } @@ -672,8 +672,8 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image } /// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as -/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an -/// image (`new_image`), except a DCS file's plates; else `old` itself. +/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is a +/// raster or DCS image (`new_image`), except a DCS file's plates; else `old` itself. fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node { match &old.kind { NodeKind::Group { children, clip: true } if new_image => match &children[..] { @@ -704,7 +704,7 @@ fn distorted_replace(old: &Node, art: &Art) -> Option<(Affine, [Point; 4], Homog Art::Dcs(a) => (a.xf, a.img.width, a.img.height), _ => return None, }; - if width == 0 || height == 0 || pixels.determinant().abs() <= 1e-12 { + if width == 0 || height == 0 || !Homography::affine_is_invertible(pixels) { return None; } let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width) / f64::from(width), f64::from(im.height) / f64::from(height)); @@ -725,7 +725,7 @@ fn with_corners(mut node: Node, q: [Point; 4]) -> Option { let [path, image] = &mut children[..] else { return None }; let image = Arc::make_mut(image); let NodeKind::Image(im) = &image.kind else { return None }; - if im.xf.determinant().abs() <= 1e-12 { + if !Homography::affine_is_invertible(im.xf) { return None; } // The clipping path in the image's pixels, which its transform placed on the page. @@ -905,10 +905,11 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { // art is refused. Type, and any other object it measures, is placed by the bounds of what it // replaces, so a distorted image there is not refused. let mut distorted = None; + let new_image = matches!(loaded.art, Art::Image(..) | Art::Dcs(..)); if let Some(o) = old_node && !is_text { - let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..))); + let image = replace_measured(&st.doc, o, new_image); if image.is_distorted_image() { let fit = distorted_replace(image, &loaded.art).ok_or_else(|| super::xform::distorted_image_error(PLACE, image.id))?; distorted = Some((image.id, fit)); @@ -916,7 +917,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { } let m = match (old_node, rect) { (Some(_), _) if let Some((_, (m, ..))) = distorted => m, - (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))), + (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, new_image), (None, Some(r)) => fit(natural, r), // Its artboard's bottom-left corner on the target's. (None, None) if let (Some(src), Some(to)) = (loaded.board, target) => Affine::translate((to.x0 - src.x0, to.y1 - src.y1)), diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index bc6b04b0dc..b6616765ed 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -49,7 +49,7 @@ mod css; mod curvature_circle; mod cut; mod dashalign; -mod dcs; +pub(super) mod dcs; mod delete_keeps_joined; mod distort; mod docsetup; diff --git a/crates/engine/src/tests/dcs.rs b/crates/engine/src/tests/dcs.rs index 32dd882f32..34bfe7a7bc 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -56,7 +56,7 @@ fn single_file(plates: &[(&str, String)], extra: &str) -> Vec { } /// Cyan solid on the top row, PANTONE 185 C at 50% on the left column. -fn two_plates() -> Vec { +pub(crate) fn two_plates() -> Vec { single_file( &[("Cyan", plate_eps([0, 0, 255, 255])), ("PANTONE 185 C", plate_eps([127, 255, 127, 255]))], "%%DocumentCustomColors: (PANTONE 185 C)\n%%CMYKCustomColor: 0 .91 .76 0 (PANTONE 185 C)\n", From a7e5a586614f31d01e49f8ac0b5f99832b7f7300 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 18:01:08 -0800 Subject: [PATCH 19/20] 3D: length sliders show pt, or px in a pixels document Extrude & Bevel's Depth and bevel Width and Height, and Revolve's Offset, showed px in a points document. The classic Extrude & Bevel and Revolve rows and the Map Art X and Y rows showed the document's unit after a number of points. These sliders show the number of points they hold, so each now shows pt, or px in a pixels document, through one rule (three_d_classic::length_unit). --- crates/ui-egui/src/dialogs/revolve.rs | 5 ++-- crates/ui-egui/src/dialogs/revolve/tests.rs | 30 +++++++++++++++++++ crates/ui-egui/src/dialogs/three_d_classic.rs | 10 +++++-- 3 files changed, 40 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 6eab0d5404..a3acab8b0b 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -194,11 +194,12 @@ impl Rows<'_> { self.range(key, label, range, 1, UnitKind::Percent) } - /// A length in points, shown in the general unit. + /// A length in points, its unit shown as [`length_unit`](super::three_d_classic::length_unit) says. fn length(&self, key: &str, label: &'static str, range: (f64, f64)) -> Param { // Stored in points; a pixel is a point, as the rulers count it. let lengths = LengthUnits::new(UnitKind::Points, crate::canvas::rulers::unit_kind(self.unit), 72.0); - self.range(key, label, range, 1, UnitKind::Pixels).length(crate::fields::bare_points(lengths, self.bare_points)) + let shown = super::three_d_classic::length_unit(self.unit); + self.range(key, label, range, 1, shown).length(crate::fields::bare_points(lengths, self.bare_points)) } fn flag(&self, key: &str, label: &'static str) -> Param { diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index 6b73aed5f9..e3d6fca91d 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -494,6 +494,36 @@ fn the_bevel_repeat_and_the_revolve_segments_show_no_unit() { assert_eq!(unit(EXTRUDE, "object", "taper"), Some(Some(UnitKind::Percent))); } +/// The depth, bevel and offset rows of Extrude & Bevel and Revolve, classic ones included, are lengths in points: their +/// sliders show "pt" in a points document, "px" in a pixels one, and points in a document of any other unit. +#[test] +fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { + use craft::ui::patterns::form_dialogs::DialogFields; + use craft::ui::runtime::env::UnitKind; + use vectorcraft_doc::Unit; + let app = VectorcraftApp::new(Session::new(), crate::Services::default()); + let unit = |general: Unit, effect: &str, page: &str, key: &str| { + let mut data = super::super::three_d::data(&app, Some(effect), &serde_json::Map::new()); + data.unit = general; + let mut fields = DialogFields::new(); + fields.set("__page", FieldValue::Text(page.into())); + super::params(&data, &fields, super::Place::Dialog).into_iter().find(|p| p.key == key).map(|p| p.unit) + }; + let mut checked = 0; + for (general, shown) in [(Unit::Points, UnitKind::Points), (Unit::Pixels, UnitKind::Pixels), (Unit::Millimeters, UnitKind::Points)] { + for key in ["depth", "bevelWidth", "bevelHeight"] { + assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}"); + checked += 1; + } + let others = [(REVOLVE, "rotation", "offset"), (CLASSIC_EXTRUDE, "object", "depth"), (CLASSIC_EXTRUDE, "object", "bevelHeight"), (CLASSIC_REVOLVE, "object", "offset")]; + for (effect, page, key) in others { + assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}"); + checked += 1; + } + } + assert_eq!(checked, 21); +} + #[test] fn reset_all_keeps_map_art_and_its_options() { let mut h = drawn(SQUARE, CLASSIC_EXTRUDE); diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index 8c9f26bb1e..f461b3cfe2 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -50,9 +50,13 @@ const MAP_SYMBOL: &str = "mapSymbol"; /// The Map Art page's rows of the shown surface's map: views of `mapArt`, never effect parameters. pub(super) const MAP_ROWS: [&str; 6] = [MAP_SYMBOL, MAP_KEYS[0], MAP_KEYS[1], MAP_KEYS[2], MAP_KEYS[3], MAP_KEYS[4]]; -/// The unit of the general-unit length rows. -fn length_unit(unit: Unit) -> UnitKind { - crate::canvas::rulers::unit_kind(unit) +/// The unit shown after a 3D length row, whose slider shows the number of points it holds: the general `unit` when +/// that counts the same number (points, or pixels at 72 per inch), and points otherwise. +pub(super) fn length_unit(unit: Unit) -> UnitKind { + match crate::canvas::rulers::unit_kind(unit) { + UnitKind::Pixels => UnitKind::Pixels, + _ => UnitKind::Points, + } } /// Where the rows show: the 3D and Materials panel marks its fields with `__panel`. From 10ae2973b0a7642d97167522f239cfc747ca6524 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 18:15:24 -0800 Subject: [PATCH 20/20] 3D: format the length-unit test --- crates/ui-egui/src/dialogs/revolve/tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/revolve/tests.rs b/crates/ui-egui/src/dialogs/revolve/tests.rs index e3d6fca91d..ceb96018f7 100644 --- a/crates/ui-egui/src/dialogs/revolve/tests.rs +++ b/crates/ui-egui/src/dialogs/revolve/tests.rs @@ -515,7 +515,12 @@ fn the_3d_length_rows_show_the_unit_of_the_number_they_hold() { assert_eq!(unit(general, EXTRUDE, "object", key), Some(Some(shown)), "{key} in {general:?}"); checked += 1; } - let others = [(REVOLVE, "rotation", "offset"), (CLASSIC_EXTRUDE, "object", "depth"), (CLASSIC_EXTRUDE, "object", "bevelHeight"), (CLASSIC_REVOLVE, "object", "offset")]; + let others = [ + (REVOLVE, "rotation", "offset"), + (CLASSIC_EXTRUDE, "object", "depth"), + (CLASSIC_EXTRUDE, "object", "bevelHeight"), + (CLASSIC_REVOLVE, "object", "offset"), + ]; for (effect, page, key) in others { assert_eq!(unit(general, effect, page, key), Some(Some(shown)), "{effect} {key} in {general:?}"); checked += 1;