diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 7a2676f300..ba5451207a 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, else its text)}] (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, windows and resource strings throw that they are not available yet); 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, 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, else its text)}] (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, 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", always, run ), diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index e572d01f64..4c68a27fa4 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -80,6 +80,19 @@ fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { assert_eq!(closed["log"], json!([0])); } +#[test] +fn a_dialog_from_a_resource_specification_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = "var w = new Window(\"dialog { text: 'Settings', \ + g: Group { label: StaticText { text: 'Name:' }, field: EditText { text: 'first', properties: {name: 'field'} } }, \ + ok: Button { text: 'OK' } }\"); vc.log([w.show(), w.g.field.text]);"; + let steps = json!([{"control": "field", "event": "change", "value": "typed"}, {"control": "OK", "event": "click"}]); + let r = headless(&mut s, source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "typed"]]), "{r}"); + assert_eq!(r["dialogs"][0]["title"], "Settings"); + assert_eq!(r["dialogs"][0]["controls"], 4); +} + #[test] fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { let mut s = one_doc(); diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c953004550..6958f93b10 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -68,6 +68,7 @@ mod regexp; mod regexp_builtins; mod regexp_vm; pub mod scriptui; +mod scriptui_resource; mod string_builtins; mod token; mod value; diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index febbcea099..aca94d40dc 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -3,8 +3,15 @@ //! drawing a host does ([`crate::Realm::define_script_ui`]). //! //! `new Window("dialog"[, title, bounds, properties])` makes a dialog, with or without `new`. A -//! window of type `palette` or `window`, and a resource specification in place of the type, throw -//! an `Error` that says they are not available yet. `add(type[, bounds, text, properties])` adds a +//! window of type `palette` or `window` throws an `Error` that says it is not available yet. +//! `new Window` and `add` also take a resource specification in place of the type, as the help +//! page +//! describes it (read by [`crate::scriptui_resource`]), and then read no other argument: the +//! window or control is made with the creation properties given in `properties`. Then, in order, +//! each control listed in its braces is added to it through `add`, with `add`'s limits, and +//! assigned to the container's property of that name, a list's `items` gives its item texts as +//! `add`'s third argument does, and each other value is assigned to the property of its name. A +//! malformed specification throws a `SyntaxError`. `add(type[, bounds, text, properties])` adds a //! control to a dialog, a `group` or a `panel` and returns it: `statictext`, `edittext`, `button`, //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). @@ -62,6 +69,7 @@ use crate::builtins::{arg, constructor, data, method, native, pausable_method}; use crate::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; use crate::host::Data; use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::scriptui_resource::{self, Fault, Res, Spec}; use crate::value::{Value, index_key}; /// The most controls a dialog holds, its groups and panels included. @@ -422,10 +430,8 @@ fn dimension(i: &mut Interp, width: f64, height: f64) -> JsResult { /// `new Window(type[, title, bounds, properties])`. fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { let kind = i.to_str(&arg(args, 0))?.to_rust_string(); - if kind.contains('{') { - return Err(error(i, "Window: resource specifications are not available yet; build the dialog with add()")); - } - let lower = kind.to_lowercase(); + let spec = if kind.contains('{') { Some(resource(i, &kind, "Window")?) } else { None }; + let lower = spec.as_ref().map_or(kind.as_str(), |s| s.class.as_str()).to_lowercase(); if lower == "palette" || lower == "window" { return Err(error(i, &format!("Window: a window of type {lower} is not available yet; use dialog"))); } @@ -435,15 +441,133 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let creation = creation_properties(i, spec)?; + new_element(i, proto, "dialog", None, None, 0, [&Value::Undefined, &Value::Undefined, &creation])? + } + None => new_element(i, proto, "dialog", None, None, 0, [&arg(args, 2), &arg(args, 1), &arg(args, 3)])?, + }; set_slot(i, o, COUNT, Value::Number(0.0))?; set_slot(i, o, ITEM_COUNT, Value::Number(0.0))?; + if let Some(spec) = &spec { + apply_resource(i, o, spec, false)?; + } Ok(Value::Object(o)) })(); i.temp_roots.truncate(mark); r } +/// The resource specification `text` given to `what`, or a `SyntaxError` or `RangeError` naming +/// `what`. +fn resource(i: &mut Interp, text: &str, what: &str) -> JsResult { + match scriptui_resource::parse(text) { + Ok(spec) => Ok(spec), + Err(Fault::Syntax(m)) => Err(i.throw(ErrorType::Syntax, &format!("{what}: {m}"))), + Err(Fault::Limit(m)) => Err(range(i, &format!("{what}: {m}"))), + } +} + +/// The value of a resource specification's `properties`, its creation properties, kept in the +/// temporary roots; `undefined` when it has none. +fn creation_properties(i: &mut Interp, spec: &Spec) -> JsResult { + let Some((_, v)) = spec.props.iter().rev().find(|(name, _)| name == "properties") else { return Ok(Value::Undefined) }; + if matches!(v, Res::Control(_)) { + return Err(i.type_error("properties: give the creation properties as an object")); + } + let v = resource_value(i, v)?; + i.temp_roots.push(v.clone()); + Ok(v) +} + +/// A new value for the resource value `v`, built in the temporary roots. +fn resource_value(i: &mut Interp, v: &Res) -> JsResult { + Ok(match v { + Res::Null => Value::Null, + Res::Bool(b) => Value::Bool(*b), + Res::Number(n) => Value::Number(*n), + Res::String(s) => Value::str(s), + Res::Array(items) => { + let mut values = Vec::with_capacity(items.len()); + for item in items { + let v = resource_value(i, item)?; + i.temp_roots.push(v.clone()); + values.push(v); + } + let a = list(i, &values, true)?; + i.temp_roots.push(Value::Object(a)); + Value::Object(a) + } + Res::Object(props) => { + i.reserve_heap(OBJECT_BYTES)?; + let o = i.new_object(); + i.temp_roots.push(Value::Object(o)); + for (name, v) in props { + let v = resource_value(i, v)?; + set_open(i, o, name, v)?; + } + Value::Object(o) + } + Res::Control(_) => return Err(i.type_error("a control is not a value")), + }) +} + +/// Adds the control `spec` describes to the container `parent`, as `add` does, with the controls +/// and properties it lists. +fn add_resource(i: &mut Interp, parent: ObjId, spec: &Spec) -> JsResult { + let creation = creation_properties(i, spec)?; + // `add` reads a slider's and a progress bar's later arguments as numbers; their creation + // properties are set after `add` makes them. + let class = spec.class.to_lowercase(); + let numeric = matches!(class.as_str(), "slider" | "progressbar"); + // A list's `items` gives its item texts, as `add`'s third argument does. + let list_kind = matches!(class.as_str(), "dropdownlist" | "listbox"); + let items = match spec.props.iter().rev().find(|(name, _)| name == "items") { + Some((_, v)) if list_kind => { + let v = resource_value(i, v)?; + i.temp_roots.push(v.clone()); + v + } + _ => Value::Undefined, + }; + let args = if numeric { vec![Value::str(&spec.class)] } else { vec![Value::str(&spec.class), Value::Undefined, items, creation.clone()] }; + let c = add(i, Value::Object(parent), &args, false)?; + i.temp_roots.push(c.clone()); + let Some(o) = c.as_object() else { return Err(Abrupt::Internal("add gave no control".into())) }; + if numeric && creation.as_object().is_some() { + set_open(i, o, "properties", creation.clone())?; + let name = i.get_value(&creation, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + let alignment = i.get_value(&creation, &key("alignment"))?; + if !matches!(alignment, Value::Undefined) { + set_open(i, o, "alignment", alignment)?; + } + } + apply_resource(i, o, spec, list_kind)?; + Ok(c) +} + +/// Sets the properties `spec` lists on the element `o`, in order, leaving out `properties`, and +/// `items` for a list (`list`): a control is added to `o` and assigned to `o`'s property of that +/// name, and any other value is assigned to the property of its name. +fn apply_resource(i: &mut Interp, o: ObjId, spec: &Spec, list: bool) -> JsResult<()> { + for (name, v) in &spec.props { + if name == "properties" || (list && name == "items") { + continue; + } + let value = match v { + Res::Control(child) => add_resource(i, o, child)?, + v => resource_value(i, v)?, + }; + i.temp_roots.push(value.clone()); + i.put(o, key(name), value, true)?; + } + Ok(()) +} + fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { let n = i.to_number(v)?; if !n.is_finite() { @@ -467,7 +591,11 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Err(error(i, &format!("add: a {kind} holds no controls"))); } if ty.contains('{') { - return Err(error(i, "add: resource specifications are not available yet; add each control by its type")); + let spec = resource(i, &ty, "add")?; + let mark = i.temp_roots.len(); + let r = add_resource(i, o, &spec); + i.temp_roots.truncate(mark); + return r; } let ty = ty.to_lowercase(); if LATER.contains(&ty.as_str()) { diff --git a/crates/js/src/scriptui_resource.rs b/crates/js/src/scriptui_resource.rs new file mode 100644 index 0000000000..8789777518 --- /dev/null +++ b/crates/js/src/scriptui_resource.rs @@ -0,0 +1,336 @@ +//! The reader of ScriptUI resource specifications, as the help page +//! describes +//! them: a type, then braces holding property definitions, where a property whose value is a +//! control class followed by braces defines a control the container holds. +//! +//! `[name:] Type { name: value, ... }` is read into a [`Spec`]. A value is `null`, `true`, `false`, +//! a string in single or double quotes, a number, an inline array `[value, ...]`, an inline object +//! `{name: value, ...}`, or, directly in a window's or control's braces, a control `Class { ... }`. +//! A name is an identifier or a quoted string. The commas between properties may be left out, and +//! a comma may end a list. A string longer than [`MAX_BYTES`] or values nested more than +//! [`MAX_NESTING`] deep are refused; these are VectorCraft's own limits. + +/// The most bytes (UTF-8) of a resource specification. +pub const MAX_BYTES: usize = 1 << 20; +/// How deeply braces and brackets nest in a resource specification. +pub const MAX_NESTING: usize = 64; + +/// A value in a resource specification. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Res { + Null, + Bool(bool), + Number(f64), + String(String), + Array(Vec), + Object(Vec<(String, Res)>), + Control(Spec), +} + +/// A window or control: its class as written and its properties in order. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Spec { + pub(crate) class: String, + pub(crate) props: Vec<(String, Res)>, +} + +/// Why a resource specification could not be read. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Fault { + /// The text is not a resource specification; the message says where. + Syntax(String), + /// The text passes [`MAX_BYTES`] or [`MAX_NESTING`]. + Limit(String), +} + +/// Reads `text`, which is `[name:] Type { ... }` with nothing after it but white space. +pub(crate) fn parse(text: &str) -> Result { + if text.len() > MAX_BYTES { + return Err(Fault::Limit(format!("a resource specification is longer than {} MiB", MAX_BYTES >> 20))); + } + let mut r = Reader { chars: text.chars().collect(), at: 0 }; + r.space(); + let quoted = matches!(r.peek(), Some('\'' | '"')); + let first = r.name()?; + r.space(); + let class = if r.eat(':') { + r.space(); + r.ident()? + } else if quoted { + return Err(r.expected(": after the name")); + } else { + first + }; + r.space(); + if !r.eat('{') { + return Err(r.expected("{ after the type")); + } + let props = r.props(true, 1)?; + r.space(); + if r.at < r.chars.len() { + return Err(r.expected("the end of the resource specification")); + } + Ok(Spec { class, props }) +} + +struct Reader { + chars: Vec, + at: usize, +} + +impl Reader { + fn peek(&self) -> Option { + self.chars.get(self.at).copied() + } + + fn eat(&mut self, c: char) -> bool { + if self.peek() == Some(c) { + self.at += 1; + true + } else { + false + } + } + + fn space(&mut self) { + while self.peek().is_some_and(char::is_whitespace) { + self.at += 1; + } + } + + fn expected(&self, what: &str) -> Fault { + match self.peek() { + Some(c) => Fault::Syntax(format!("expected {what} at character {}, found {c:?}", self.at + 1)), + None => Fault::Syntax(format!("expected {what} at the end of the resource specification")), + } + } + + fn ident(&mut self) -> Result { + let start = self.at; + while self.peek().is_some_and(|c| c.is_alphanumeric() || c == '_' || c == '$') { + self.at += 1; + } + if self.at == start || self.chars[start].is_ascii_digit() { + self.at = start; + return Err(self.expected("a name")); + } + Ok(self.chars[start..self.at].iter().collect()) + } + + /// A property name: an identifier or a quoted string. + fn name(&mut self) -> Result { + match self.peek() { + Some('\'' | '"') => self.string(), + _ => self.ident(), + } + } + + /// The properties after an opening brace, up to and including its closing brace. Controls are + /// allowed among them when `controls`. + fn props(&mut self, controls: bool, depth: usize) -> Result, Fault> { + if depth > MAX_NESTING { + return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep"))); + } + let mut props = Vec::new(); + loop { + self.space(); + if self.eat('}') { + return Ok(props); + } + let name = self.name()?; + self.space(); + if !self.eat(':') { + return Err(self.expected(": after a property name")); + } + self.space(); + let value = self.value(controls, depth)?; + props.push((name, value)); + self.space(); + self.eat(','); + } + } + + fn value(&mut self, controls: bool, depth: usize) -> Result { + match self.peek() { + Some('\'' | '"') => Ok(Res::String(self.string()?)), + Some('[') => { + self.at += 1; + if depth + 1 > MAX_NESTING { + return Err(Fault::Limit(format!("a resource specification nests more than {MAX_NESTING} deep"))); + } + let mut items = Vec::new(); + loop { + self.space(); + if self.eat(']') { + return Ok(Res::Array(items)); + } + items.push(self.value(false, depth + 1)?); + self.space(); + if !self.eat(',') && self.peek() != Some(']') { + return Err(self.expected(", or ] in an array")); + } + } + } + Some('{') => { + self.at += 1; + Ok(Res::Object(self.props(false, depth + 1)?)) + } + Some(c) if c.is_ascii_digit() || matches!(c, '-' | '+' | '.') => self.number(), + Some(_) => { + let start = self.at; + let word = self.ident()?; + match word.as_str() { + "null" => return Ok(Res::Null), + "true" => return Ok(Res::Bool(true)), + "false" => return Ok(Res::Bool(false)), + _ => {} + } + self.space(); + if self.peek() != Some('{') { + self.at = start; + return Err(self.expected("a value")); + } + if !controls { + self.at = start; + return Err(self.expected("a value (a control can only be a property of a window or a container)")); + } + self.at += 1; + Ok(Res::Control(Spec { class: word, props: self.props(true, depth + 1)? })) + } + None => Err(self.expected("a value")), + } + } + + fn number(&mut self) -> Result { + let start = self.at; + while self.peek().is_some_and(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '+' | '.')) { + self.at += 1; + } + let text: String = self.chars[start..self.at].iter().collect(); + let plain = text.strip_prefix(['-', '+']).unwrap_or(&text); + // Rust also reads words such as inf and nan, which are not numbers here. + let n = if plain.starts_with(|c: char| c.is_ascii_digit() || c == '.') { text.parse::().ok() } else { None }; + match n { + Some(n) if n.is_finite() => Ok(Res::Number(n)), + _ => { + self.at = start; + Err(self.expected("a number")) + } + } + } + + fn string(&mut self) -> Result { + let Some(quote) = self.peek() else { return Err(self.expected("a string")) }; + let start = self.at; + self.at += 1; + let mut s = String::new(); + loop { + let Some(c) = self.peek() else { + self.at = start; + return Err(Fault::Syntax(format!("the string at character {} has no closing quote", start + 1))); + }; + self.at += 1; + if c == quote { + return Ok(s); + } + if c != '\\' { + s.push(c); + continue; + } + let Some(e) = self.peek() else { continue }; + self.at += 1; + match e { + 'n' => s.push('\n'), + 't' => s.push('\t'), + 'r' => s.push('\r'), + 'b' => s.push('\u{8}'), + 'f' => s.push('\u{c}'), + 'v' => s.push('\u{b}'), + '0' => s.push('\0'), + '\n' => {} + 'u' | 'x' => { + let digits = if e == 'u' { 4 } else { 2 }; + let hex: String = self.chars.iter().skip(self.at).take(digits).collect(); + match u32::from_str_radix(&hex, 16).ok().filter(|_| hex.len() == digits).and_then(char::from_u32) { + Some(c) => { + s.push(c); + self.at += digits; + } + None => return Err(Fault::Syntax(format!("the escape at character {} is not valid", self.at - 1))), + } + } + e => s.push(e), + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(class: &str, props: Vec<(&str, Res)>) -> Spec { + Spec { class: class.into(), props: props.into_iter().map(|(k, v)| (k.into(), v)).collect() } + } + + #[test] + fn a_resource_specification_reads_its_controls_and_values() { + let got = parse( + "p: Panel { text: 'Messages', alignChildren: ['right', \"top\"], \ + g: Group { st: StaticText { text: 'a\\'b' } } \ + e: EditText { properties: {multiline: true, name: null}, characters: -3.5e1, }, }", + ); + let want = spec( + "Panel", + vec![ + ("text", Res::String("Messages".into())), + ("alignChildren", Res::Array(vec![Res::String("right".into()), Res::String("top".into())])), + ("g", Res::Control(spec("Group", vec![("st", Res::Control(spec("StaticText", vec![("text", Res::String("a'b".into()))])))]))), + ( + "e", + Res::Control(spec( + "EditText", + vec![ + ("properties", Res::Object(vec![("multiline".into(), Res::Bool(true)), ("name".into(), Res::Null)])), + ("characters", Res::Number(-35.0)), + ], + )), + ), + ], + ); + assert_eq!(got, Ok(want)); + assert_eq!(parse(" dialog{} "), Ok(spec("dialog", vec![]))); + } + + #[test] + fn a_malformed_resource_specification_is_a_syntax_fault() { + for text in [ + "dialog", + "dialog {", + "dialog { b: }", + "dialog { b: Button { } } x", + "dialog { b Button {} }", + "dialog { t: 'open }", + "dialog { n: inf }", + "dialog { n: 1.2.3 }", + "dialog { a: [1 2] }", + "dialog { o: { b: Button {} } }", + "dialog { a: [Button {}] }", + "dialog { v: orange }", + "dialog { t: '\\u12' }", + "{ }", + ] { + assert!(matches!(parse(text), Err(Fault::Syntax(_))), "{text}: {:?}", parse(text)); + } + } + + #[test] + fn a_resource_specification_past_the_limits_is_refused() { + let deep = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING), "]".repeat(MAX_NESTING)); + assert!(matches!(parse(&deep), Err(Fault::Limit(_))), "{:?}", parse(&deep)); + let fits = format!("dialog {{ a: {}1{} }}", "[".repeat(MAX_NESTING - 1), "]".repeat(MAX_NESTING - 1)); + assert!(parse(&fits).is_ok()); + let long = format!("dialog {{ t: '{}' }}", "x".repeat(MAX_BYTES)); + assert!(matches!(parse(&long), Err(Fault::Limit(_)))); + } +} diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 263ae48f8f..42195d7baf 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -233,7 +233,8 @@ fn a_dialog_can_be_shown_again_after_it_closed() { fn types_that_are_not_available_yet_throw_errors_that_say_so() { for (source, want) in [ ("new Window('palette')", "Window: a window of type palette is not available yet; use dialog"), - ("new Window('dialog { b: Button {} }')", "Window: resource specifications are not available yet; build the dialog with add()"), + ("new Window('palette { b: Button {} }')", "Window: a window of type palette is not available yet; use dialog"), + ("new Window('dialog').add('p: TabbedPanel {}')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('tabbedpanel')", "add: the control type tabbedpanel is not available yet"), ("new Window('dialog').add('wobble')", "add: there is no control type wobble"), ("new Window('dialog').add('button').add('button')", "add: a button holds no controls"), @@ -248,6 +249,119 @@ fn types_that_are_not_available_yet_throw_errors_that_say_so() { } } +/// A dialog built from a resource specification: 0 is the dialog, 1 the panel, 2 its group, 3 the +/// static text, 4 the edit field, 5 the button group, 6 OK and 7 Cancel. +const RESOURCE_FORM: &str = r#" + var w = new Window("dialog { text: 'Form', ignored: 1, \ + msg: Panel { orientation: 'column', alignChildren: ['right', 'top'], text: 'Messages', \ + title: Group { st: StaticText { text: 'Title:' }, et: EditText { text: 'Sample', characters: 35 } } \ + } \ + buttons: Group { \ + ok: Button { text: 'Build', properties: {name: 'ok'} }, \ + no: Button { text: 'Cancel', properties: {name: 'cancel'} } \ + } \ + }", "not read", [0, 0, 10, 10]); +"#; + +#[test] +fn a_resource_specification_builds_the_controls_it_names() { + let (mut r, seen, _) = realm(vec![change(4, Data::String("typed".into())), click(6)]); + let rest = r#" + var t = w.msg.title; + var shape = [w.text, w.bounds === undefined, w.children.length, w.msg.type, w.msg.text, w.msg.orientation, w.msg.alignChildren.join(), + t.parent === w.msg, t.st.type, t.st.text, t.et.type, t.et.characters, w.buttons.ok.name, w.buttons.no.name, w.ignored].join('|'); + var p = w.add("more: Panel { text: 'More', e: EditText { properties: {multiline: true}, text: 'x' }, l: DropDownList { properties: {items: ['a', 'b']} } }"); + var added = [p.parent === w, w.more === undefined, p.e.properties.multiline, p.l.items.length, p.l.items[1].text].join('|'); + p.parent.remove(p); + [shape, added, w.show(), t.et.text].join('#') + "#; + let source = format!("{RESOURCE_FORM} {rest}"); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String( + "Form|true|2|panel|Messages|column|right,top|true|statictext|Title:|edittext|35|ok|cancel|1#true|true|true|2|b#1#typed".into() + ) + ); + let seen = seen.borrow(); + assert_eq!(nodes(&seen.descriptions[0]).len(), 8, "the dialog lists the controls the specification names"); +} + +#[test] +fn a_resource_slider_and_progress_bar_take_their_creation_properties_and_values() { + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window(\"dialog { \ + s: Slider { properties: {name: 'size'}, minvalue: 2, maxvalue: 20, value: 7 }, \ + p: ProgressBar { properties: {name: 'done', alignment: 'fill'}, maxvalue: 50, value: 5 } }\"); \ + [w.s.name, w.s.minvalue, w.s.maxvalue, w.s.value, w.findElement('size') === w.s, w.p.name, w.p.alignment, w.p.maxvalue, w.p.value].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("size|2|20|7|true|done|fill|50|5".into())); +} + +#[test] +fn a_resource_list_s_items_are_the_items_the_dialog_shows() { + let (mut r, _, _) = realm(vec![change(1, Data::Number(2.0)), click(2)]); + let source = "var w = new Window(\"dialog { l: DropDownList { items: ['a', 'b', 'c'], selection: 1 }, ok: Button { text: 'OK' } }\"); \ + var before = [w.l.items.length, w.l.selection.text].join(); [before, w.show(), w.l.selection.text].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("3,b|1|c".into())); + let (mut r, _, _) = realm(Vec::new()); + let both = + r.run("try { new Window(\"dialog { l: ListBox { items: ['a'], properties: {items: ['b']} } }\"); 'made' } catch (e) { e.name }").unwrap(); + assert_eq!(both, JsValue::String("TypeError".into()), "items given both ways"); +} + +#[test] +fn a_malformed_resource_specification_throws_a_syntax_error() { + for source in [ + "new Window('dialog { b: Button { text: } }')", + "new Window('dialog { b: Button {} ')", + "new Window('dialog {} trailing')", + "new Window('dialog').add('g: Group { v: orange }')", + "new Window('dialog').add('g: Group { o: { b: Button {} } }')", + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.name }}")).unwrap(); + assert_eq!(e, JsValue::String("SyntaxError".into()), "{source}"); + } + let (mut r, _, _) = realm(Vec::new()); + let unknown = r.run("try { new Window('dialog { b: Wobble {} }'); 'made' } catch (e) { e.message }").unwrap(); + assert_eq!(unknown, JsValue::String("add: there is no control type wobble".into())); +} + +#[test] +fn a_resource_specification_keeps_to_the_dialog_limits() { + let (mut r, _, _) = realm(Vec::new()); + let many = r + .run(&format!( + "var s = 'dialog {{'; for (var i = 0; i <= {}; i++) s += ' b' + i + ': Button {{}}'; s += ' }}'; \ + try {{ new Window(s); 'made' }} catch (e) {{ e.name }}", + scriptui::MAX_CONTROLS + )) + .unwrap(); + assert_eq!(many, JsValue::String("RangeError".into())); + let fits = r + .run(&format!( + "var s = 'dialog {{'; for (var i = 0; i < {}; i++) s += ' b' + i + ': Button {{}}'; s += ' }}'; new Window(s).children.length", + scriptui::MAX_CONTROLS + )) + .unwrap(); + assert_eq!(fits, JsValue::Number(scriptui::MAX_CONTROLS as f64)); + let added = r + .run(&format!( + "var w = new Window('dialog'); for (var i = 0; i < {}; i++) w.add('button'); \ + var e = ''; try {{ w.add('g: Group {{ a: Button {{}}, b: Button {{}} }}'); }} catch (x) {{ e = x.name; }} [e, w.children.length].join()", + scriptui::MAX_CONTROLS - 2 + )) + .unwrap(); + assert_eq!(added, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS - 1)), "the group took a place before its second button"); + let nested = |depth: usize| { + format!( + "var s = ''; for (var d = 0; d < {depth}; d++) s += 'g: Group {{ '; for (d = 0; d < {depth}; d++) s += '}} '; \ + try {{ var c = new Window('dialog {{ ' + s + '}}'); while (c.g) c = c.g; 'made ' + c.type }} catch (e) {{ e.name }}" + ) + }; + assert_eq!(r.run(&nested(scriptui::MAX_DEPTH)).unwrap(), JsValue::String("made group".into())); + assert_eq!(r.run(&nested(scriptui::MAX_DEPTH + 1)).unwrap(), JsValue::String("RangeError".into())); +} + #[test] fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { let (mut r, _, _) = realm(Vec::new()); diff --git a/docs/mcp.md b/docs/mcp.md index 1317559a57..b6df55b2f3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2902,8 +2902,17 @@ https://extendscript.docsforadobe.dev/user-interface-tools/control-objects/ and https://extendscript.docsforadobe.dev/user-interface-tools/types-of-controls/ describe ScriptUI's `Window` and its controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and shows it: -- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) or a - resource string throws an `Error` that says it is not available yet. +- `new Window("dialog"[, title, bounds, properties])` makes a dialog. Another type (`palette`, `window`) throws + an `Error` that says it is not available yet. +- `new Window` and `add` also take a resource specification in place of the type, as + https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/ describes it: + `"dialog { text: 'Settings', g: Group { label: StaticText { text: 'Name:' }, ok: Button { text: 'OK' } } }"`, or + `"[name:] Class { ... }"` for `add`. The other arguments are not read. Inside the braces, `properties` gives the + creation properties, each `name: Class { ... }` adds that control through `add`, with its limits, and sets it as + the container's property `name`, a list's `items` gives its item texts, and every other `name: value` sets that + property. A value is `null`, `true`, `false`, a quoted string, a number, an inline array or an inline object, + and the commas between properties may be left out. A malformed specification throws a `SyntaxError`, and one longer than 1 MiB or nested more than 64 + deep throws a `RangeError` (VectorCraft's own limits). - `container.add(type[, bounds, ...])` adds a control to the dialog, a `group` or a `panel` and returns it. The types are `group`, `panel`, `statictext`, `edittext`, `button`, `checkbox`, `radiobutton`, `dropdownlist`, `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b47a547b34..3fe2745c73 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,7 +1066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Custom arrowheads under `--automation-read-root`: `stroke.arrowheads.list` gives `file` as `null` for an arrowheads file outside the read roots and names it by its file name in `error`, and `stroke.arrowheads.edit` and `stroke.arrowheads.reload` refuse such a file before anything is made, opened, brought to the front or read; inside the roots `edit` opens the file under the client's roots. `crates/engine/src/tests/arrowheads.rs` (`an_agent_outside_the_arrowheads_files_folder_sees_its_file_name_alone_and_cannot_reload_it`, `an_agent_edits_the_arrowheads_file_only_inside_its_read_roots`). - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. Palettes, other control types and resource strings throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. + - Scripts: ScriptUI's `new Window("dialog")` builds a modal dialog of groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars (https://extendscript.docsforadobe.dev/user-interface-tools/window-object/). `show()` waits for the person, runs the controls' `onClick`, `onChanging`, `onChange`, `onShow` and `onClose` handlers, and returns the result of `close(result)`, 1 for the default button or 2 for the cancel button. Controls also take `notify`, size objects a script can set one side of, lists' `find` and `remove`, and `addEventListener` for clicks and changes, which the dialog also takes for `show`; `Window.alert`, `Window.confirm` and `Window.prompt` open the script dialogs; a run over MCP or the command line takes the clicks and changes from a `window` answer. `new Window` and `add` also build a window or a control and the controls inside it from a resource specification (https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/). Palettes and other control types throw that they are not available yet. `crates/js/src/scriptui_tests.rs`, `crates/engine/src/tests/script_scriptui.rs`, `crates/ui-egui/src/tests/script_window.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).