diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index b9fd0b98e6..009fc4efd8 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -855,7 +855,7 @@ pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles, s /// write a resolution and a number of bytes. pub use docinfo::{CATEGORIES, OBJECT_LABELS, byte_size, ppi_number}; 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 d895c3969f..194df59e51 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|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (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; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; 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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (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|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, or the text of a control without a name)}] (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; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, or fourth after a third that is not an object, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes and windows throw that they are not available yet); new Window and add also take a resource string such as \"dialog { g: Group { b: Button { text: 'OK' } } }\" in place of the type, which adds each control it lists through add and sets it and each other value as the property of its name (properties gives the creation properties and a list's items its item texts; at most 1 MiB nested 64 deep, and a malformed one throws a SyntaxError); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; the other documented event types throw that they are not available yet, and an unknown type throws that there is no such event), a removed control leaves the dialog (no parent or window, and its events no longer reach the containers it was in), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws while a dialog is showing, and in the app so do a show() in a handler that notify runs and the alert, confirm, prompt and file dialogs a handler calls (a run with nobody to ask shows a dialog from a handler that notify runs while none is showing, and takes a window answer for it), and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; 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; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns 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 (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (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 ), @@ -195,6 +195,7 @@ fn prepare(s: &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; @@ -241,6 +242,7 @@ fn prepare(s: &Session, p: &Value) -> Result { fuel, locale, answers, + actions, }) } @@ -442,6 +444,7 @@ impl Session { fuel, locale, answers: vec![], + actions: vec![], }; let runs = self.script_runs; self.script_start(request).map_err(|e| { diff --git a/crates/engine/src/script/actions.rs b/crates/engine/src/script/actions.rs new file mode 100644 index 0000000000..2abb290cf7 --- /dev/null +++ b/crates/engine/src/script/actions.rs @@ -0,0 +1,354 @@ +//! `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, 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. + +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, 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 +/// 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" => { + // 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")) }; + 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, artboard)); + } + } + _ if id == "command.batch" => return Err(format!("{at}.params.commands must be a list")), + _ => 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")); + } + } + 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, artboard: Option) -> Step { + let bytes = serde_json::to_vec(¶ms).map_or(0, |b| b.len() as u64); + Step { place, id, params, bytes, artboard } +} + +/// `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 { + 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 info = super::dom::returns("undefined", &[("action", "string"), ("set", "string"), ("dialogs", "boolean")]); + let mut members = vec![("doScript".to_string(), HostMember::Method(play), info)]; + 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 { + 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 `{}`, which a script cannot run", shown(&id)) + })); + } + } + 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 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); + 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) +} + +/// 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 +/// 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). 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.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"; + 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() }; + 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/dom.rs b/crates/engine/src/script/dom.rs index db5786878f..168f033166 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -293,7 +293,7 @@ fn method(link: &Link, f: Member) -> HostMember { } /// A member of a class with what `reflect` tells of it. -type Described = (String, HostMember, MemberInfo); +pub(super) type Described = (String, HostMember, MemberInfo); /// A property's or a method's result's type for `reflect`. fn typed(data_type: &str) -> MemberInfo { @@ -301,7 +301,7 @@ fn typed(data_type: &str) -> MemberInfo { } /// A method's result's type and its arguments' names and types, for `reflect`. -fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { +pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { let arguments = arguments.iter().map(|(n, t)| ArgInfo { name: (*n).into(), data_type: (*t).into(), ..ArgInfo::default() }).collect(); MemberInfo { arguments, ..typed(data_type) } } @@ -309,7 +309,7 @@ fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo { /// A member the help pages list that is not available yet: reading or assigning it throws, after /// the check that a document, page item or text range `this` is still there. `hasOwnProperty` is /// false for it, so a script that checks for the member first skips it, and `reflect` leaves it out. -fn later(link: &Link, class: &'static str, name: &'static str) -> Described { +pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described { let message = format!("{class}.{name} is not available yet"); let l = link.clone(); let f: HostFunction = Rc::new(move |a: Vec| { @@ -571,7 +571,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) } @@ -2672,6 +2672,7 @@ fn classes(link: &Link) -> Vec { ]); application.push(("textFonts".into(), text::app_text_fonts(l), MemberInfo { collection: true, ..typed("TextFonts") })); 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 |_: Vec| { diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index bc6ae00250..19ee454c87 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; @@ -206,6 +207,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! { @@ -806,6 +809,15 @@ 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)>, + /// 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)>, /// The documents open when the run began as the person last left them, each with its own file /// and the file it was read from ([`crate::DocState::as_person_left`], /// [`crate::cmd::links::LinkBase::of_files`]), until the run's first command takes the files @@ -2063,6 +2075,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)); @@ -2182,6 +2197,9 @@ impl Session { dollar: dollar::RunState::new(&request.locale), args: RefCell::new((Data::Undefined, 0)), dom: dom::State::new(heap_bytes), + actions: request.actions, + active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(), + artboard_picks, run_docs: RefCell::new( self.docs .iter() diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2f3c5556e7..6182550bbf 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -175,6 +175,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..1432b8671b --- /dev/null +++ b/crates/engine/src/tests/script_actions.rs @@ -0,0 +1,396 @@ +//! `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); + // 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] +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"); +} + +/// 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] +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 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"); + 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 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(); + 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!({})); +} + +/// 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/src/tests/script_folder.rs b/crates/engine/src/tests/script_folder.rs index 7d8f06700e..dc9749fb6c 100644 --- a/crates/engine/src/tests/script_folder.rs +++ b/crates/engine/src/tests/script_folder.rs @@ -376,6 +376,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/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 0b20de0e23..0eeae87282 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -89,8 +89,9 @@ const INSIDE: &[(&str, &str)] = &[ ("Application.", "prototype"), ( "Application.prototype.", - "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents executeMenuCommand \ - getIsFileOpen redraw selection selection= textFonts toString typename", + "activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \ + executeMenuCommand getIsFileOpen loadAction loadAction= redraw selection selection= textFonts toString typename \ + unloadAction unloadAction=", ), ("DocumentPreset.", "prototype"), ( diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index 53c9664aec..89ccb1ae9c 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -166,6 +166,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 c44c6dc8ba..8694052a3a 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -58,7 +58,7 @@ pub use playback::{ deserialize_playback, play, play_action, play_at, playback_drawn, playback_held, playback_options, playback_shown, tick_playback, waiting_at_stop, }; -pub(crate) use playback::{KnownCommands, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands}; +pub(crate) use playback::{KnownCommands, add_script_actions, has_stop, is_ui_step, shown_text, step_place, stop_params, unknown_commands}; pub use recording::{START_RECORDING, STOP_RECORDING, record, stop}; pub(crate) use recording::{after_journaled_edit, after_recorded_command, before_recorded_command}; diff --git a/crates/ui-egui/src/panels/actions/playback.rs b/crates/ui-egui/src/panels/actions/playback.rs index 50cab383e2..bff0bd1d4d 100644 --- a/crates/ui-egui/src/panels/actions/playback.rs +++ b/crates/ui-egui/src/panels/actions/playback.rs @@ -39,6 +39,72 @@ fn playback_steps(action: &Action) -> Vec { .collect() } +/// 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 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; + } + let list = &app.ui.actions; + let (mut held, mut steps, mut bytes) = (Vec::new(), 0usize, 2usize); + for set in list.sets() { + for a in model::members(list, set).into_iter().filter_map(|i| list.action(i)) { + if held.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 playback_steps(a) { + 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(|step| step.command != "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 one = Value::Array(vec![json!({"set": set, "name": a.name, "steps": played})]); + let Ok(parsed) = parse(Some(&one)) else { continue }; + let count = parsed.first().map_or(0, 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 { + held.append(&mut one); + } + } + } + p.insert("actions".into(), Value::Array(held)); +} + /// The steps of `action` whose command `known` does not hold, in order, as (step index, the index /// of the command in a `command.batch` step, command id). A `command.batch` step's own commands are /// checked one by one, as playback runs them ([`included_commands`]); a command of one with no diff --git a/crates/ui-egui/src/panels/actions/tests_playback.rs b/crates/ui-egui/src/panels/actions/tests_playback.rs index b6db1c5941..f566eb22fc 100644 --- a/crates/ui-egui/src/panels/actions/tests_playback.rs +++ b/crates/ui-egui/src/panels/actions/tests_playback.rs @@ -637,6 +637,79 @@ fn an_error_counts_excluded_steps() { assert_eq!(x(&app), 0.0, "the failing batch changes nothing"); } +/// 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", json!({"x": x, "y": 10, "width": 10, "height": 10})); + let bad = json!({"command": "object.move", "params": {"ids": [999_999], "dx": 1, "dy": 1}}); + let batch = json!({"commands": [{"command": "select.none"}, bad]}); + let actions = vec![ + action("Draw", &[rect(0), rect(20), rect(40)]), + action("Odd", &[rect(0), ("select.none", json!(5))]), + action("Batched", &[("select.none", json!({})), ("command.batch", batch)]), + ]; + push_set(&mut app, "Mine", actions); + let draw = model::members(&app.ui.actions, "Mine")[0]; + app.ui.actions.set_step(draw, 1, false).unwrap(); + 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 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] +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 = json!({"commands": [align]}); + push_set(&mut app, "Mine", vec![action("Align", &[("command.batch", batch)]), action("Fit", &[("artboard.fitToSelection", json!({}))])]); + 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"); +} + /// A step of a recorded `command.batch` that fails is named by the batch's place in the action /// and its own command. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 36ec1542bb..89db258833 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3111,6 +3111,29 @@ other files through `$`: `importVariables` and `exportVariables` take a `File`, not a path, which must be a file the script may read, or write, through its `File` objects; the files of the open documents do not count. A value that changes nothing runs no command. +- `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 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. 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. + 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. - `PageItem.tags` and `Document.tags` are `Tags` collections (https://ai-scripting.docsforadobe.dev/jsobjref/Tags/) with `typename`, `length`, `parent`, `[i]`, `index(key)`, `getByName(name)`, `add()` and `removeAll()`, and each `Tag` (https://ai-scripting.docsforadobe.dev/jsobjref/Tag/) has `typename`, `name`, `value`, `parent` (its page diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f3a87498d4..e270fa8436 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1122,6 +1122,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.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 warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.