From c3ea4e2f9cca7a2250b47c428ec93a25e5629b24 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 00:14:17 -0800 Subject: [PATCH 01/29] Scripts: build and show ScriptUI dialogs with new Window("dialog") A script can now build a modal dialog with new Window("dialog", title) and add() groups, panels, static text, edit fields, buttons, check boxes, radio buttons, drop-down lists, list boxes, sliders and progress bars. The engine checks the description and lays it out without recursion, within VectorCraft's own limits (512 controls 16 deep, 1024 list items, 16 KiB a text, sizes clamped to 8192 px). Other control types, palettes and resource strings throw that they are not available yet. - show() waits like alert, runs onClick, onChanging, onChange, onShow and onClose in the run's fuel, and returns close(result)'s result, 1 for the default button or 2 for the cancel button, or 0 for the close box. A show() inside a handler throws. - In the app the dialog draws the controls where the engine placed them, gives text still typed in a field before a click or a close, and keeps its state while a handler runs. Enter clicks the default button, Escape the cancel button, and Stop ends the run and puts the documents back. - A run over MCP or the command line takes a window answer: the steps of one show(), each a click, a change or a close. - The report lists each dialog with its controls, events and result; vc.api.has("scriptui") is true. Docs: docs/mcp.md (script.run), docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/dialogs.rs | 165 ++- crates/engine/src/script/mod.rs | 22 +- crates/engine/src/script/scriptui.rs | 666 +++++++++++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/script_scriptui.rs | 365 ++++++ .../tests/it/script_host_vs_scriptcheck.rs | 8 +- crates/js/src/file_classes.rs | 1 + crates/js/src/interp.rs | 80 +- crates/js/src/lib.rs | 3 + crates/js/src/realm.rs | 14 + crates/js/src/scriptui.rs | 1026 +++++++++++++++++ crates/js/src/scriptui_tests.rs | 309 +++++ crates/ui-egui/src/dialogs.rs | 12 +- crates/ui-egui/src/dialogs/script_run.rs | 6 +- crates/ui-egui/src/dialogs/script_window.rs | 360 ++++++ crates/ui-egui/src/i18n/ca.tsv | 4 +- crates/ui-egui/src/i18n/cs.tsv | 4 +- crates/ui-egui/src/i18n/da.tsv | 4 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 4 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fi.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hi.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 4 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 4 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ka.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 4 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 4 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/sv.tsv | 4 +- crates/ui-egui/src/i18n/tests.rs | 13 +- crates/ui-egui/src/i18n/tr.tsv | 4 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/script_runs.rs | 30 +- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/script_window.rs | 273 +++++ docs/mcp.md | 71 +- docs/target-app-parity.md | 1 + 47 files changed, 3455 insertions(+), 74 deletions(-) create mode 100644 crates/engine/src/script/scriptui.rs create mode 100644 crates/engine/src/tests/script_scriptui.rs create mode 100644 crates/js/src/scriptui.rs create mode 100644 crates/js/src/scriptui_tests.rs create mode 100644 crates/ui-egui/src/dialogs/script_window.rs create mode 100644 crates/ui-egui/src/tests/script_window.rs diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index dc33c46ab1..fd02b3a9a1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; 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, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|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, 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); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose 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 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/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index a674396f4b..4c0ce4a39b 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -23,6 +23,7 @@ use std::rc::Rc; use serde_json::{Map, Value, json}; use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; /// The most bytes (UTF-8) of a dialog's message. @@ -48,6 +49,8 @@ pub enum DialogKind { Alert, Confirm, Prompt, + /// A ScriptUI dialog's `show()` ([`super::scriptui`]). + Window, } impl DialogKind { @@ -57,6 +60,7 @@ impl DialogKind { Self::Alert => "alert", Self::Confirm => "confirm", Self::Prompt => "prompt", + Self::Window => "window", } } } @@ -85,6 +89,8 @@ pub enum DialogAnswer { Confirm(bool), /// OK with the field's text, or Cancel (`None`), for `prompt`. Prompt(Option), + /// What happens in a ScriptUI dialog, step by step, for a run with nobody to ask. + Window(Vec), } impl DialogAnswer { @@ -93,13 +99,14 @@ impl DialogAnswer { Self::Ok => DialogKind::Alert, Self::Confirm(_) => DialogKind::Confirm, Self::Prompt(_) => DialogKind::Prompt, + Self::Window(_) => DialogKind::Window, } } /// What the function returns. fn data(&self) -> Data { match self { - Self::Ok => Data::Undefined, + Self::Ok | Self::Window(_) => Data::Undefined, Self::Confirm(b) => Data::Bool(*b), Self::Prompt(Some(t)) => Data::String(t.clone()), Self::Prompt(None) => Data::Null, @@ -112,6 +119,7 @@ impl DialogAnswer { Self::Ok => json!("ok"), Self::Confirm(b) => json!(b), Self::Prompt(t) => json!(t), + Self::Window(steps) => json!(steps.len()), } } } @@ -148,8 +156,9 @@ pub fn cut_to(text: &str, max: usize) -> &str { } /// `script.run`'s `answers`: a list of `{kind: "alert", value: "ok"}`, `{kind: "confirm", value: -/// true | false}` and `{kind: "prompt", value: text | null}`. An empty object, which the parameter -/// took before dialogs existed, is an empty list. +/// true | false}`, `{kind: "prompt", value: text | null}` and `{kind: "window", value: [step, ...]}` +/// ([`super::scriptui`]). An empty object, which the parameter took before dialogs existed, is an +/// empty list. pub(crate) fn parse_answers(v: Option<&Value>) -> Result, String> { let list = match v { None => return Ok(Vec::new()), @@ -166,11 +175,18 @@ pub(crate) fn parse_answers(v: Option<&Value>) -> Result, Stri list.iter().enumerate().map(|(i, a)| answer(a).map_err(|e| format!("`answers[{i}]` {e}"))).collect() } -fn answer(a: &Value) -> Result { - let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`") }; +fn answer(a: &Value) -> Result { + let Some(o) = a.as_object() else { return Err("must be an object with `kind` and `value`".into()) }; if o.len() != 2 || !o.contains_key("value") { - return Err("must have exactly `kind` and `value`"); + return Err("must have exactly `kind` and `value`".into()); } + if o.get("kind").and_then(Value::as_str) == Some("window") { + return super::scriptui::parse_steps(&o["value"]).map(DialogAnswer::Window); + } + known_answer(o).map_err(String::from) +} + +fn known_answer(o: &Map) -> Result { match (o.get("kind").and_then(Value::as_str), &o["value"]) { (Some("alert"), Value::String(s)) if s == "ok" => Ok(DialogAnswer::Ok), (Some("alert"), _) => Err("is an alert's answer, whose `value` must be \"ok\""), @@ -180,7 +196,7 @@ fn answer(a: &Value) -> Result { (Some("prompt"), Value::String(s)) if s.len() <= MAX_PROMPT_BYTES => Ok(DialogAnswer::Prompt(Some(s.clone()))), (Some("prompt"), Value::String(_)) => Err("is longer than 16 KiB"), (Some("prompt"), _) => Err("is a prompt's answer, whose `value` must be a string or null"), - _ => Err("must have `kind` alert, confirm or prompt"), + _ => Err("must have `kind` alert, confirm, prompt or window"), } } @@ -199,6 +215,12 @@ pub(crate) struct Dialogs { record_bytes: Cell, count: Cell, truncated: Cell, + /// The ScriptUI dialog whose `show()` is running. + window: RefCell>, + /// That dialog waits for what the person does. + window_waiting: Cell, + /// The `show()` calls the run has made. + shows: Cell, } impl Dialogs { @@ -213,6 +235,9 @@ impl Dialogs { record_bytes: Cell::new(0), count: Cell::new(0), truncated: Cell::new(false), + window: RefCell::default(), + window_waiting: Cell::new(false), + shows: Cell::new(0), } } @@ -222,7 +247,118 @@ impl Dialogs { } pub(crate) fn is_waiting(&self) -> bool { - self.waiting.borrow().is_some() + self.waiting.borrow().is_some() || self.window_waiting.get() + } + + /// The ScriptUI dialog that waits for what the person does. + pub(crate) fn waiting_window(&self) -> Option { + if !self.window_waiting.get() { + return None; + } + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. + pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { + if !self.window_waiting.get() { + return Err("no script dialog waits".into()); + } + let event = { + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err("no script dialog waits".into()) }; + let event = scriptui::check_event(&showing.dialog, event)?; + showing.events = showing.events.saturating_add(1); + event + }; + self.window_waiting.set(false); + if let Err(e) = realm.answer(event.data()) { + *self.failed.borrow_mut() = Some(e); + } + Ok(()) + } + + fn cannot_wait(&self) -> Result<(), HostError> { + if self.framed && !self.can_wait.get() { + return Err(HostError::Error( + "show: a dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + .into(), + )); + } + Ok(()) + } + + /// `show()` opens `dialog`. A run with nobody to ask takes its next answer, which must be a + /// `window` answer. + pub(crate) fn window_open(&self, mut dialog: ScriptUiDialog) -> Result<(), HostError> { + self.cannot_wait()?; + self.shows.set(self.shows.get().saturating_add(1)); + dialog.shown = self.shows.get(); + let mut showing = Showing { dialog, steps: None, events: 0 }; + if !self.framed { + let next = self.answers.borrow_mut().pop_front(); + match next { + Some(DialogAnswer::Window(steps)) => showing.steps = Some(steps.into()), + Some(a) => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort(format!("show: the next answer in `answers` is for {}, not window", a.kind().id()))); + } + None => { + self.push_record(showing.record(json!("missing"))); + return Err(HostError::Abort("show: `answers` has no answer left for this dialog".into())); + } + } + } + *self.window.borrow_mut() = Some(showing); + Ok(()) + } + + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the + /// next step of its answer. + pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { + self.cannot_wait()?; + let mut window = self.window.borrow_mut(); + let Some(showing) = window.as_mut() else { return Err(HostError::Error("show: no dialog is showing".into())) }; + dialog.shown = showing.dialog.shown; + showing.dialog = dialog; + let Some(steps) = showing.steps.as_mut() else { + drop(window); + self.window_waiting.set(true); + return Err(HostError::Wait); + }; + let failure = match steps.pop_front() { + None => "show: the dialog's answer in `answers` has no step left".to_string(), + Some(step) => match scriptui::step_event(&showing.dialog, &step) { + Ok(event) => { + showing.events = showing.events.saturating_add(1); + return Ok(event.data()); + } + Err(e) => format!("show: a step of the dialog's answer in `answers` cannot be taken: {e}"), + }, + }; + if let Some(showing) = window.take() { + self.push_record(showing.record(json!("missing"))); + } + Err(HostError::Abort(failure)) + } + + /// `show()` ends with `result`, or with an error when not `normal`. A run with nobody to ask + /// must have used every step of the dialog's answer. + pub(crate) fn window_end(&self, result: f64, normal: bool) -> Result<(), HostError> { + self.window_waiting.set(false); + let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; + let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + if normal && left > 0 { + self.push_record(showing.record(json!("missing"))); + let steps = if left == 1 { "step" } else { "steps" }; + return Err(HostError::Abort(format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"))); + } + let answer = match result { + _ if !normal => json!("error"), + r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), + r => json!(r), + }; + self.push_record(showing.record(answer)); + Ok(()) } /// The error that ended the run when its answer could not reach the script. @@ -257,10 +393,13 @@ impl Dialogs { if let Some(d) = self.waiting.borrow_mut().take() { self.record(&d, json!("stop")); } + self.window_waiting.set(false); + if let Some(showing) = self.window.borrow_mut().take() { + self.push_record(showing.record(json!("stop"))); + } } fn record(&self, d: &ScriptDialog, answer: Value) { - self.count.set(self.count.get().saturating_add(1)); let mut r = Map::new(); r.insert("kind".into(), json!(d.kind.id())); r.insert("message".into(), json!(d.message)); @@ -269,9 +408,14 @@ impl Dialogs { DialogKind::Alert => r.insert("errorIcon".into(), json!(d.error_icon)), DialogKind::Confirm => r.insert("noAsDefault".into(), json!(d.no_as_default)), DialogKind::Prompt => r.insert("preset".into(), json!(d.preset)), + DialogKind::Window => None, }; r.insert("answer".into(), answer); - let r = Value::Object(r); + self.push_record(Value::Object(r)); + } + + fn push_record(&self, r: Value) { + self.count.set(self.count.get().saturating_add(1)); let bytes = serde_json::to_vec(&r).map_or(usize::MAX, |b| b.len()); let mut records = self.records.borrow_mut(); if self.truncated.get() || records.len() >= MAX_RECORDS || self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { @@ -325,6 +469,7 @@ fn open(host: &Host, kind: DialogKind, args: &[Data]) -> Result let Some(preset) = text(args, 1) else { return Err(HostError::Type(format!("{name}: give the text the field starts with"))) }; (text(args, 2), false, false, preset) } + DialogKind::Window => return Err(HostError::Error("a ScriptUI dialog opens with show()".into())), }; if message.len() > MAX_MESSAGE_BYTES { return Err(HostError::Range(format!("{name}: the message is longer than 16 KiB"))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 0e702c0076..293d77c716 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -52,8 +52,10 @@ pub mod console; pub mod dialogs; pub mod dollar; pub mod include; +pub mod scriptui; pub use dialogs::{DialogAnswer, DialogKind, ScriptDialog}; +pub use scriptui::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; @@ -133,7 +135,7 @@ impl Written { /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; /// The features `vc.api.has` knows. -pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar"]; +pub const API_FEATURES: &[&str] = &["run", "document", "commands", "log", "args", "console", "dialogs", "dollar", "scriptui"]; /// The most commands a run's report lists in `slowestCommands`. pub const SLOWEST_COMMANDS: usize = 5; @@ -1822,6 +1824,23 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The ScriptUI dialog the running script's `show()` waits at for what the person does. A run + /// asked to stop no longer waits: the next [`Session::script_pump`] ends it. + pub fn script_window(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() + } + + /// Gives the ScriptUI dialog the running script waits at `event`; the next + /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still + /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). + pub fn script_window_answer(&mut self, event: UiEvent) -> std::result::Result<(), String> { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return Err("no script dialog waits".into()) }; + with_job(k, |j| j.host.dialogs.window_answer(&mut j.realm, event)).unwrap_or_else(|| Err("no script dialog waits".into())) + } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no /// longer waits. @@ -2076,6 +2095,7 @@ impl Session { .and_then(|()| if fresh { realm.define_host_object("vc", vc_object(&link)) } else { Ok(()) }) .and_then(|()| if fresh { realm.define_host_object("$", dollar_object(&link, info, &localization)) } else { Ok(()) }) .and_then(|()| if fresh { dialogs::install(&mut realm, &link) } else { Ok(()) }) + .and_then(|()| if fresh { scriptui::install(&mut realm, &link) } else { Ok(()) }) .and_then(|()| if fresh { files::install(&mut realm, &link) } else { realm.reset_folder_current() }) .and_then(|()| { let r = realm.start(&expanded.source); diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs new file mode 100644 index 0000000000..62cfaade79 --- /dev/null +++ b/crates/engine/src/script/scriptui.rs @@ -0,0 +1,666 @@ +//! ScriptUI dialogs (`new Window("dialog")`, [`vectorcraft_js::scriptui`]): the description a run +//! gives when it shows one, checked and laid out here before the app draws it, and the events the +//! person or `script.run`'s `answers` give back. +//! +//! A description lists the dialog first and each control after the container that holds it. It is +//! refused with an error thrown at `show()` when a control's container comes after it or is not a +//! group or panel, when it holds more than [`MAX_CONTROLS`] controls, nests deeper than +//! [`MAX_DEPTH`], has more than [`MAX_ITEMS`] list items or a text longer than [`MAX_TEXT_BYTES`], +//! names an orientation or an alignment that does not exist, or gives a slider a minimum above its +//! maximum. Sizes, places, spacing and margins are clamped to [`MAX_EXTENT`] pixels, and a slider's +//! or progress bar's value to its range. +//! +//! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` and `bounds` (left, top, right +//! and bottom in its container). A control's size comes from its text, items and kind, by +//! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out +//! with loops over the list, from the last control to the first for sizes and from the first to the +//! last for places, so a description's nesting takes no native stack. +//! +//! A run with nobody to ask takes one answer from `answers` for each `show()`: `{kind: "window", +//! value: [step, ...]}`, where a step is `{control, event: "click"}`, `{control, event: "change", +//! value}` or `{event: "close"}`. `control` is a control's `name`, or else its text; `value` is an +//! edit field's text, a slider's number, or a list's item index or `null`. Each time the dialog +//! waits it takes the next step; a dialog that waits with no step left, a step for a control the +//! dialog does not hold or cannot take it, and steps left when the dialog closes end the run. +//! +//! The limits here are VectorCraft's own: [`MAX_EXTENT`], and the js crate's [`MAX_CONTROLS`], +//! [`MAX_DEPTH`], [`MAX_ITEMS`] and [`MAX_TEXT_BYTES`]. + +use std::rc::Rc; + +use serde_json::{Map, Value, json}; +use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; + +pub use vectorcraft_js::scriptui::{MAX_CONTROLS, MAX_DEPTH, MAX_ITEMS, MAX_TEXT_BYTES}; + +use super::Host; + +/// The largest size or place, in pixels, of a dialog or a control in it. +pub const MAX_EXTENT: f32 = 8192.0; +/// A character's width and a line's height in VectorCraft's size estimates, in pixels. +const CHAR: f32 = 7.0; +const LINE: f32 = 16.0; + +/// A dialog's element. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum UiKind { + Dialog, + Group, + Panel, + StaticText, + EditText, + Button, + CheckBox, + RadioButton, + DropDownList, + ListBox, + Slider, + ProgressBar, +} + +impl UiKind { + fn parse(s: &str) -> Option { + Some(match s { + "dialog" => Self::Dialog, + "group" => Self::Group, + "panel" => Self::Panel, + "statictext" => Self::StaticText, + "edittext" => Self::EditText, + "button" => Self::Button, + "checkbox" => Self::CheckBox, + "radiobutton" => Self::RadioButton, + "dropdownlist" => Self::DropDownList, + "listbox" => Self::ListBox, + "slider" => Self::Slider, + "progressbar" => Self::ProgressBar, + _ => return None, + }) + } + + /// Does it hold controls? + pub fn container(self) -> bool { + matches!(self, Self::Dialog | Self::Group | Self::Panel) + } + + /// Does a click reach it? + pub fn clicks(self) -> bool { + matches!(self, Self::Button | Self::CheckBox | Self::RadioButton) + } +} + +/// How a container places its controls. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Orientation { + Row, + Column, + Stack, +} + +/// Where a control goes across its container: left or top, right or bottom, the middle, or the +/// whole width or height. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Align { + Start, + End, + Center, + Fill, +} + +/// A control's place and size in the dialog, from its top left corner. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct UiRect { + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, +} + +/// One element of a [`ScriptUiDialog`]. +#[derive(Clone, Debug, PartialEq)] +pub struct UiNode { + pub kind: UiKind, + /// The index of its container; the dialog's own is 0. + pub parent: usize, + pub name: String, + pub text: String, + /// It and every container around it are enabled. + pub enabled: bool, + /// It and every container around it are visible. + pub visible: bool, + /// A check box's or radio button's value. + pub checked: bool, + /// A slider's or progress bar's value, within `min` to `max`. + pub value: f64, + pub min: f64, + pub max: f64, + pub items: Vec, + pub selection: Option, + pub multiline: bool, + pub readonly: bool, + pub rect: UiRect, + orientation: Orientation, + align_children: (Option, Option), + alignment: (Option, Option), + spacing: f32, + margins: [f32; 4], + size: [Option; 2], + bounds: Option, +} + +/// A dialog a run shows, checked and laid out. +#[derive(Clone, Debug, PartialEq)] +pub struct ScriptUiDialog { + /// The dialog first, then each control after the container that holds it. + pub nodes: Vec, + /// The button Enter clicks and the one Escape clicks. + pub default_element: Option, + pub cancel_element: Option, + /// Which `show()` of the run this is, counted from 1; 0 before it shows. + pub shown: u64, +} + +impl ScriptUiDialog { + /// The dialog's title. + pub fn title(&self) -> &str { + self.nodes.first().map_or("", |n| n.text.as_str()) + } + + /// The size of the dialog's content. + pub fn size(&self) -> (f32, f32) { + self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) + } + + /// The first control whose name, or else whose text, is `control`. + pub fn find(&self, control: &str) -> Option { + let by = |name: bool| { + self.nodes.iter().enumerate().skip(1).find(|(_, n)| if name { n.name == control } else { n.text == control }).map(|(i, _)| i) + }; + by(true).or_else(|| by(false)) + } +} + +/// A value a control takes in a change. +#[derive(Clone, Debug, PartialEq)] +pub enum UiValue { + Text(String), + Number(f64), + Index(Option), +} + +/// What the person did with a dialog. +#[derive(Clone, Debug, PartialEq)] +pub enum UiEvent { + /// A click on a button, check box or radio button. + Click(usize), + /// A new value for an edit field, a slider or a list. + Change(usize, UiValue), + /// The dialog's close box. + Close, +} + +impl UiEvent { + /// The event as `show()` takes it. + pub(crate) fn data(&self) -> Data { + let event = |e: &str| ("event".to_string(), Data::String(e.into())); + let id = |i: usize| ("id".to_string(), Data::Number(i as f64)); + match self { + Self::Click(i) => Data::Object(vec![event("click"), id(*i)]), + Self::Change(i, v) => { + let value = match v { + UiValue::Text(t) => Data::String(t.clone()), + UiValue::Number(n) => Data::Number(*n), + UiValue::Index(Some(k)) => Data::Number(*k as f64), + UiValue::Index(None) => Data::Null, + }; + Data::Object(vec![event("change"), id(*i), ("value".into(), value)]) + } + Self::Close => Data::Object(vec![event("close")]), + } + } +} + +/// Checks `event` against `dialog`. → the event as the dialog takes it: a slider's value clamped +/// to its range. +pub fn check_event(dialog: &ScriptUiDialog, event: UiEvent) -> Result { + let id = match &event { + UiEvent::Close => return Ok(event), + UiEvent::Click(i) | UiEvent::Change(i, _) => *i, + }; + let Some(n) = dialog.nodes.get(id).filter(|_| id > 0) else { return Err(format!("the dialog has no control {id}")) }; + if !n.enabled || !n.visible { + return Err(format!("the control {} is disabled or hidden", label(n))); + } + match event { + UiEvent::Click(_) if n.kind.clicks() => Ok(event), + UiEvent::Click(_) => Err(format!("the control {} cannot be clicked", label(n))), + UiEvent::Change(_, UiValue::Text(t)) if n.kind == UiKind::EditText && !n.readonly => { + if t.len() > MAX_TEXT_BYTES { + return Err("the text is longer than 16 KiB".into()); + } + Ok(UiEvent::Change(id, UiValue::Text(t))) + } + UiEvent::Change(_, UiValue::Number(v)) if n.kind == UiKind::Slider && v.is_finite() => { + Ok(UiEvent::Change(id, UiValue::Number(v.clamp(n.min, n.max)))) + } + UiEvent::Change(_, UiValue::Index(k)) if matches!(n.kind, UiKind::DropDownList | UiKind::ListBox) => match k { + Some(k) if k >= n.items.len() => Err(format!("the list {} has no item {k}", label(n))), + k => Ok(UiEvent::Change(id, UiValue::Index(k))), + }, + UiEvent::Change(..) => Err(format!("the control {} cannot take that change", label(n))), + UiEvent::Close => Ok(UiEvent::Close), + } +} + +fn label(n: &UiNode) -> String { + let shown = if n.name.is_empty() { &n.text } else { &n.name }; + super::dialogs::cut_to(shown, 64).to_string() +} + +/// A step of a `window` answer in `script.run`'s `answers`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct UiStep { + /// The control's name or text; none for a close. + pub control: Option, + pub event: String, + pub value: Option, +} + +/// The steps of a `window` answer: `[{control, event: "click"} | {control, event: "change", value} +/// | {event: "close"}]`, where `control` is a string of at most 16 KiB and `value` a string, a +/// number or null. +pub(crate) fn parse_steps(v: &Value) -> Result, String> { + let Some(list) = v.as_array() else { return Err("is a window's answer, whose `value` must be a list of steps".into()) }; + list.iter().enumerate().map(|(i, s)| step(s).ok_or_else(|| format!("has a step {i} that is not a valid click, change or close"))).collect() +} + +fn step(s: &Value) -> Option { + let o = s.as_object()?; + if o.keys().any(|k| !matches!(k.as_str(), "control" | "event" | "value")) { + return None; + } + let control = match o.get("control") { + None => None, + Some(Value::String(c)) if c.len() <= MAX_TEXT_BYTES => Some(c.clone()), + Some(_) => return None, + }; + let value = o.get("value").cloned(); + let event = o.get("event").and_then(Value::as_str)?; + let fits = match event { + "close" => control.is_none() && value.is_none(), + "click" => control.is_some() && value.is_none(), + "change" => control.is_some() && matches!(value, Some(Value::String(_) | Value::Number(_) | Value::Null)), + _ => false, + }; + fits.then(|| UiStep { control, event: event.to_string(), value }) +} + +/// The event `step` is for `dialog`. +pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result { + let Some(control) = &step.control else { return Ok(UiEvent::Close) }; + let Some(id) = dialog.find(control) else { return Err(format!("the dialog has no control named {}", super::dialogs::cut_to(control, 64))) }; + let event = match (step.event.as_str(), &step.value) { + ("click", _) => UiEvent::Click(id), + (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match n.as_u64() { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + None => return Err("a list's `value` must be an item index or null".into()), + }, + (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), + (_, Some(Value::Null)) => UiEvent::Change(id, UiValue::Index(None)), + _ => return Err("a change's `value` must be a string, a number or null".into()), + }; + check_event(dialog, event) +} + +fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { + fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) +} + +fn bad(what: &str) -> HostError { + HostError::Type(format!("show: the dialog's description {what}")) +} + +/// A finite number. +fn number(d: &Data) -> Option { + match d { + Data::Number(n) if n.is_finite() => Some(*n), + _ => None, + } +} + +fn text(d: &Data, what: &str) -> Result { + match d { + Data::String(s) if s.len() <= MAX_TEXT_BYTES => Ok(s.clone()), + Data::String(_) => Err(HostError::Range(format!("show: {what} is longer than 16 KiB"))), + _ => Err(bad(&format!("has no {what}"))), + } +} + +fn extent(n: f64) -> f32 { + (n as f32).clamp(-MAX_EXTENT, MAX_EXTENT) +} + +fn align_name(s: &str, horizontal: Option) -> Result<(Option, Option), HostError> { + let a = match (s, horizontal) { + ("left", Some(true) | None) => (Some(Align::Start), None), + ("right", Some(true) | None) => (Some(Align::End), None), + ("top", Some(false) | None) => (None, Some(Align::Start)), + ("bottom", Some(false) | None) => (None, Some(Align::End)), + ("center", _) => (Some(Align::Center), Some(Align::Center)), + ("fill", _) => (Some(Align::Fill), Some(Align::Fill)), + _ => return Err(HostError::Error(format!("show: there is no alignment {}", super::dialogs::cut_to(s, 64)))), + }; + Ok(match horizontal { + Some(true) => (a.0, None), + Some(false) => (None, a.1), + None => a, + }) +} + +fn alignment(d: &Data) -> Result<(Option, Option), HostError> { + match d { + Data::Null | Data::Undefined => Ok((None, None)), + Data::String(s) => align_name(s, None), + Data::Array(a) if a.len() == 2 => { + let part = |d: &Data, h: bool| match d { + Data::String(s) => align_name(s, Some(h)), + _ => Err(bad("has an alignment that is not a name")), + }; + Ok((part(&a[0], true)?.0, part(&a[1], false)?.1)) + } + _ => Err(bad("has an alignment that is not a name or a pair of names")), + } +} + +fn numbers(d: &Data) -> Result, HostError> { + match d { + Data::Null | Data::Undefined => Ok(None), + Data::Array(a) if a.len() == N => { + let mut out = [0.0; N]; + for (o, v) in out.iter_mut().zip(a) { + *o = number(v).ok_or_else(|| bad("has a size that is not a number"))?; + } + Ok(Some(out)) + } + _ => Err(bad("has a size with the wrong count of numbers")), + } +} + +/// Reads, checks and lays out a dialog's description. +pub fn parse(d: &Data) -> Result { + let Data::Object(top) = d else { return Err(bad("is not an object")) }; + let Data::Array(list) = field(top, "nodes") else { return Err(bad("has no list of controls")) }; + if list.is_empty() { + return Err(bad("has no dialog")); + } + if list.len() > MAX_CONTROLS + 1 { + return Err(HostError::Range(format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let mut nodes: Vec = Vec::with_capacity(list.len()); + let mut depth: Vec = Vec::with_capacity(list.len()); + let mut items_total = 0usize; + for (i, n) in list.iter().enumerate() { + let Data::Object(f) = n else { return Err(bad("has a control that is not an object")) }; + let kind = match field(f, "kind") { + Data::String(k) => UiKind::parse(k).ok_or_else(|| bad("has a control of a kind that does not exist"))?, + _ => return Err(bad("has a control without a kind")), + }; + let parent = number(field(f, "parent")).ok_or_else(|| bad("has a control without its container"))?; + let parent = if i == 0 { + if kind != UiKind::Dialog || parent != -1.0 { + return Err(bad("does not start with the dialog")); + } + 0 + } else { + let p = parent as usize; + if parent < 0.0 || parent.fract() != 0.0 || p >= i || kind == UiKind::Dialog { + return Err(bad("has a control before its container")); + } + if !nodes[p].kind.container() { + return Err(bad("has a control inside a control that holds none")); + } + p + }; + let level = if i == 0 { 0 } else { depth[parent] + 1 }; + if level > MAX_DEPTH { + return Err(HostError::Range(format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + depth.push(level); + let flag = |name: &str| matches!(field(f, name), Data::Bool(true)); + let (parent_enabled, parent_visible) = if i == 0 { (true, true) } else { (nodes[parent].enabled, nodes[parent].visible) }; + let items = match field(f, "items") { + Data::Array(a) => a.iter().map(|t| text(t, "a list item's text")).collect::, _>>()?, + _ => Vec::new(), + }; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(HostError::Range(format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let selection = number(field(f, "selection")).map(|k| k as usize).filter(|k| *k < items.len()); + let (min, max) = (number(field(f, "minvalue")).unwrap_or(0.0), number(field(f, "maxvalue")).unwrap_or(100.0)); + if min > max { + return Err(HostError::Range("show: a slider's or progress bar's minvalue is larger than its maxvalue".into())); + } + let orientation = match field(f, "orientation") { + Data::String(s) if s == "row" => Orientation::Row, + Data::String(s) if s == "column" => Orientation::Column, + Data::String(s) if s == "stack" => Orientation::Stack, + Data::Undefined => Orientation::Column, + _ => return Err(HostError::Error("show: a container's orientation must be row, column or stack".into())), + }; + let bounds = numbers::<4>(field(f, "bounds"))?.map(|[l, t, r, b]| { + let (l, t) = (extent(l), extent(t)); + UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } + }); + let size = numbers::<2>(field(f, "size"))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]); + let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); + nodes.push(UiNode { + kind, + parent, + name: text(field(f, "name"), "a control's name")?, + text: text(field(f, "text"), "a control's text")?, + enabled: flag("enabled") && parent_enabled, + visible: flag("visible") && parent_visible, + checked: flag("value"), + value: number(field(f, "value")).unwrap_or(0.0).clamp(min, max), + min, + max, + items, + selection, + multiline: flag("multiline"), + readonly: flag("readonly"), + rect: UiRect::default(), + orientation, + align_children: alignment(field(f, "alignChildren"))?, + alignment: alignment(field(f, "alignment"))?, + spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), + margins, + size, + bounds, + }); + } + let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); + let (default_element, cancel_element) = (target("defaultElement"), target("cancelElement")); + let mut dialog = ScriptUiDialog { nodes, default_element, cancel_element, shown: 0 }; + layout(&mut dialog); + Ok(dialog) +} + +/// A control's own size, by VectorCraft's estimates. +fn own_size(n: &UiNode) -> [f32; 2] { + let chars = |s: &str| s.chars().count() as f32; + let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); + let lines = |s: &str| s.lines().count().max(1) as f32; + let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + match n.kind { + UiKind::StaticText => [widest(&mut n.text.lines()) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], + UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], + UiKind::EditText if n.multiline => [(widest(&mut n.text.lines()) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0], + UiKind::EditText => [(chars(&n.text) * CHAR + 12.0).max(80.0), 24.0], + UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], + UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], + UiKind::Slider => [160.0, 20.0], + UiKind::ProgressBar => [160.0, 12.0], + UiKind::Dialog | UiKind::Group | UiKind::Panel => [0.0, 0.0], + } +} + +/// Lays the dialog out: each control's size from the last to the first, then each place from the +/// first to the last. +fn layout(d: &mut ScriptUiDialog) { + let n = d.nodes.len(); + let mut kids: Vec> = vec![Vec::new(); n]; + for (i, node) in d.nodes.iter().enumerate().skip(1) { + kids[node.parent].push(i); + } + let mut size = vec![[0.0f32; 2]; n]; + for i in (0..n).rev() { + let node = &d.nodes[i]; + let mut s = if node.kind.container() { + let [l, t, r, b] = node.margins; + let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); + for &k in &kids[i] { + if let Some(bounds) = d.nodes[k].bounds { + reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; + continue; + } + let [w, h] = size[k]; + count += 1; + match node.orientation { + Orientation::Row => (main, cross) = (main + w, cross.max(h)), + Orientation::Column => (main, cross) = (main + h, cross.max(w)), + Orientation::Stack => (main, cross) = (main.max(w), cross.max(h)), + } + } + if node.orientation != Orientation::Stack { + main += node.spacing * count.saturating_sub(1) as f32; + } + let (w, h) = match node.orientation { + Orientation::Row | Orientation::Stack => (main, cross), + Orientation::Column => (cross, main), + }; + [(w + l + r).max(reach[0]), (h + t + b).max(reach[1])] + } else { + own_size(node) + }; + for axis in 0..2 { + if let Some(v) = node.size[axis] { + s[axis] = v; + } + } + if let Some(b) = node.bounds { + s = [b.w, b.h]; + } + size[i] = [s[0].clamp(0.0, MAX_EXTENT), s[1].clamp(0.0, MAX_EXTENT)]; + } + d.nodes[0].rect = UiRect { x: 0.0, y: 0.0, w: size[0][0], h: size[0][1] }; + for i in 0..n { + if !d.nodes[i].kind.container() { + continue; + } + let node = d.nodes[i].clone(); + let [l, t, r, b] = node.margins; + let (x, y) = (node.rect.x + l, node.rect.y + t); + let (cw, ch) = ((node.rect.w - l - r).max(0.0), (node.rect.h - t - b).max(0.0)); + let mut cursor = 0.0f32; + for &k in &kids[i] { + let kid = &d.nodes[k]; + let rect = if let Some(bounds) = kid.bounds { + UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } + } else { + let [w, h] = size[k]; + let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); + let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); + let place = |align: Align, own: f32, room: f32| match align { + Align::Start => (0.0, own), + Align::End => ((room - own).max(0.0), own), + Align::Center => (((room - own) / 2.0).max(0.0), own), + Align::Fill => (0.0, room.max(own)), + }; + match node.orientation { + Orientation::Row => { + let (dy, kh) = place(v_align, h, ch); + let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; + cursor += w + node.spacing; + r + } + Orientation::Column => { + let (dx, kw) = place(h_align, w, cw); + let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; + cursor += h + node.spacing; + r + } + Orientation::Stack => { + let (dx, kw) = place(h_align, w, cw); + let (dy, kh) = place(v_align, h, ch); + UiRect { x: x + dx, y: y + dy, w: kw, h: kh } + } + } + }; + d.nodes[k].rect = UiRect { + x: rect.x.clamp(-MAX_EXTENT, MAX_EXTENT), + y: rect.y.clamp(-MAX_EXTENT, MAX_EXTENT), + w: rect.w.clamp(0.0, MAX_EXTENT), + h: rect.h.clamp(0.0, MAX_EXTENT), + }; + } + } +} + +/// The dialog of one `show()`: the steps left for a run with nobody to ask, and how many events it +/// took. +pub(crate) struct Showing { + pub(crate) dialog: ScriptUiDialog, + pub(crate) steps: Option>, + pub(crate) events: u64, +} + +impl Showing { + /// The report's record of the dialog, with its `answer`: the result of `show()`, `"stop"`, + /// `"missing"` or `"error"`. + pub(crate) fn record(&self, answer: Value) -> Value { + let mut r = Map::new(); + r.insert("kind".into(), json!("window")); + r.insert("title".into(), json!(super::dialogs::cut_to(self.dialog.title(), super::dialogs::MAX_TITLE_BYTES))); + r.insert("controls".into(), json!(self.dialog.nodes.len().saturating_sub(1))); + r.insert("events".into(), json!(self.events)); + r.insert("answer".into(), answer); + Value::Object(r) + } +} + +/// The host function `name` of `Window`, for the run `link` holds. +fn function(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem { + let l = link.clone(); + HostItem::Function(Rc::new(move |a| f(&*super::current(&l)?, &a))) +} + +/// Adds `Window` to the realm, for the run `link` holds. +pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunError> { + realm.define_script_ui(vec![("open".into(), function(link, open)), ("wait".into(), function(link, wait)), ("end".into(), function(link, end))]) +} + +fn described(host: &Host, args: &[Data]) -> Result { + host.charge_call(args.iter().map(super::data_size).sum())?; + parse(args.first().unwrap_or(&Data::Undefined)) +} + +fn open(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_open(dialog)?; + Ok(Data::Undefined) +} + +fn wait(host: &Host, args: &[Data]) -> Result { + let dialog = described(host, args)?; + host.dialogs.window_wait(dialog) +} + +fn end(host: &Host, args: &[Data]) -> Result { + let result = number(args.first().unwrap_or(&Data::Undefined)).unwrap_or(0.0); + let normal = matches!(args.get(1), Some(Data::Bool(true))); + host.dialogs.window_end(result, normal)?; + Ok(Data::Undefined) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e524d1c63c..58addcd9fe 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -177,6 +177,7 @@ mod script_folder; mod script_include; mod script_io; mod script_run; +mod script_scriptui; mod scripts; mod select_effects; mod select_ids_first; diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs new file mode 100644 index 0000000000..24a6052154 --- /dev/null +++ b/crates/engine/src/tests/script_scriptui.rs @@ -0,0 +1,365 @@ +//! ScriptUI dialogs in a script: the description the engine checks and lays out, the `window` +//! answers a run with nobody to ask takes from `answers`, the wait in the app, Stop, and the +//! report's `dialogs`. + +use serde_json::{Value, json}; +use vectorcraft_js::{Data, HostError}; + +use crate::script::scriptui::{self, MAX_CONTROLS, MAX_DEPTH, MAX_EXTENT, MAX_TEXT_BYTES}; +use crate::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; +use crate::*; + +/// One open document with one rectangle. +fn one_doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + s +} + +fn art(s: &Session) -> (String, usize) { + let d = &s.documents()[0]; + (format!("{:?}", d.doc.layers), d.history.undo.len()) +} + +fn headless(s: &mut Session, source: &str, answers: Value) -> Result { + s.execute("script.run", &json!({"source": source, "name": "w.js", "answers": answers})) +} + +/// A run in the app of `source`, one slice in. +fn framed(s: &mut Session, source: &str) { + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + assert!(s.script_pump().is_none()); +} + +/// Pumps the run in the app until it ends or waits at a ScriptUI dialog (`None`). +fn pump(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_window().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +fn window(steps: Value) -> Value { + json!([{"kind": "window", "value": steps}]) +} + +const EDIT: &str = "vc.run('shape.rectangle', {x: 20, y: 0, width: 5, height: 5});"; + +/// A dialog with a field, a check box, a slider, a list and OK and Cancel. +const FORM: &str = "var w = new Window('dialog', 'Settings'); var g = w.add('group'); \ + g.add('statictext', undefined, 'Name:'); var name = g.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); var size = w.add('slider', undefined, 5, 0, 10); size.name = 'size'; \ + var pick = w.add('dropdownlist', undefined, ['a', 'b', 'c']); pick.name = 'pick'; \ + var ok = w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +#[test] +fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { + let mut s = one_doc(); + let source = format!( + "{EDIT} {FORM} bold.onClick = function () {{ name.text = 'bolded'; }}; var r = w.show(); vc.log([r, name.text, bold.value, size.value, pick.selection.text]);" + ); + let steps = json!([ + {"control": "Bold", "event": "click"}, + {"control": "size", "event": "change", "value": 99}, + {"control": "pick", "event": "change", "value": 2}, + {"control": "OK", "event": "click"}, + ]); + let r = headless(&mut s, &source, window(steps)).unwrap(); + assert_eq!(r["log"], json!([[1, "bolded", true, 10, "c"]]), "the slider's value is clamped to its range: {r}"); + assert_eq!(r["dialogs"], json!([{"kind": "window", "title": "Settings", "controls": 8, "events": 4, "answer": 1}])); + let cancel = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"control": "Cancel", "event": "click"}]))).unwrap(); + assert_eq!(cancel["log"], json!([2])); + let closed = headless(&mut s, &format!("{FORM} vc.log(w.show());"), window(json!([{"event": "close"}]))).unwrap(); + assert_eq!(closed["log"], json!([0])); +} + +#[test] +fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}"); + for (given, says) in [ + (json!([]), "`answers` has no answer left for this dialog"), + (json!([{"kind": "alert", "value": "ok"}]), "is for alert, not window"), + (window(json!([])), "has no step left"), + (window(json!([{"control": "Nothing", "event": "click"}])), "the dialog has no control named Nothing"), + (window(json!([{"control": "Name:", "event": "click"}])), "cannot be clicked"), + (window(json!([{"control": "pick", "event": "change", "value": 3}])), "has no item 3"), + (window(json!([{"control": "OK", "event": "click"}, {"event": "close"}])), "has 1 step the dialog did not use"), + ] { + let e = headless(&mut s, &source, given.clone()).unwrap_err().to_string(); + assert!(e.contains(says), "{given}: {e}"); + assert_eq!(art(&s), before, "{given}"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!([]), "a missing answer cannot be caught: {report}"); + assert_eq!(report["dialogs"][0]["answer"], "missing", "{report}"); + } +} + +#[test] +fn window_answers_that_do_not_parse_are_refused_before_the_run() { + let mut s = one_doc(); + let bad = |i: usize| format!("`answers[0]` has a step {i} that is not a valid click, change or close"); + for (steps, says) in [ + (json!("click"), "`answers[0]` is a window's answer, whose `value` must be a list of steps".to_string()), + (json!([1]), bad(0)), + (json!([{"event": "close"}, {"event": "tap", "control": "OK"}]), bad(1)), + (json!([{"event": "click"}]), bad(0)), + (json!([{"event": "click", "control": "OK", "value": 1}]), bad(0)), + (json!([{"event": "change", "control": "x"}]), bad(0)), + (json!([{"event": "change", "control": "x", "value": [1]}]), bad(0)), + (json!([{"event": "change", "control": "x".repeat(MAX_TEXT_BYTES + 1), "value": 1}]), bad(0)), + (json!([{"event": "close", "control": "x"}]), bad(0)), + (json!([{"event": "close", "extra": 1}]), bad(0)), + ] { + let e = headless(&mut s, "1", window(steps.clone())).unwrap_err().to_string(); + assert!(e.contains(&says), "{steps}: {e}"); + } +} + +#[test] +fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { + let mut s = one_doc(); + framed( + &mut s, + &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), + ); + let d = s.script_window().expect("show waits"); + assert_eq!(d.title(), "Settings"); + assert_eq!(d.nodes.len(), 9); + assert_eq!((d.nodes[3].kind, d.nodes[3].text.as_str()), (UiKind::EditText, "first")); + let bold = d.find("Bold").unwrap(); + let size = d.find("size").unwrap(); + assert!(s.script_window_answer(UiEvent::Click(d.find("Name:").unwrap())).is_err(), "static text takes no click"); + assert!(s.script_window_answer(UiEvent::Change(3, UiValue::Text("x".repeat(MAX_TEXT_BYTES + 1)))).is_err()); + assert!(s.script_window_answer(UiEvent::Click(99)).is_err()); + s.script_window_answer(UiEvent::Click(bold)).unwrap(); + assert!(s.script_window_answer(UiEvent::Close).is_err(), "nothing waits until the run goes on"); + assert!(pump(&mut s).is_none()); + let d = s.script_window().unwrap(); + assert!(d.nodes[bold].checked); + assert!(!d.nodes[size].enabled, "the handler disabled the slider"); + assert!(s.script_window_answer(UiEvent::Change(size, UiValue::Number(3.0))).is_err(), "a disabled control takes no events"); + s.script_window_answer(UiEvent::Change(3, UiValue::Text("Ann".into()))).unwrap(); + assert!(pump(&mut s).is_none()); + s.script_window_answer(UiEvent::Click(d.default_element.unwrap())).unwrap(); + let r = pump(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[1, "Ann", 5]])); + assert_eq!(r["dialogs"][0]["events"], 3); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); +} + +#[test] +fn stop_while_show_waits_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + framed(&mut s, &format!("{EDIT} {FORM} w.show(); vc.log('after');")); + assert!(s.script_window().is_some()); + assert_eq!(s.execute("script.stop", &json!({})).unwrap()["stopped"], true); + assert_eq!(s.script_window(), None, "a run asked to stop no longer waits"); + assert!(s.script_window_answer(UiEvent::Close).is_err()); + assert!(s.script_pump().unwrap().is_err()); + let report = s.script_report().unwrap(); + assert_eq!((report["kind"].as_str(), &report["log"]), (Some("stopped"), &json!([])), "{report}"); + assert_eq!(report["dialogs"][0]["answer"], "stop"); + assert_eq!(art(&s), before); + framed(&mut s, &format!("{EDIT} {FORM} w.show();")); + assert!(s.script_abandon(), "quitting while a dialog waits abandons the run"); + assert_eq!(art(&s), before); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!("{EDIT} {FORM} bold.onClick = function () {{ for (;;) {{}} }}; w.show();"); + let e = headless(&mut s, &source, window(json!([{"control": "Bold", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("limit") || e.contains("fuel") || e.contains("instructions"), "{e}"); + assert_eq!(art(&s), before); + assert_eq!(s.script_report().unwrap()["dialogs"][0]["answer"], "error"); +} + +#[test] +fn a_show_in_a_callback_throws_in_the_app() { + let mut s = one_doc(); + s.script_frames = true; + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var e = ''; try { [1].forEach(function () { w.show(); }); } catch (x) { e = x.message; } vc.log(e);"; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a callback").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + +fn node(kind: &str, parent: f64) -> Data { + Data::Object(vec![ + ("kind".into(), Data::String(kind.into())), + ("parent".into(), Data::Number(parent)), + ("name".into(), Data::String(String::new())), + ("text".into(), Data::String("t".into())), + ("enabled".into(), Data::Bool(true)), + ("visible".into(), Data::Bool(true)), + ]) +} + +fn description(nodes: Vec) -> Data { + Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(-1.0)), + ("cancelElement".into(), Data::Number(-1.0)), + ]) +} + +fn with(n: Data, name: &str, value: Data) -> Data { + let Data::Object(mut fields) = n else { panic!("a node is an object") }; + fields.retain(|(k, _)| k != name); + fields.push((name.into(), value)); + Data::Object(fields) +} + +fn refused(d: &Data) -> String { + match scriptui::parse(d) { + Err(HostError::Type(m) | HostError::Range(m) | HostError::Error(m)) => m, + other => panic!("not refused: {other:?}"), + } +} + +#[test] +fn a_description_out_of_order_too_large_too_deep_or_too_long_is_refused() { + let dialog = node("dialog", -1.0); + assert!(refused(&description(vec![])).contains("has no dialog")); + assert!(refused(&description(vec![node("group", -1.0)])).contains("does not start with the dialog")); + assert!(refused(&description(vec![dialog.clone(), node("button", 2.0), node("group", 0.0)])).contains("before its container")); + assert!(refused(&description(vec![dialog.clone(), node("button", 1.0)])).contains("before its container"), "a control cannot hold itself"); + assert!(refused(&description(vec![dialog.clone(), node("button", 0.0), node("button", 1.0)])).contains("holds none")); + assert!(refused(&description(vec![dialog.clone(), node("dialog", 0.0)])).contains("before its container")); + let many: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_CONTROLS).map(|_| node("button", 0.0))).collect(); + assert!(refused(&description(many)).contains(&format!("at most {MAX_CONTROLS} controls"))); + let deep: Vec = std::iter::once(dialog.clone()).chain((0..=MAX_DEPTH).map(|k| node("group", k as f64))).collect(); + assert!(refused(&description(deep)).contains(&format!("at most {MAX_DEPTH} deep"))); + let long = with(node("statictext", 0.0), "text", Data::String("x".repeat(MAX_TEXT_BYTES + 1))); + assert!(refused(&description(vec![dialog.clone(), long])).contains("longer than 16 KiB")); + let slider = with(with(node("slider", 0.0), "minvalue", Data::Number(5.0)), "maxvalue", Data::Number(1.0)); + assert!(refused(&description(vec![dialog.clone(), slider])).contains("minvalue is larger")); + let nan = with(node("button", 0.0), "bounds", Data::Array(vec![Data::Number(0.0), Data::Number(f64::NAN), Data::Number(1.0), Data::Number(1.0)])); + assert!(refused(&description(vec![dialog.clone(), nan])).contains("not a number")); + let orient = with(dialog.clone(), "orientation", Data::String("diagonal".into())); + assert!(refused(&description(vec![orient])).contains("row, column or stack")); + let align = with(node("button", 0.0), "alignment", Data::String("sideways".into())); + assert!(refused(&description(vec![dialog, align])).contains("no alignment sideways")); +} + +#[test] +fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { + let dialog = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "margins", Data::Array(vec![Data::Number(10.0); 4])); + let row = with(with(node("group", 0.0), "orientation", Data::String("row".into())), "spacing", Data::Number(5.0)); + let a = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(100.0), Data::Number(20.0)])); + let b = with(node("button", 1.0), "size", Data::Array(vec![Data::Number(50.0), Data::Number(30.0)])); + let huge = + with(node("statictext", 0.0), "bounds", Data::Array(vec![Data::Number(-1e12), Data::Number(0.0), Data::Number(1e12), Data::Number(1e300)])); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, row, a, b, huge])).unwrap(); + assert_eq!((d.nodes[1].rect.w, d.nodes[1].rect.h), (155.0, 30.0), "a row adds widths and spacing, and takes the tallest height"); + assert_eq!((d.nodes[2].rect.x, d.nodes[3].rect.x), (10.0, 115.0)); + assert_eq!(d.nodes[2].rect.y, 15.0, "a shorter control is centered in its row"); + for n in &d.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + } + let (w, h) = d.size(); + assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); +} + +/// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and +/// not-a-number ones included) and texts of any length. +fn any_description() -> impl proptest::strategy::Strategy { + use proptest::prelude::*; + let kind = prop_oneof![ + Just("dialog"), + Just("group"), + Just("panel"), + Just("statictext"), + Just("edittext"), + Just("button"), + Just("checkbox"), + Just("radiobutton"), + Just("dropdownlist"), + Just("listbox"), + Just("slider"), + Just("progressbar"), + Just("wobble"), + ]; + let number = prop_oneof![1 => Just(f64::NAN), 1 => Just(f64::INFINITY), 1 => Just(-1e300), 1 => any::(), 6 => -50.0..400.0f64]; + let text = prop_oneof![2 => Just(String::new()), 8 => "[ -~]{0,40}", 1 => Just("x".repeat(MAX_TEXT_BYTES + 1))]; + let bounds = proptest::option::of(proptest::collection::vec(number.clone(), 4..=4)); + let size = proptest::option::of(proptest::collection::vec(number.clone(), 2..=2)); + // The container is a share of the controls before this one, or with a share past 1, one after it. + let fields = (kind, 0.0..1.1f64, text, bounds, size, 0..4usize, number); + proptest::collection::vec(fields, 0..40).prop_map(|nodes| { + let mut containers = vec![0usize]; + let mut out = Vec::new(); + for (i, (kind, share, text, bounds, size, items, value)) in nodes.into_iter().enumerate() { + let kind = if i == 0 { "dialog" } else { kind }; + let parent = match i { + 0 => -1.0, + _ if share >= 1.0 => (i + 1) as f64, + _ => containers[((share * containers.len() as f64) as usize).min(containers.len() - 1)] as f64, + }; + if matches!(kind, "group" | "panel") { + containers.push(i); + } + let numbers = |v: Option>| v.map_or(Data::Null, |v| Data::Array(v.into_iter().map(Data::Number).collect())); + let mut n = with(with(node(kind, parent), "text", Data::String(text)), "bounds", numbers(bounds)); + n = with(n, "size", numbers(size)); + n = with(n, "items", Data::Array((0..items).map(|k| Data::String(k.to_string())).collect())); + n = with(n, "selection", Data::Number(value)); + out.push(with(with(n, "minvalue", Data::Number(0.0)), "value", Data::Number(value))); + } + description(out) + }) +} + +proptest::proptest! { + #![proptest_config(proptest::prelude::ProptestConfig::with_cases(256))] + + /// Any description is refused with an error or laid out with every place and size finite and + /// within the limit. + #[test] + fn any_description_is_refused_or_laid_out_within_its_limits(d in any_description()) { + if let Ok(dialog) = scriptui::parse(&d) { + for n in &dialog.nodes { + for v in [n.rect.x, n.rect.y, n.rect.w, n.rect.h] { + proptest::prop_assert!(v.is_finite() && v.abs() <= MAX_EXTENT, "{:?}", n.rect); + } + proptest::prop_assert!(n.value.is_finite() && n.selection.is_none_or(|k| k < n.items.len())); + } + } + } +} + +#[test] +fn an_event_is_checked_against_the_dialog() { + let d = scriptui::parse(&description(vec![ + node("dialog", -1.0), + node("button", 0.0), + with(node("edittext", 0.0), "readonly", Data::Bool(true)), + with(with(with(node("slider", 0.0), "minvalue", Data::Number(0.0)), "maxvalue", Data::Number(10.0)), "value", Data::Number(4.0)), + with(node("listbox", 0.0), "items", Data::Array(vec![Data::String("a".into())])), + with(node("button", 0.0), "visible", Data::Bool(false)), + ])) + .unwrap(); + assert_eq!(scriptui::check_event(&d, UiEvent::Click(1)), Ok(UiEvent::Click(1))); + assert!(scriptui::check_event(&d, UiEvent::Click(0)).is_err(), "the dialog itself is no control"); + assert!(scriptui::check_event(&d, UiEvent::Change(2, UiValue::Text("x".into()))).is_err(), "a read-only field takes no text"); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(-5.0))), Ok(UiEvent::Change(3, UiValue::Number(0.0)))); + assert!(scriptui::check_event(&d, UiEvent::Change(3, UiValue::Number(f64::NAN))).is_err()); + assert!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(Some(1)))).is_err()); + assert_eq!(scriptui::check_event(&d, UiEvent::Change(4, UiValue::Index(None))), Ok(UiEvent::Change(4, UiValue::Index(None)))); + assert!(scriptui::check_event(&d, UiEvent::Click(5)).is_err(), "a hidden control takes no events"); + assert_eq!(scriptui::check_event(&d, UiEvent::Close), Ok(UiEvent::Close)); +} diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 660433b800..800b0f35df 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -40,10 +40,12 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ ]; /// The names the host adds that stay inside the document and the run, by the object that has them. -/// Reading a file or a folder, a file dialog and a message to the person do not change anything -/// outside it. +/// Reading a file or a folder, a file dialog, a message to the person and a ScriptUI dialog do not +/// change anything outside it. const INSIDE: &[(&str, &str)] = &[ - ("", "$ File Folder alert confirm localize prompt toSource"), + ("", "$ File Folder Window alert confirm localize prompt toSource"), + ("Window.", "length prototype"), + ("Window.prototype.", "add center close constructor findElement hide show"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 30de04cf12..f999a59b33 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -617,6 +617,7 @@ fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Val args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], resume: picked, + failed: None, }) } diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 24c33d2fc5..bd78fa419d 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -193,18 +193,25 @@ pub(crate) type CodeObserver = Rc; pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; /// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the -/// answer, and gives the result of its call. +/// answer, and gives the result of its call. One that puts another [`Pause`] in +/// [`Interp::again`] makes that host call next, and the call's result is what that pause's +/// resume function gives. pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; +/// What a [`Pause`] does with its kept values when its host call fails. +pub(crate) type FailFn = fn(&mut Interp, &[Value]); + /// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to /// `resume` with `keep`, at once when the host answers at once. When the host waits /// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on /// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +/// When the host call fails, `failed` is given `keep` before the error is thrown at the call. pub(crate) struct Pause { pub(crate) host: Value, pub(crate) args: Vec, pub(crate) keep: Vec, pub(crate) resume: ResumeFn, + pub(crate) failed: Option, } /// A [`Pause`] whose host call waits for its answer. @@ -276,6 +283,10 @@ pub(crate) struct Interp { /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before /// the next instruction runs. pub(crate) resuming: Option, + /// The next host call a resume function asks for ([`ResumeFn`]). + pub(crate) again: Option, + /// ScriptUI's `Window` and its controls, when the host added them. + pub(crate) script_ui: Option, /// The message of the uncatchable error a host function ended the run with. pub(crate) host_abort: Option, /// How much a value passed to or from a host function may carry. @@ -528,6 +539,8 @@ impl Interp { can_wait: Rc::default(), waiting: false, resuming: None, + again: None, + script_ui: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -758,6 +771,7 @@ impl Interp { roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); + roots.values.extend(self.again.iter().flat_map(|p| p.keep.iter().chain(p.args.iter()).chain(std::iter::once(&p.host)))); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -774,6 +788,7 @@ impl Interp { roots.objects.push(self.global); roots.objects.extend(self.intrinsics.all()); roots.objects.extend(self.files.iter().flat_map(crate::file_classes::Classes::objects)); + roots.objects.extend(self.script_ui.iter().flat_map(crate::scriptui::Classes::objects)); roots.envs.push(self.global_env); self.heap.collect(&roots); // The collection counts the live total again, so bytes already released are not in it. @@ -2487,35 +2502,60 @@ impl Interp { /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host /// function is called as the script's own code calls it, so it may wait; then the resume /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands - /// in for that answer is the call's result for now. + /// in for that answer is the call's result for now. A resume function that asks [`Self::again`] + /// makes that call next, in this loop, so a built-in may ask any number of times. fn ask(&mut self, p: Pause) -> JsResult { - let Pause { host, args, keep, resume } = p; - let mark = self.temp_roots.len(); - self.temp_roots.push(host.clone()); - self.temp_roots.extend(args.iter().cloned()); - self.temp_roots.extend(keep.iter().cloned()); - let was_waiting = self.waiting; - let answer = match self.func_of(&host) { - Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), - _ => self.call(&host, &Value::Undefined, &args), - }; - self.temp_roots.truncate(mark); - let answer = answer?; - let r = Resumption { resume, keep }; - if self.waiting && !was_waiting { - self.resuming = Some(r); - return Ok(answer); + let mut p = p; + loop { + let Pause { host, args, keep, resume, failed } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + if answer.is_err() + && let Some(failed) = failed + { + failed(self, &keep); + } + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => p = next, + None => return Ok(v), + } } - self.resume(r, answer) } - /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function, and + /// makes the host call it asks for next, if any. fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let v = self.resume_once(r, answer)?; + match self.again.take() { + Some(next) => self.ask(next), + None => Ok(v), + } + } + + fn resume_once(&mut self, r: Resumption, answer: Value) -> JsResult { let mark = self.temp_roots.len(); self.temp_roots.push(answer.clone()); self.temp_roots.extend(r.keep.iter().cloned()); let v = (r.resume)(self, &r.keep, answer); self.temp_roots.truncate(mark); + if v.is_err() { + self.again = None; + } v } diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index 1561d71dfe..c953004550 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -67,6 +67,7 @@ mod realm; mod regexp; mod regexp_builtins; mod regexp_vm; +pub mod scriptui; mod string_builtins; mod token; mod value; @@ -209,6 +210,8 @@ mod host_tests; #[cfg(test)] mod interp_tests; #[cfg(test)] +mod scriptui_tests; +#[cfg(test)] mod tests; #[cfg(test)] mod text_tests; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index ee2cd364f8..ad8d10acce 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -256,6 +256,8 @@ impl Realm { interp.host_abort = None; interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -292,6 +294,8 @@ impl Realm { interp.join_stack.clear(); interp.waiting = false; interp.resuming = None; + interp.again = None; + crate::scriptui::end_run(interp); interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -488,6 +492,16 @@ impl Realm { } } + /// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host + /// functions in `items` show: `open` and `wait`, each given the dialog's description, and + /// `end`, given the result of `show()` and whether `show()` ended normally. + pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { + match crate::scriptui::install(&mut self.interp, items) { + Ok(()) => Ok(()), + Err(e) => self.outcome(Err(e)).map(drop), + } + } + /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs new file mode 100644 index 0000000000..9afc647960 --- /dev/null +++ b/crates/js/src/scriptui.rs @@ -0,0 +1,1026 @@ +//! ScriptUI's `Window` with modal dialogs, as the help page +//! describes it, whose +//! 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 +//! 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). +//! The other documented control types throw an `Error` that says they are not available yet. A +//! list's `add("item", text)` adds an item; its `selection` is an item or `null`, and takes an +//! item, an index or `null`. +//! +//! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the +//! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the +//! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a +//! `change` with its new value, or a `close`. The control takes the change, its `onClick`, +//! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A +//! button without `onClick` closes the dialog with 1 when it is the dialog's default element and +//! with 2 when it is its cancel element. `close(result)` closes the dialog after the running handler +//! returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps the dialog +//! open when it returns `false`. A dialog that is showing cannot be shown again, and no other dialog +//! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether +//! it ended normally. +//! +//! An element keeps its kind, its container, its controls and a list's items in properties that a +//! script cannot change. The description lists the dialog first and every control after the +//! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] +//! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. + +use crate::HostItem; +use crate::builtins::{arg, constructor, method, native, pausable_method}; +use crate::heap::{Class, ENUMERABLE, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +use crate::host::Data; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; + +/// The most controls a dialog holds, its groups and panels included. +pub const MAX_CONTROLS: usize = 512; +/// How deeply controls nest in a dialog: a control the dialog holds is at depth 1. +pub const MAX_DEPTH: usize = 16; +/// The most items a dialog's lists hold together. +pub const MAX_ITEMS: usize = 1024; +/// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. +pub const MAX_TEXT_BYTES: usize = 16 << 10; + +/// The control types `add` makes. +pub const BUILT: [&str; 11] = + ["group", "panel", "statictext", "edittext", "button", "checkbox", "radiobutton", "dropdownlist", "listbox", "slider", "progressbar"]; +/// The documented control types that are not available yet. +const LATER: [&str; 10] = + ["tabbedpanel", "tab", "scrollbar", "image", "iconbutton", "treeview", "flashplayer", "customview", "custombutton", "customboundedvalue"]; + +const KIND: &str = "__vcKind"; +const PARENT: &str = "__vcParent"; +const WINDOW: &str = "__vcWindow"; +const KIDS: &str = "__vcKids"; +const DEPTH: &str = "__vcDepth"; +const COUNT: &str = "__vcCount"; +const ITEM_COUNT: &str = "__vcItemCount"; +const CLOSING: &str = "__vcClosing"; +const ITEMS: &str = "__vcItems"; +const SELECTION: &str = "__vcSelection"; +const LIST: &str = "__vcList"; + +/// The objects of `Window`, kept by the realm, and the dialog that is showing. +#[derive(Clone, Debug)] +pub(crate) struct Classes { + window_proto: ObjId, + control_proto: ObjId, + item_proto: ObjId, + layout: ObjId, + host: ObjId, + selection_get: ObjId, + selection_set: ObjId, + showing: Option, +} + +impl Classes { + /// The objects a collection keeps. + pub(crate) fn objects(&self) -> Vec { + let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; + all.extend(self.showing); + all + } +} + +/// Forgets the dialog that was showing when a run ended where it was. +pub(crate) fn end_run(i: &mut Interp) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = None; + } +} + +fn classes(i: &Interp) -> JsResult { + i.script_ui.clone().ok_or_else(|| Abrupt::Internal("Window is not installed".into())) +} + +fn error(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Error, message) +} + +fn range(i: &mut Interp, message: &str) -> Abrupt { + i.throw(ErrorType::Range, message) +} + +/// The value of the own data property `name` of `o`, `undefined` when it has none. +fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match i.get_own_property(o, &key(name))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) +} + +/// Sets the property `name` of `o` that a script can read but not change. +fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: 0 }) +} + +/// Sets the property `name` of `o` that a script can change. +fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { + i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; + i.define(o, key(name), Prop::Data { value, flags: OPEN }) +} + +fn number_slot(i: &Interp, o: ObjId, name: &str) -> JsResult { + Ok(match slot(i, o, name)? { + Value::Number(n) => n, + _ => 0.0, + }) +} + +fn object_slot(i: &Interp, o: ObjId, name: &str) -> JsResult> { + Ok(slot(i, o, name)?.as_object()) +} + +/// An element's kind, or `None` for a value that is not a ScriptUI window or control. +fn kind_of(i: &Interp, v: &Value) -> JsResult> { + let Some(o) = v.as_object() else { return Ok(None) }; + Ok(match slot(i, o, KIND)? { + Value::String(s) => Some((o, s.to_rust_string())), + _ => None, + }) +} + +/// `this` as an element, or a `TypeError` naming `what`. +fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String)> { + match kind_of(i, this)? { + Some(e) => Ok(e), + None => Err(i.type_error(&format!("{what}: this is not a ScriptUI window or control"))), + } +} + +/// Are `a` and `b` the same object? +fn same(a: &Value, b: &Value) -> bool { + matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) +} + +/// The values of an array made by [`list`]. +fn list_values(i: &Interp, a: ObjId) -> JsResult> { + let length = match &i.object(a)?.class { + Class::Array { length, .. } => *length, + _ => return Ok(Vec::new()), + }; + (0..length) + .map(|n| { + Ok(match i.get_own_property(a, &index_key(n))? { + Some(Prop::Data { value, .. }) => value, + _ => Value::Undefined, + }) + }) + .collect() +} + +/// A new array holding `items`: one a script cannot change unless `open`. +fn list(i: &mut Interp, items: &[Value], open: bool) -> JsResult { + i.rooted(items, |i| i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(items.len() + 1))))?; + let proto = i.intrinsics.array_proto; + let a = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: open }, Some(proto))); + let flags = if open { OPEN } else { ENUMERABLE }; + for (n, v) in items.iter().enumerate() { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + i.define(a, index_key(n), Prop::Data { value: v.clone(), flags })?; + } + i.object_mut(a)?.extensible = open; + Ok(a) +} + +/// Adds `v` to the end of the list in `o`'s slot `name`, and puts a copy a script can change in +/// its property `public`. +fn append(i: &mut Interp, o: ObjId, name: &str, public: &str, v: Value) -> JsResult<()> { + let mut items = match object_slot(i, o, name)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + items.push(v); + i.rooted(&items.clone(), |i| { + let kept = list(i, &items, false)?; + set_slot(i, o, name, Value::Object(kept))?; + let copy = list(i, &items, true)?; + set_open(i, o, public, Value::Object(copy)) + }) +} + +fn text_arg(i: &mut Interp, v: &Value) -> JsResult { + Ok(match v { + Value::Undefined => Value::str(""), + v => Value::String(i.to_str(v)?), + }) +} + +/// A new element of `kind`, with the properties every element has. +fn new_element( + i: &mut Interp, + proto: ObjId, + kind: &str, + parent: Option, + window: Option, + depth: usize, + args: [&Value; 3], +) -> JsResult { + let [bounds, text, props] = args; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(32)))?; + let o = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(o)); + let window = window.unwrap_or(o); + let parent = parent.map_or(Value::Null, Value::Object); + let layout = classes(i)?.layout; + set_slot(i, o, KIND, Value::str(kind))?; + set_slot(i, o, PARENT, parent.clone())?; + set_slot(i, o, WINDOW, Value::Object(window))?; + set_slot(i, o, DEPTH, Value::Number(depth as f64))?; + set_open(i, o, "type", Value::str(kind))?; + set_open(i, o, "parent", parent)?; + set_open(i, o, "window", Value::Object(window))?; + let text = text_arg(i, text)?; + set_open(i, o, "text", text)?; + let props = match props { + Value::Object(_) => props.clone(), + _ => Value::Object(i.new_object()), + }; + set_open(i, o, "properties", props.clone())?; + let name = i.get_value(&props, &key("name"))?; + let name = text_arg(i, &name)?; + set_open(i, o, "name", name)?; + set_open(i, o, "enabled", Value::Bool(true))?; + set_open(i, o, "visible", Value::Bool(true))?; + if !matches!(bounds, Value::Undefined | Value::Null) { + set_open(i, o, "bounds", bounds.clone())?; + } + set_open(i, o, "layout", Value::Object(layout))?; + if matches!(kind, "dialog" | "group" | "panel") { + let kids = list(i, &[], false)?; + set_slot(i, o, KIDS, Value::Object(kids))?; + let children = list(i, &[], true)?; + set_open(i, o, "children", Value::Object(children))?; + set_open(i, o, "orientation", Value::str(if kind == "group" { "row" } else { "column" }))?; + set_open(i, o, "alignChildren", Value::str("center"))?; + set_open(i, o, "spacing", Value::Number(10.0))?; + set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?; + } + Ok(o) +} + +/// `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(); + if lower == "palette" || lower == "window" { + return Err(error(i, &format!("Window: a window of type {lower} is not available yet; use dialog"))); + } + if lower != "dialog" { + return Err(error(i, "Window: the type must be dialog, palette or window")); + } + let proto = classes(i)?.window_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let o = 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))?; + Ok(Value::Object(o)) + })(); + i.temp_roots.truncate(mark); + r +} + +fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let n = i.to_number(v)?; + if !n.is_finite() { + return Err(range(i, &format!("{what} is not a finite number"))); + } + Ok(n) +} + +/// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. +fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "add")?; + let ty = i.to_str(&arg(args, 0))?.to_rust_string(); + if kind == "dropdownlist" || kind == "listbox" { + if ty.to_lowercase() != "item" { + return Err(error(i, "add: a list holds only items")); + } + return add_item(i, o, &arg(args, 1)); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + 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 ty = ty.to_lowercase(); + if LATER.contains(&ty.as_str()) { + return Err(error(i, &format!("add: the control type {ty} is not available yet"))); + } + let Some(&ty) = BUILT.iter().find(|b| **b == ty) else { return Err(error(i, &format!("add: there is no control type {ty}"))) }; + let depth = number_slot(i, o, DEPTH)? as usize + 1; + if depth > MAX_DEPTH { + return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); + } + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a control without its window".into())) }; + let count = number_slot(i, win, COUNT)?; + if count as usize >= MAX_CONTROLS { + return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let props = arg(args, 3); + let list_kind = ty == "dropdownlist" || ty == "listbox"; + if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { + return Err(error(i, "add: a list box that selects several items is not available yet")); + } + let proto = classes(i)?.control_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() }; + let text = if list_kind || matches!(ty, "slider" | "progressbar") { Value::Undefined } else { arg(args, 2) }; + let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?; + match ty { + "checkbox" | "radiobutton" => set_open(i, c, "value", Value::Bool(false))?, + "slider" | "progressbar" => { + let (value, min, max) = + if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) }; + let given = |v: &Value| !matches!(v, Value::Undefined); + let value = if given(&value) { number_arg(i, &value, "add: the value")? } else { 0.0 }; + let min = if given(&min) { number_arg(i, &min, "add: the minimum value")? } else { 0.0 }; + let max = if given(&max) { number_arg(i, &max, "add: the maximum value")? } else { 100.0 }; + set_open(i, c, "minvalue", Value::Number(min))?; + set_open(i, c, "maxvalue", Value::Number(max))?; + set_open(i, c, "value", Value::Number(value))?; + } + "dropdownlist" | "listbox" => { + let kept = list(i, &[], false)?; + set_slot(i, c, ITEMS, Value::Object(kept))?; + set_slot(i, c, SELECTION, Value::Number(-1.0))?; + let items = list(i, &[], true)?; + set_open(i, c, "items", Value::Object(items))?; + let cl = classes(i)?; + i.define(c, key("selection"), Prop::Accessor { get: Some(cl.selection_get), set: Some(cl.selection_set), flags: ENUMERABLE })?; + } + _ => {} + } + if list_kind { + match arg(args, 2) { + Value::Undefined | Value::Null => {} + Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { + for item in list_values(i, a)? { + add_item(i, c, &item)?; + } + } + _ => return Err(i.type_error("add: give a list's items as an array")), + } + } + append(i, o, KIDS, "children", Value::Object(c))?; + set_slot(i, win, COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(c)) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Adds an item with `text` to the list `o`. +fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + if count as usize >= MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let text = text_arg(i, text)?; + let proto = classes(i)?.item_proto; + i.rooted(std::slice::from_ref(&text), |i| { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(item)], |i| { + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + append(i, o, ITEMS, "items", Value::Object(item))?; + set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0))?; + Ok(Value::Object(item)) + }) + }) +} + +fn list_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dropdownlist" || kind == "listbox" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a list"))), + } +} + +fn items_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, ITEMS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +fn selection_index(i: &Interp, o: ObjId) -> JsResult> { + let n = number_slot(i, o, SELECTION)?; + Ok((n >= 0.0).then_some(n as usize)) +} + +fn selection_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + Ok(selection_index(i, o)?.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +fn selection_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "selection")?; + let items = items_of(i, o)?; + let v = arg(args, 0); + let n = match &v { + Value::Undefined | Value::Null => -1.0, + Value::Number(n) if n.fract() == 0.0 && *n >= 0.0 && (*n as usize) < items.len() => *n, + Value::Number(n) => return Err(range(i, &format!("selection: the list has no item {n}"))), + v => match items.iter().position(|item| same(item, v)) { + Some(n) => n as f64, + None => return Err(i.type_error("selection: give an item of this list, its index or null")), + }, + }; + set_slot(i, o, SELECTION, Value::Number(n))?; + Ok(Value::Undefined) +} + +/// The list an item belongs to and its index there. +fn item_place(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, Option)> { + let list = match this.as_object() { + Some(o) => object_slot(i, o, LIST)?, + None => None, + }; + let Some(list) = list else { return Err(i.type_error(&format!("{what}: this is not a list item"))) }; + let index = items_of(i, list)?.iter().position(|item| same(item, this)); + Ok((list, index)) +} + +fn item_index(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (_, index) = item_place(i, &this, "index")?; + Ok(Value::Number(index.map_or(-1.0, |n| n as f64))) +} + +fn item_selected_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + Ok(Value::Bool(index.is_some() && selection_index(i, list)? == index)) +} + +fn item_selected_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (list, index) = item_place(i, &this, "selected")?; + let Some(index) = index else { return Ok(Value::Undefined) }; + if arg(args, 0).truthy() { + set_slot(i, list, SELECTION, Value::Number(index as f64))?; + } else if selection_index(i, list)? == Some(index) { + set_slot(i, list, SELECTION, Value::Number(-1.0))?; + } + Ok(Value::Undefined) +} + +fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + item_place(i, &this, "toString")?; + let text = i.get_value(&this, &key("text"))?; + Ok(Value::String(i.to_str(&text)?)) +} + +/// `list.removeAll()`. +fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "removeAll")?; + let n = items_of(i, o)?.len() as f64; + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let count = number_slot(i, win, ITEM_COUNT)?; + set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; + let kept = list(i, &[], false)?; + set_slot(i, o, ITEMS, Value::Object(kept))?; + let items = list(i, &[], true)?; + set_open(i, o, "items", Value::Object(items))?; + set_slot(i, o, SELECTION, Value::Number(-1.0))?; + Ok(Value::Undefined) +} + +fn kids_of(i: &Interp, o: ObjId) -> JsResult> { + match object_slot(i, o, KIDS)? { + Some(a) => list_values(i, a), + None => Ok(Vec::new()), + } +} + +/// `findElement(name)`: the first control in the element, in order, whose `name` is `name`. +fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "findElement")?; + let want = i.to_str(&arg(args, 0))?; + let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(c) = v.as_object() else { continue }; + let name = i.get_value(&v, &key("name"))?; + if matches!(&name, Value::String(s) if *s == want) { + return Ok(v); + } + stack.extend(kids_of(i, c)?.into_iter().rev()); + } + Ok(Value::Null) +} + +/// Calls the element's handler `name` when it has one. → its result, or `None` without one. +fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult> { + let f = i.get_value(&Value::Object(o), &key(name))?; + if !i.is_callable(&f) { + return Ok(None); + } + i.call(&f, &Value::Object(o), &[]).map(Some) +} + +/// `notify([event])`: runs the control's `onClick`, `onChange` or `onChanging`. +fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "notify")?; + let event = match arg(args, 0) { + Value::Undefined if matches!(kind.as_str(), "button" | "checkbox" | "radiobutton") => "onClick".to_string(), + Value::Undefined => "onChange".to_string(), + v => i.to_str(&v)?.to_rust_string(), + }; + if !matches!(event.as_str(), "onClick" | "onChange" | "onChanging") { + return Err(error(i, "notify: give onClick, onChange or onChanging")); + } + handler(i, o, &event)?; + Ok(Value::Undefined) +} + +fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "show")?; + i.put(o, key("visible"), Value::Bool(true), true)?; + Ok(Value::Undefined) +} + +fn control_hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "hide")?; + i.put(o, key("visible"), Value::Bool(false), true)?; + Ok(Value::Undefined) +} + +fn nothing(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { + Ok(Value::Undefined) +} + +fn dialog_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { + match kind_of(i, this)? { + Some((o, kind)) if kind == "dialog" => Ok(o), + _ => Err(i.type_error(&format!("{what}: this is not a ScriptUI window"))), + } +} + +/// `close([result])`: closes the dialog that is showing once the running handler returns. +fn close(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = dialog_of(i, &this, "close")?; + let result = match arg(args, 0) { + Value::Undefined => 0.0, + v => number_arg(i, &v, "close: the result")?, + }; + if classes(i)?.showing == Some(o) { + set_slot(i, o, CLOSING, Value::Number(result))?; + } + Ok(Value::Undefined) +} + +/// `hide()`: closes the dialog that is showing with the result 0. +fn hide(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + close(i, this, &[], false) +} + +fn host_fn(i: &mut Interp, name: &str) -> JsResult { + let host = classes(i)?.host; + i.get_value(&Value::Object(host), &key(name)) +} + +fn set_showing(i: &mut Interp, showing: Option) { + if let Some(c) = i.script_ui.as_mut() { + c.showing = showing; + } +} + +/// `show()` on a dialog: gives its description to the host's `open`, then runs it ([`opened`]). +fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { + let win = dialog_of(i, &this, "show")?; + match classes(i)?.showing { + Some(o) if o == win => return Err(error(i, "show: this dialog is already showing")), + Some(_) => return Err(error(i, "show: a dialog cannot open while another dialog is showing")), + None => {} + } + set_showing(i, Some(win)); + set_slot(i, win, CLOSING, Value::Undefined)?; + let described = describe(i, win); + let (desc, nodes, def, cancel) = match described { + Ok(d) => d, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; + let open = host_fn(i, "open")?; + Ok(Pause { + host: open, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: opened, + failed: Some(failed), + }) +} + +/// A host call of `show()` failed, or a handler threw: the dialog is no longer showing. +fn failed(i: &mut Interp, keep: &[Value]) { + let Some(win) = arg(keep, 0).as_object() else { return }; + if classes(i).ok().and_then(|c| c.showing) != Some(win) { + return; + } + set_showing(i, None); + if let Ok(end) = host_fn(i, "end") { + let _ = i.call(&end, &Value::Undefined, &[Value::Number(0.0), Value::Bool(false)]); + } +} + +/// `show()` ends with `result`. +fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { + set_showing(i, None); + set_slot(i, win, CLOSING, Value::Undefined)?; + let end = host_fn(i, "end")?; + i.call(&end, &Value::Undefined, &[Value::Number(result), Value::Bool(true)])?; + Ok(Value::Number(result)) +} + +/// Runs `onClose`. → false when it returned `false`. +fn may_close(i: &mut Interp, win: ObjId) -> JsResult { + Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) +} + +/// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. +fn next(i: &mut Interp, win: ObjId) -> JsResult { + loop { + i.use_fuel()?; + if let Value::Number(result) = slot(i, win, CLOSING)? { + set_slot(i, win, CLOSING, Value::Undefined)?; + if may_close(i, win)? { + return finish(i, win, result); + } + continue; + } + let (desc, nodes, def, cancel) = describe(i, win)?; + let wait = host_fn(i, "wait")?; + i.again = Some(Pause { + host: wait, + args: vec![desc], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + resume: answered, + failed: Some(failed), + }); + return Ok(Value::Undefined); + } +} + +/// Runs `r`; when it fails, the dialog is no longer showing. +fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { + let v = r(i); + if v.is_err() { + failed(i, keep); + } + v +} + +fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult { + guarded(i, keep, |i| { + let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) }; + handler(i, win, "onShow")?; + next(i, win) + }) +} + +/// What the host's `wait` gave: the event, which the dialog takes, and what happens next. +fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + guarded(i, keep, |i| { + let (Some(win), Some(nodes)) = (arg(keep, 0).as_object(), arg(keep, 1).as_object()) else { + return Err(Abrupt::Internal("show lost its dialog".into())); + }; + let Some(ev) = answer.as_object() else { return Err(Abrupt::Internal("the host gave show no event".into())) }; + let event = match slot(i, ev, "event")? { + Value::String(s) => s.to_rust_string(), + _ => String::new(), + }; + if event == "close" { + if may_close(i, win)? { + return finish(i, win, 0.0); + } + return next(i, win); + } + let id = match slot(i, ev, "id")? { + Value::Number(n) if n >= 0.0 && n.fract() == 0.0 => n as usize, + _ => return Err(Abrupt::Internal("the host gave show an event without a control".into())), + }; + let nodes = list_values(i, nodes)?; + let Some((c, kind)) = nodes.get(id).map(|v| kind_of(i, v)).transpose()?.flatten() else { + return Err(Abrupt::Internal("the host gave show an event for a control the dialog does not hold".into())); + }; + let value = slot(i, ev, "value")?; + match event.as_str() { + "click" => { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + let parent = object_slot(i, c, PARENT)?; + for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { + if !same(&other, &Value::Object(c)) + && let Some((o, k)) = kind_of(i, &other)? + && k == "radiobutton" + { + i.put(o, key("value"), Value::Bool(false), true)?; + } + } + i.put(c, key("value"), Value::Bool(true), true)?; + } + if handler(i, c, "onClick")?.is_none() && kind == "button" { + let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); + if is(2) { + set_slot(i, win, CLOSING, Value::Number(1.0))?; + } else if is(3) { + set_slot(i, win, CLOSING, Value::Number(2.0))?; + } + } + } + "change" => { + match kind.as_str() { + "edittext" => { + i.put(c, key("text"), value, true)?; + handler(i, c, "onChanging")?; + } + "slider" => { + i.put(c, key("value"), value, true)?; + handler(i, c, "onChanging")?; + } + _ => { + let n = match value { + Value::Number(n) => n, + _ => -1.0, + }; + set_slot(i, c, SELECTION, Value::Number(n))?; + } + } + handler(i, c, "onChange")?; + } + _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), + } + next(i, win) + }) +} + +fn text_of(i: &mut Interp, v: &Value, what: &str) -> JsResult { + let s = i.to_str(v)?; + let text = if s.len() > MAX_TEXT_BYTES { None } else { Some(s.to_rust_string()) }; + match text { + Some(t) if t.len() <= MAX_TEXT_BYTES => Ok(t), + _ => Err(range(i, &format!("show: {what} is longer than 16 KiB"))), + } +} + +fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + i.get_value(&Value::Object(o), &key(name)) +} + +fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?)) +} + +/// An alignment: a name, or an array of a horizontal and a vertical name; `null` when not set. +fn alignment(i: &mut Interp, v: &Value) -> JsResult { + match v { + Value::Undefined | Value::Null => Ok(Data::Null), + Value::Object(a) if matches!(i.object(*a)?.class, Class::Array { .. }) => { + let mut out = Vec::new(); + for n in 0..2 { + let part = i.get_value(v, &index_key(n))?; + out.push(Data::String(text_of(i, &part, "an alignment")?.to_lowercase())); + } + Ok(Data::Array(out)) + } + v => Ok(Data::String(text_of(i, v, "an alignment")?.to_lowercase())), + } +} + +/// Numbers read from `v`'s indices, or else from its properties `names`. +fn numbers(i: &mut Interp, v: &Value, names: &[&str], what: &str) -> JsResult { + let Some(o) = v.as_object() else { + if matches!(v, Value::Undefined | Value::Null) { + return Ok(Data::Null); + } + return Err(i.type_error(&format!("show: give {what} as an array or an object"))); + }; + let array = matches!(i.object(o)?.class, Class::Array { .. }); + let mut out = Vec::new(); + for (n, name) in names.iter().enumerate() { + let part = if array { i.get_value(v, &index_key(n as u32))? } else { i.get_value(v, &key(name))? }; + out.push(Data::Number(number_arg(i, &part, &format!("show: {what}"))?)); + } + Ok(Data::Array(out)) +} + +/// Bounds as `[left, top, right, bottom]`: from an array, from `x`, `y`, `width` and `height`, or +/// from `left`, `top`, `right` and `bottom`. +fn bounds(i: &mut Interp, v: &Value) -> JsResult { + if let Some(o) = v.as_object() + && !matches!(i.object(o)?.class, Class::Array { .. }) + && !matches!(i.get_value(v, &key("width"))?, Value::Undefined) + { + let Data::Array(xywh) = numbers(i, v, &["x", "y", "width", "height"], "bounds")? else { return Ok(Data::Null) }; + let n = |k: usize| match xywh.get(k) { + Some(Data::Number(n)) => *n, + _ => 0.0, + }; + return Ok(Data::Array(vec![Data::Number(n(0)), Data::Number(n(1)), Data::Number(n(0) + n(2)), Data::Number(n(1) + n(3))])); + } + numbers(i, v, &["left", "top", "right", "bottom"], "bounds") +} + +fn margins(i: &mut Interp, v: &Value) -> JsResult { + if v.as_object().is_some() { + return numbers(i, v, &["left", "top", "right", "bottom"], "margins"); + } + let m = number_arg(i, v, "show: margins")?; + Ok(Data::Array(vec![Data::Number(m); 4])) +} + +/// The dialog's description: its elements in order, each after the container that holds it, as +/// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of +/// its default and cancel elements (-1 for none). +fn describe(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mark = i.temp_roots.len(); + let r = describe_rooted(i, win); + i.temp_roots.truncate(mark); + r +} + +fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { + let mut order: Vec<(ObjId, String, f64)> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; + while let Some((v, parent, depth)) = stack.pop() { + i.use_fuel()?; + let Some((o, kind)) = kind_of(i, &v)? else { return Err(i.type_error("show: the dialog holds something that is not a control")) }; + if !seen.insert(o) { + return Err(i.type_error("show: a control appears twice in the dialog")); + } + if order.len() > MAX_CONTROLS { + return Err(range(i, &format!("show: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + if depth > MAX_DEPTH { + return Err(range(i, &format!("show: controls can be nested at most {MAX_DEPTH} deep"))); + } + let index = order.len() as f64; + order.push((o, kind, parent)); + for kid in kids_of(i, o)?.into_iter().rev() { + stack.push((kid, index, depth + 1)); + } + } + let objects: Vec = order.iter().map(|(o, ..)| Value::Object(*o)).collect(); + i.temp_roots.extend(objects.iter().cloned()); + let mut nodes = Vec::with_capacity(order.len()); + let mut names = Vec::with_capacity(order.len()); + let mut items_total = 0usize; + for (o, kind, parent) in &order { + let o = *o; + let name_v = get(i, o, "name")?; + let name = text_of(i, &name_v, "a control's name")?; + let text_v = get(i, o, "text")?; + let text = text_of(i, &text_v, "a control's text")?; + let mut d: Vec<(String, Data)> = vec![ + ("kind".into(), Data::String(kind.clone())), + ("parent".into(), Data::Number(*parent)), + ("name".into(), Data::String(name.clone())), + ("text".into(), Data::String(text.clone())), + ]; + names.push((kind.clone(), name, text)); + let enabled = get(i, o, "enabled")?.truthy(); + let visible = get(i, o, "visible")?.truthy(); + d.push(("enabled".into(), Data::Bool(enabled))); + d.push(("visible".into(), Data::Bool(visible))); + let b = get(i, o, "bounds")?; + d.push(("bounds".into(), bounds(i, &b)?)); + let size = get(i, o, "preferredSize")?; + d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); + let a = get(i, o, "alignment")?; + d.push(("alignment".into(), alignment(i, &a)?)); + if matches!(kind.as_str(), "dialog" | "group" | "panel") { + let orientation = get(i, o, "orientation")?; + d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); + let ac = get(i, o, "alignChildren")?; + d.push(("alignChildren".into(), alignment(i, &ac)?)); + d.push(("spacing".into(), number_of(i, o, "spacing")?)); + let m = get(i, o, "margins")?; + d.push(("margins".into(), margins(i, &m)?)); + } + match kind.as_str() { + "checkbox" | "radiobutton" => { + let on = get(i, o, "value")?.truthy(); + d.push(("value".into(), Data::Bool(on))); + } + "slider" | "progressbar" => { + d.push(("value".into(), number_of(i, o, "value")?)); + d.push(("minvalue".into(), number_of(i, o, "minvalue")?)); + d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?)); + } + "edittext" => { + let props = get(i, o, "properties")?; + let (multiline, readonly) = match props { + Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), + _ => (false, false), + }; + d.push(("multiline".into(), Data::Bool(multiline))); + d.push(("readonly".into(), Data::Bool(readonly))); + } + "dropdownlist" | "listbox" => { + let items = items_of(i, o)?; + items_total = items_total.saturating_add(items.len()); + if items_total > MAX_ITEMS { + return Err(range(i, &format!("show: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let mut texts = Vec::with_capacity(items.len()); + for item in &items { + let t = i.get_value(item, &key("text"))?; + texts.push(Data::String(text_of(i, &t, "a list item's text")?)); + } + d.push(("items".into(), Data::Array(texts))); + let sel = selection_index(i, o)?.filter(|n| *n < items.len()); + d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); + } + _ => {} + } + nodes.push(Data::Object(d)); + } + let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { + let given = get(i, win, name)?; + if let Some(n) = objects.iter().position(|o| same(o, &given)) { + return Ok(n as f64); + } + if !matches!(given, Value::Undefined | Value::Null) { + return Ok(-1.0); + } + let button = |by_name: bool| names.iter().position(|(k, n, t)| k == "button" && (if by_name { n } else { t }).to_lowercase() == word); + Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) + }; + let def = target(i, "defaultElement", "ok")?; + let cancel = target(i, "cancelElement", "cancel")?; + let desc = Data::Object(vec![ + ("nodes".into(), Data::Array(nodes)), + ("defaultElement".into(), Data::Number(def)), + ("cancelElement".into(), Data::Number(cancel)), + ]); + let desc = i.write_data(desc, 0, true)?; + i.temp_roots.push(desc.clone()); + let kept = list(i, &objects, false)?; + Ok((desc, kept, def, cancel)) +} + +/// Adds `Window`, its prototype's methods, and the host functions in `items`. +pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResult<()> { + let host = i.host_object("Window", items)?; + let object_proto = i.intrinsics.object_proto; + i.rooted(&[Value::Object(host)], |i| { + i.reserve_heap(OBJECT_BYTES.saturating_mul(4))?; + let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(window_proto)); + let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(control_proto)); + let item_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(item_proto)); + let layout = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(layout)); + let selection_get = native(i, "selection", selection_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_get)); + let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(selection_set)); + i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; + constructor(i, "Window", window, window_proto)?; + method(i, window_proto, "add", add, 4)?; + method(i, window_proto, "findElement", find_element, 1)?; + method(i, window_proto, "close", close, 1)?; + method(i, window_proto, "hide", hide, 0)?; + method(i, window_proto, "center", nothing, 1)?; + pausable_method(i, window_proto, "show", show, 0)?; + method(i, control_proto, "add", add, 4)?; + method(i, control_proto, "findElement", find_element, 1)?; + method(i, control_proto, "removeAll", remove_all, 0)?; + method(i, control_proto, "notify", notify, 1)?; + method(i, control_proto, "show", control_show, 0)?; + method(i, control_proto, "hide", control_hide, 0)?; + method(i, item_proto, "toString", item_to_string, 0)?; + let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; + i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; + let get = native(i, "selected", item_selected_get, 0, NativeKind::Plain, false)?; + let set = native(i, "selected", item_selected_set, 1, NativeKind::Plain, false)?; + i.define(item_proto, key("selected"), Prop::Accessor { get: Some(get), set: Some(set), flags: 0 })?; + method(i, layout, "layout", nothing, 1)?; + method(i, layout, "resize", nothing, 0)?; + i.object_mut(layout)?.extensible = false; + Ok(()) + }) +} diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs new file mode 100644 index 0000000000..18067d6375 --- /dev/null +++ b/crates/js/src/scriptui_tests.rs @@ -0,0 +1,309 @@ +//! ScriptUI's `Window`: building a dialog, its description, the events a host gives `show()`, the +//! handlers they run, and the limits on what a dialog may hold. + +use std::cell::RefCell; +use std::collections::VecDeque; +use std::rc::Rc; + +use super::*; + +/// What the host was given: each description, and each `end`'s result and whether it was normal. +#[derive(Default)] +struct Seen { + descriptions: Vec, + ends: Vec<(f64, bool)>, +} + +/// The events `wait` has left to give. +type Queue = Rc>>; + +/// A realm whose `wait` gives the events in `events`, in order, and throws when none is left +/// (or waits, where the run can). +fn realm(events: Vec) -> (Realm, Rc>, Queue) { + let mut r = Realm::new(); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let seen: Rc> = Rc::default(); + let queue = Rc::new(RefCell::new(VecDeque::from(events))); + let can_wait = r.wait_flag(); + let s = seen.clone(); + let open: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + Ok(Data::Undefined) + }); + let s = seen.clone(); + let q = queue.clone(); + let wait: HostFunction = Rc::new(move |args| { + s.borrow_mut().descriptions.push(args.into_iter().next().unwrap_or(Data::Undefined)); + match q.borrow_mut().pop_front() { + Some(e) => Ok(e), + None if can_wait.get() => Err(HostError::Wait), + None => Err(HostError::Error("no event left".into())), + } + }); + let s = seen.clone(); + let end: HostFunction = Rc::new(move |args| { + let n = match args.first() { + Some(Data::Number(n)) => *n, + _ => f64::NAN, + }; + s.borrow_mut().ends.push((n, matches!(args.get(1), Some(Data::Bool(true))))); + Ok(Data::Undefined) + }); + let items = vec![("open".into(), HostItem::Function(open)), ("wait".into(), HostItem::Function(wait)), ("end".into(), HostItem::Function(end))]; + r.define_script_ui(items).unwrap(); + (r, seen, queue) +} + +fn click(id: usize) -> Data { + Data::Object(vec![("event".into(), Data::String("click".into())), ("id".into(), Data::Number(id as f64))]) +} + +fn change(id: usize, value: Data) -> Data { + Data::Object(vec![("event".into(), Data::String("change".into())), ("id".into(), Data::Number(id as f64)), ("value".into(), value)]) +} + +fn close() -> Data { + Data::Object(vec![("event".into(), Data::String("close".into()))]) +} + +fn field<'a>(d: &'a Data, name: &str) -> &'a Data { + match d { + Data::Object(fields) => fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v), + _ => &Data::Undefined, + } +} + +fn nodes(d: &Data) -> Vec { + match field(d, "nodes") { + Data::Array(a) => a.clone(), + _ => Vec::new(), + } +} + +/// Every built control, in the order the description lists them: 0 is the dialog. +const FORM: &str = r#" + var w = new Window("dialog", "Form"); + var g = w.add("group"); + var label = g.add("statictext", undefined, "Name:"); + var name = g.add("edittext", undefined, "first"); + var p = w.add("panel", undefined, "Options"); + var check = p.add("checkbox", undefined, "Bold"); + var r1 = p.add("radiobutton", undefined, "A"); + var r2 = p.add("radiobutton", undefined, "B"); + var drop = p.add("dropdownlist", undefined, ["x", "y", "z"]); + var box = p.add("listbox", undefined, ["one", "two"]); + var slide = p.add("slider", undefined, 5, 0, 10); + var bar = p.add("progressbar", undefined, 3, 10); + var ok = w.add("button", undefined, "OK"); + var cancel = w.add("button", undefined, "Cancel", {name: "cancel"}); +"#; + +#[test] +fn a_dialog_with_each_control_gives_back_the_values_the_person_set() { + let events = vec![ + change(3, Data::String("second".into())), + click(5), + click(6), + click(7), + change(8, Data::Number(2.0)), + change(9, Data::Number(1.0)), + change(10, Data::Number(7.5)), + click(12), + ]; + let (mut r, seen, _) = realm(events); + let source = format!( + "{FORM} var result = w.show(); [result, name.text, check.value, r1.value, r2.value, drop.selection.text, box.selection.index, slide.value, bar.value].join('|')" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("1|second|true|false|true|z|1|7.5|3".into())); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let kinds: Vec = first + .iter() + .map(|n| match field(n, "kind") { + Data::String(s) => s.clone(), + _ => String::new(), + }) + .collect(); + let want = [ + "dialog", + "group", + "statictext", + "edittext", + "panel", + "checkbox", + "radiobutton", + "radiobutton", + "dropdownlist", + "listbox", + "slider", + "progressbar", + "button", + "button", + ]; + assert_eq!(kinds, want); + assert_eq!(field(&first[3], "parent"), &Data::Number(1.0), "the field is in the group"); + assert_eq!(field(&first[8], "items"), &Data::Array(vec![Data::String("x".into()), Data::String("y".into()), Data::String("z".into())])); + assert_eq!(field(&first[10], "maxvalue"), &Data::Number(10.0)); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(12.0), "OK is the default element by its text"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(13.0), "Cancel is the cancel element by its name"); + assert_eq!(seen.ends, vec![(1.0, true)]); +} + +#[test] +fn the_default_and_cancel_buttons_close_with_1_and_2_and_a_close_gives_0() { + for (event, want) in [(click(12), 1.0), (click(13), 2.0), (close(), 0.0)] { + let (mut r, _, _) = realm(vec![event]); + assert_eq!(r.run(&format!("{FORM} w.show()")).unwrap(), JsValue::Number(want)); + } +} + +#[test] +fn a_button_with_a_handler_does_not_close_the_dialog() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + let source = format!("{FORM} var clicks = 0; ok.onClick = function () {{ clicks++; }}; [w.show(), clicks].join()"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("2,1".into())); +} + +#[test] +fn close_gives_its_result_and_on_close_can_keep_the_dialog_open() { + let (mut r, seen, _) = realm(vec![click(5), click(5)]); + let source = format!( + "{FORM} var asked = 0; check.onClick = function () {{ w.close(7); }}; w.onClose = function () {{ asked++; return asked > 1; }}; [w.show(), asked].join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("7,2".into())); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn close_in_on_show_ends_show_without_waiting() { + let (mut r, seen, _) = realm(Vec::new()); + assert_eq!(r.run(&format!("{FORM} w.onShow = function () {{ w.close(4); }}; w.show()")).unwrap(), JsValue::Number(4.0)); + assert_eq!(seen.borrow().descriptions.len(), 1, "only open saw the dialog"); +} + +#[test] +fn handlers_change_other_controls_and_the_next_description_shows_it() { + let (mut r, seen, _) = realm(vec![click(5), click(12)]); + let source = + format!("{FORM} check.onClick = function () {{ name.text = check.value ? 'on' : 'off'; slide.enabled = false; }}; w.show(); name.text"); + assert_eq!(r.run(&source).unwrap(), JsValue::String("on".into())); + let seen = seen.borrow(); + let after = nodes(&seen.descriptions[2]); + assert_eq!(field(&after[3], "text"), &Data::String("on".into())); + assert_eq!(field(&after[10], "enabled"), &Data::Bool(false)); +} + +#[test] +fn on_change_runs_after_on_changing() { + let (mut r, _, _) = realm(vec![change(3, Data::String("x".into())), click(12)]); + let source = format!( + "{FORM} var log = []; name.onChanging = function () {{ log.push('changing ' + name.text); }}; name.onChange = function () {{ log.push('change'); }}; w.show(); log.join()" + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String("changing x,change".into())); +} + +#[test] +fn a_handler_that_loops_ends_the_run_at_its_fuel() { + let (mut r, seen, _) = realm(vec![click(5)]); + r.set_limits(Limits { fuel: 200_000, ..Limits::default() }); + let e = r.run(&format!("{FORM} check.onClick = function () {{ for (;;) {{}} }}; w.show()")).unwrap_err(); + assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}"); + assert_eq!(seen.borrow().ends, vec![(0.0, false)], "show ended without its result"); +} + +#[test] +fn a_dialog_cannot_be_shown_inside_its_own_or_another_show() { + let (mut r, _, _) = realm(vec![click(5), click(12)]); + let source = format!( + "{FORM} var errors = []; check.onClick = function () {{ try {{ w.show(); }} catch (e) {{ errors.push(e.message); }} try {{ new Window('dialog').show(); }} catch (e) {{ errors.push(e.message); }} }}; w.show(); errors.join('|')" + ); + assert_eq!( + r.run(&source).unwrap(), + JsValue::String("show: this dialog is already showing|show: a dialog cannot open while another dialog is showing".into()) + ); +} + +#[test] +fn a_dialog_can_be_shown_again_after_it_closed() { + let (mut r, _, _) = realm(vec![click(12), click(13)]); + assert_eq!(r.run(&format!("{FORM} [w.show(), w.show()].join()")).unwrap(), JsValue::String("1,2".into())); +} + +#[test] +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('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"), + ( + "new Window('dialog').add('listbox', undefined, [], {multiselect: true})", + "add: a list box that selects several items is not available yet", + ), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +#[test] +fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { + let (mut r, _, _) = realm(Vec::new()); + let many = + r.run("var w = new Window('dialog'); try { for (var i = 0; i < 100000; i++) w.add('button'); } catch (e) { [e.name, i].join() }").unwrap(); + assert_eq!(many, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS))); + let deep = + r.run("var c = new Window('dialog'); try { for (var d = 0; d < 1000; d++) c = c.add('group'); } catch (e) { [e.name, d].join() }").unwrap(); + assert_eq!(deep, JsValue::String(format!("RangeError,{}", scriptui::MAX_DEPTH))); + let items = r.run("var l = new Window('dialog').add('dropdownlist'); try { for (var n = 0; n < 5000; n++) l.add('item', n); } catch (e) { [e.name, n].join() }").unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS))); + let long = r + .run("var w = new Window('dialog'); w.add('statictext', undefined, new Array(20000).join('x')); try { w.show(); } catch (e) { e.message }") + .unwrap(); + assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into())); +} + +#[test] +fn a_bounds_value_that_is_not_finite_is_refused_when_shown() { + let (mut r, _, _) = realm(Vec::new()); + let v = r.run("var w = new Window('dialog'); w.add('button', [0, 0, Infinity, 20]); try { w.show(); } catch (e) { e.name }").unwrap(); + assert_eq!(v, JsValue::String("RangeError".into())); +} + +#[test] +fn a_script_cannot_change_a_dialog_s_controls_behind_its_back() { + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + w.children.push(w); w.__vcKids = []; try { w.__vcKids.push(w); } catch (e) {} b.__vcKind = 'dialog'; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); +} + +#[test] +fn a_show_that_waits_resumes_with_the_host_s_answer() { + let (mut r, seen, queue) = realm(Vec::new()); + r.start(&format!("{FORM} check.onClick = function () {{ name.text = 'clicked'; }}; var n = w.show(); n + ':' + name.text")).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits at open's first wait"); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Paused); + assert!(r.waits(), "show waits again after the handler"); + queue.borrow_mut().push_back(click(12)); + r.answer(click(5)).unwrap(); + assert_eq!(r.advance(1_000_000).unwrap(), Progress::Done(JsValue::String("1:clicked".into()))); + assert_eq!(seen.borrow().ends, vec![(1.0, true)]); +} + +#[test] +fn findelement_items_and_selection_follow_the_list() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var d = g.add('dropdownlist', undefined, [], {name: 'pick'}); \ + d.add('item', 'a'); var b = d.add('item', 'b'); d.selection = 1; var s1 = d.selection.text; b.selected = false; \ + var s2 = d.selection; d.selection = 0; d.removeAll(); [w.findElement('pick') === d, s1, s2, d.selection, d.items.length, String(b)].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("true,b,,,0,b".into())); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index a24755ab12..eba418f360 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -131,6 +131,7 @@ pub mod save_swatch_library; pub mod save_symbol_library; pub mod script_check; pub mod script_run; +pub mod script_window; pub mod shape_builder_options; pub(crate) mod shapes; pub mod shortcut_import; @@ -466,6 +467,7 @@ registry! { ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, + ScriptWindow: [script_window::KIND] => script_window::SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, ObjectMosaic: [object_mosaic::KIND] => object_mosaic::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, @@ -776,7 +778,7 @@ pub fn cancel(app: &mut VectorcraftApp) { if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { return; } - if let Some(d) = app.ui.dialog.take() { + if let Some(mut d) = app.ui.dialog.take() { if d.kind == "preferences" { crate::original_editor::cancel(app); } @@ -811,6 +813,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } + if d.kind == script_window::KIND { + script_window::cancel(app, &mut d); + } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. if d.kind == recolor::KIND { @@ -830,6 +835,11 @@ pub fn cancel(app: &mut VectorcraftApp) { let _ = app.session.cancel_interaction(); } app.ui.dialog = parent(&d); + // A script's ScriptUI dialog stays open, with the text typed in its fields, until the + // script closes it or the run no longer waits at it. + if d.kind == script_window::KIND && app.ui.dialog.is_none() && app.session.script_running() { + app.ui.dialog = Some(d); + } } settle(app); } diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index f8baa7b7de..fcf80916ae 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -194,9 +194,10 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result } /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which -/// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. +/// Cancel shows again as it was, with the text typed in a ScriptUI dialog's fields. Any other open +/// dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND || d.kind == super::script_window::KIND); if app.ui.dialog.is_some() { return; } @@ -218,6 +219,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { app.ui.dialog = None; } else if app.session.script_dialog().is_none() && app.session.script_picker().is_none() + && app.session.script_window().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs new file mode 100644 index 0000000000..443f3e96cb --- /dev/null +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -0,0 +1,360 @@ +//! A dialog a script builds with ScriptUI's `new Window("dialog")` and shows with `show()` +//! (kind `scriptWindow`). It draws the controls the running script's dialog holds, at the places +//! the engine laid them out, and gives the script each click and change. +//! +//! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`, +//! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its +//! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or +//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open; an event the +//! dialog cannot take is an error. An edit field gives its text when it loses the keyboard focus, +//! when Enter is pressed in a one-line field, or before a click on another control or a close. Events given in +//! one frame reach the script one at a time, in order. Enter outside a field clicks the default button, +//! and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog when it has +//! none. Stop ends the run and puts back everything it did. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_engine::script::scriptui::UiNode; +use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; + +use super::{DialogAction, DialogSpec}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of a script's ScriptUI dialog. +pub const KIND: &str = "scriptWindow"; + +/// The most of the dialog's content shown at once; a larger dialog scrolls. +const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading, + body_with_actions: Some(body), + confirm, + ok: None, + inputs: |_| &["event", "control", "value"], + min_width: 240.0, + max_width: Some(1000.0), + ..DialogSpec::FORM +}; + +/// Shows the ScriptUI dialog the running script waits at. +pub(crate) fn open(app: &mut VectorcraftApp, w: &ScriptUiDialog) { + app.ui.dialog = Some(Dialog::new(KIND, json!({"title": w.title(), SHOWN_KEY: w.shown}))); +} + +/// The field that holds which `show()` of the run the open dialog is for. +const SHOWN_KEY: &str = "shown"; + +/// Is `d` open for the dialog `w`, and not for one the script showed before it? +pub(crate) fn is_open_for(d: &Dialog, w: &ScriptUiDialog) -> bool { + d.kind == KIND && d.fields.get(SHOWN_KEY).and_then(Value::as_u64) == Some(w.shown) +} + +fn heading(d: &Dialog) -> String { + let title = d.str("title"); + if title.is_empty() { tl!("Script Alert").into() } else { vectorcraft_engine::script::dialogs::shown_text(&title, false) } +} + +fn memory_id() -> egui::Id { + egui::Id::unique("scriptWindow.shown") +} + +/// The dialog to draw: the one the run waits at, or while a handler runs, the one it last waited +/// at, with every control disabled. +fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Option<(Arc, bool)> { + if let Some(w) = app.session.script_window() { + let w = Arc::new(w); + ctx.data_mut(|m| m.insert_temp(memory_id(), w.clone())); + return Some((w, true)); + } + ctx.data(|m| m.get_temp::>(memory_id())).map(|w| (w, false)) +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let Some((w, waiting)) = shown(app, ui.ctx()) else { return DialogAction::None }; + let mut events = Vec::new(); + let (width, height) = w.size(); + let size = egui::vec2(width.max(1.0), height.max(1.0)); + egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { + let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + ui.add_enabled_ui(waiting, |ui| { + for (i, n) in w.nodes.iter().enumerate().skip(1) { + if n.visible + && let Some(e) = control(ui, d, area.min, i, n, w.default_element == Some(i)) + { + events.push(e); + } + } + }); + }); + ui.add_space(12.0); + let mut stop = false; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::left_to_right(egui::Align::Center), |ui| { + stop = widgets::secondary_button(ui, tl!("Stop")).clicked(); + }); + if stop { + app.session.script_request_stop(); + app.ui.dialog = None; + return DialogAction::None; + } + let typing = ui.ctx().memory(|m| m.focused().is_some()); + if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + events.extend(w.default_element.map(UiEvent::Click)); + } + if events.iter().any(|e| matches!(e, UiEvent::Click(_))) { + commit_drafts(&w, d, &mut events); + } + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + queue.extend(events.iter().map(event_fields)); + if !waiting || queue.is_empty() { + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + return DialogAction::None; + } + let next = queue.remove(0); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } + if let Value::Object(fields) = next { + d.fields.extend(fields); + } + DialogAction::Confirm +} + +/// The field that holds the events the person gave in one frame that the script has not had yet; +/// the script takes one event each time it waits. +const QUEUE_KEY: &str = "queued"; + +/// Before a click or a close, gives the script the text typed in each edit field that has not left +/// the field yet, so the handler of a button that closes the dialog, or `onClose`, reads it. +pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) { + let mut changes = Vec::new(); + for (i, n) in w.nodes.iter().enumerate() { + if n.kind != UiKind::EditText || n.readonly || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) { + continue; + } + if let Some(Value::String(text)) = d.fields.remove(&draft_key(i)) + && text != n.text + { + changes.push(UiEvent::Change(i, UiValue::Text(text))); + } + } + let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); + events.sort_by_key(closing); + let at = events.iter().position(closing).unwrap_or(events.len()); + events.splice(at..at, changes); +} + +/// The field that holds an edit field's text while it is typed. +fn draft_key(i: usize) -> String { + format!("text{i}") +} + +/// Draws control `i` at its place from `origin`. → the event it gives. +fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &UiNode, default: bool) -> Option { + let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); + let t = Tokens::get(ui.ctx()); + let mut event = None; + ui.push_id(i, |ui| { + ui.add_enabled_ui(n.enabled, |ui| match n.kind { + UiKind::Dialog | UiKind::Group => {} + UiKind::Panel => { + let frame = rect.shrink(1.0); + let (enabled, name) = (ui.is_enabled(), n.text.clone()); + let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); + ui.painter().rect_stroke(frame, 4.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + if !n.text.is_empty() { + ui.painter().text(frame.min + egui::vec2(8.0, -6.0), egui::Align2::LEFT_TOP, &n.text, egui::FontId::proportional(11.0), t.text); + } + } + UiKind::StaticText => { + ui.put(rect, egui::Label::new(&n.text).wrap()); + } + UiKind::Button => { + let mut button = egui::Button::new(&n.text); + if default { + button = button.fill(t.accent_strong); + } + if ui.put(rect, button).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::CheckBox => { + let mut on = n.checked; + if ui.put(rect, egui::Checkbox::new(&mut on, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::RadioButton => { + if ui.put(rect, egui::RadioButton::new(n.checked, &n.text)).clicked() { + event = Some(UiEvent::Click(i)); + } + } + UiKind::EditText => event = edit(ui, d, rect, i, n), + UiKind::DropDownList => { + let shown = n.selection.and_then(|k| n.items.get(k)).cloned().unwrap_or_default(); + let mut picked = None; + ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { + craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() { + picked = Some(k); + } + } + }); + }); + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + UiKind::ListBox => { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(3.0)), |ui| { + egui::ScrollArea::vertical().id_salt(("script-window-listbox", i)).max_height(rect.height() - 6.0).show(ui, |ui| { + for (k, item) in n.items.iter().enumerate() { + if ui.selectable_label(n.selection == Some(k), item).clicked() && n.selection != Some(k) { + event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); + } + } + }); + }); + } + UiKind::Slider => { + let mut v = n.value; + let r = ui.put(rect, egui::Slider::new(&mut v, n.min..=n.max).show_value(false)); + name_for_screen_readers(ui, &r, n); + if (r.drag_stopped() || (r.changed() && !r.dragged())) && v != n.value { + event = Some(UiEvent::Change(i, UiValue::Number(v))); + } + } + UiKind::ProgressBar => { + let span = n.max - n.min; + let part = if span > 0.0 { ((n.value - n.min) / span) as f32 } else { 0.0 }; + let r = ui.put(rect, egui::ProgressBar::new(part)); + name_for_screen_readers(ui, &r, n); + } + }); + }); + event +} + +/// Screen readers call a control with no visible label of its own (an edit field, a slider or a +/// progress bar) by the name the script gave it, or else a slider or progress bar by its text. +fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode) { + let label = if !n.name.is_empty() { + n.name.clone() + } else if n.kind != UiKind::EditText { + n.text.clone() + } else { + String::new() + }; + if !label.is_empty() { + ui.ctx().accesskit_node_builder(r.id, |node| node.set_label(label)); + } +} + +/// An edit field: its text is kept in the dialog while it is typed and given to the script when +/// the field loses the focus, or at Enter in a one-line field. +fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, i: usize, n: &UiNode) -> Option { + let key = draft_key(i); + let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); + let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; + let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); + name_for_screen_readers(ui, &r, n); + if r.changed() { + d.fields.insert(key.clone(), json!(text)); + } + let entered = !n.multiline && r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if (r.lost_focus() || entered) && text != n.text && !n.readonly { + d.fields.remove(&key); + return Some(UiEvent::Change(i, UiValue::Text(text))); + } + if !r.has_focus() && !r.changed() { + d.fields.remove(&key); + } + None +} + +/// `event` as the dialog's `event`, `control` and `value` fields. +fn event_fields(event: &UiEvent) -> Value { + let (name, control, value) = match event { + UiEvent::Click(i) => ("click", json!(i), Value::Null), + UiEvent::Change(i, UiValue::Text(t)) => ("change", json!(i), json!(t)), + UiEvent::Change(i, UiValue::Number(v)) => ("change", json!(i), json!(v)), + UiEvent::Change(i, UiValue::Index(k)) => ("change", json!(i), json!(k)), + UiEvent::Close => ("close", Value::Null, Value::Null), + }; + json!({"event": name, "control": control, "value": value}) +} + +/// The event in the dialog's fields, for the dialog `w`. +fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { + let control = match d.fields.get("control") { + Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, + Some(Value::String(s)) => { + w.find(s).ok_or_else(|| format!("the dialog has no control named {}", vectorcraft_engine::script::dialogs::cut_to(s, 64)))? + } + _ => 0, + }; + let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); + match (d.str("event").as_str(), d.fields.get("value")) { + ("close", _) => Ok(UiEvent::Close), + ("click", _) => Ok(UiEvent::Click(control)), + ("change", Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), + ("change", Some(Value::Number(v))) if list => match v.as_u64() { + Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX))))), + None => Err("a list's `value` must be an item index or null".into()), + }, + ("change", Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))), + ("change", Some(Value::Null) | None) if list => Ok(UiEvent::Change(control, UiValue::Index(None))), + ("change", _) => Err("a change's `value` must be a string, a number or null".into()), + _ => Err("`event` must be click, change or close".into()), + } +} + +/// Gives the running script the event in the dialog's fields. The dialog stays open for the +/// script's next wait; an event it cannot take is an error. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; + let event = event_of(&w, d)?; + app.session.script_window_answer(event)?; + if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { + for k in ["event", "control", "value"] { + open.fields.remove(k); + } + } + Ok(Value::Null) +} + +/// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog +/// has none or it cannot be clicked, after the text still typed in its fields. Events the script +/// has not had yet go after the ones before them. +pub(super) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) { + let Some(w) = app.session.script_window() else { return }; + let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); + let mut events = vec![click.unwrap_or(UiEvent::Close)]; + commit_drafts(&w, d, &mut events); + let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + let mut events = events.into_iter(); + if queue.is_empty() + && let Some(first) = events.next() + { + let _ = app.session.script_window_answer(first); + } + queue.extend(events.map(|e| event_fields(&e))); + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } +} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index e4271f7926..9d442848ce 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6589,7 +6589,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a confirm's answer, whose `value` must be true or false és la resposta d'un confirm, i el seu `value` ha de ser true o false @msg is longer than 16 KiB ocupa més de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null -@msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window ha de tenir `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps és la resposta d’una finestra, el `value` de la qual ha de ser una llista de passos +@msg has a step {i} that is not a valid click, change or close té un pas {i} que no és un clic, un canvi ni un tancament vàlid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 488df173c3..ee8b68af7d 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9868,7 +9868,9 @@ breakText Glyphs Glyfy @msg more than {MAX_IMPORT} presets více než {MAX_IMPORT} přednastavení @msg moved must be [[x,y]…] moved musí být [[x,y]…] @msg must be an object with `kind` and `value` musí být objekt s `kind` a `value` -@msg must have `kind` alert, confirm or prompt musí mít `kind` alert, confirm nebo prompt +@msg must have `kind` alert, confirm, prompt or window musí mít `kind` alert, confirm, prompt nebo window +@msg is a window's answer, whose `value` must be a list of steps je odpověď okna, jejíž `value` musí být seznam kroků +@msg has a step {i} that is not a valid click, change or close má krok {i}, který není platné kliknutí, změna ani zavření @msg must have exactly `kind` and `value` musí mít právě `kind` a `value` @msg name (a toolbar's name) is required name (název panelu nástrojů) je povinné @msg name (a toolbar's name) must be a string name (název panelu nástrojů) musí být řetězec diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 302ab6aa69..cc03e6ef1b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -233,7 +233,9 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a confirm's answer, whose `value` must be true or false er svaret på en confirm, hvis `value` skal være true eller false @msg is longer than 16 KiB er længere end 16 KiB @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null -@msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window skal have `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps er et vindues svar, hvis `value` skal være en liste over trin +@msg has a step {i} that is not a valid click, change or close har et trin {i}, der ikke er et gyldigt klik, en gyldig ændring eller en gyldig lukning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 9482345f18..e92726501f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8629,7 +8629,9 @@ breakText Glyphs Glyphen @msg missing `picks` `picks` fehlt @msg missing `word` `word` fehlt @msg must be an object with `kind` and `value` muss ein Objekt mit `kind` und `value` sein -@msg must have `kind` alert, confirm or prompt muss `kind` alert, confirm oder prompt haben +@msg must have `kind` alert, confirm, prompt or window muss `kind` alert, confirm, prompt oder window haben +@msg is a window's answer, whose `value` must be a list of steps ist die Antwort auf ein Fenster, deren `value` eine Liste von Schritten sein muss +@msg has a step {i} that is not a valid click, change or close hat einen Schritt {i}, der kein gültiger Klick, keine gültige Änderung und kein gültiges Schließen ist @msg must have exactly `kind` and `value` muss genau `kind` und `value` haben @msg needs a closing quote after the name braucht ein schließendes Anführungszeichen nach dem Namen @msg needs a name braucht einen Namen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 434d0cc0b8..12d3aba3c5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2787,7 +2787,9 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a confirm's answer, whose `value` must be true or false είναι απάντηση σε confirm, οπότε το `value` πρέπει να είναι true ή false @msg is longer than 16 KiB είναι μεγαλύτερο από 16 KiB @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null -@msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt +@msg must have `kind` alert, confirm, prompt or window πρέπει να έχει `kind` alert, confirm, prompt ή window +@msg is a window's answer, whose `value` must be a list of steps είναι απάντηση παραθύρου, της οποίας το `value` πρέπει να είναι λίστα βημάτων +@msg has a step {i} that is not a valid click, change or close έχει ένα βήμα {i} που δεν είναι έγκυρο κλικ, αλλαγή ή κλείσιμο @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου @msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} @msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f83e928e4..c404d6ed6e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5061,7 +5061,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a confirm's answer, whose `value` must be true or false es la respuesta de un confirm, cuyo `value` debe ser true o false @msg is longer than 16 KiB ocupa más de 16 KiB @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null -@msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window debe tener `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps es la respuesta de una ventana, cuyo `value` debe ser una lista de pasos +@msg has a step {i} that is not a valid click, change or close tiene un paso {i} que no es un clic, un cambio ni un cierre válido @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index a4d85b23e8..2ae421c004 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5302,7 +5302,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a confirm's answer, whose `value` must be true or false on confirm-vastaus, joten sen `value`-arvon on oltava true tai false @msg is longer than 16 KiB on pidempi kuin 16 KiB @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null -@msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt +@msg must have `kind` alert, confirm, prompt or window `kind`-arvon on oltava alert, confirm, prompt tai window +@msg is a window's answer, whose `value` must be a list of steps on ikkunan vastaus, jonka `value`-arvon on oltava luettelo vaiheista +@msg has a step {i} that is not a valid click, change or close sisältää vaiheen {i}, joka ei ole kelvollinen napsautus, muutos tai sulkeminen @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8f56486157..aa2a24c90d 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9728,7 +9728,9 @@ breakText Glyphs Glyphes @msg more than {MAX_IMPORT} presets plus de {MAX_IMPORT} paramètres prédéfinis @msg moved must be [[x,y]…] moved doit être [[x,y]…] @msg must be an object with `kind` and `value` doit être un objet avec `kind` et `value` -@msg must have `kind` alert, confirm or prompt doit avoir `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window doit avoir `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps est la réponse d’une fenêtre, dont la `value` doit être une liste d’étapes +@msg has a step {i} that is not a valid click, change or close a une étape {i} qui n’est ni un clic, ni une modification, ni une fermeture valide @msg must have exactly `kind` and `value` doit avoir exactement `kind` et `value` @msg name (a toolbar's name) is required name (le nom d’une barre d’outils) est obligatoire @msg name (a toolbar's name) must be a string name (le nom d’une barre d’outils) doit être une chaîne diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e9509d9202..5bdc231564 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -7736,7 +7736,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a confirm's answer, whose `value` must be true or false यह confirm का उत्तर है, इसलिए इसका `value` true या false होना चाहिए @msg is longer than 16 KiB 16 KiB से लंबा है @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए -@msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए +@msg must have `kind` alert, confirm, prompt or window `kind` alert, confirm, prompt या window होना चाहिए +@msg is a window's answer, whose `value` must be a list of steps एक window का उत्तर है, जिसका `value` चरणों की सूची होना चाहिए +@msg has a step {i} that is not a valid click, change or close में चरण {i} मान्य क्लिक, बदलाव या बंद करना नहीं है @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए @msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 87f050ef0d..af96effe62 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9739,7 +9739,9 @@ breakText Glyphs Glifák @msg more than {MAX_IMPORT} presets több mint {MAX_IMPORT} előbeállítás @msg moved must be [[x,y]…] moved: [[x,y]…] kell @msg must be an object with `kind` and `value` `kind` és `value` kulcsot tartalmazó objektum kell -@msg must have `kind` alert, confirm or prompt a `kind` értéke alert, confirm vagy prompt kell legyen +@msg must have `kind` alert, confirm, prompt or window a `kind` értéke alert, confirm, prompt vagy window kell legyen +@msg is a window's answer, whose `value` must be a list of steps egy ablak válasza, amelynek `value` értéke lépések listája kell legyen +@msg has a step {i} that is not a valid click, change or close {i}. lépése nem érvényes kattintás, módosítás vagy bezárás @msg must have exactly `kind` and `value` pontosan a `kind` és a `value` kulcsot kell tartalmaznia @msg name (a toolbar's name) is required name (egy eszköztár neve): kötelező @msg name (a toolbar's name) must be a string name (egy eszköztár neve): karakterlánc kell diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 924d3d80b5..87d73912db 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -140,7 +140,9 @@ @msg is a confirm's answer, whose `value` must be true or false adalah jawaban confirm, yang `value`-nya harus true atau false @msg is longer than 16 KiB lebih panjang dari 16 KiB @msg is a prompt's answer, whose `value` must be a string or null adalah jawaban prompt, yang `value`-nya harus berupa string atau null -@msg must have `kind` alert, confirm or prompt harus memiliki `kind` alert, confirm, atau prompt +@msg must have `kind` alert, confirm, prompt or window harus memiliki `kind` alert, confirm, prompt, atau window +@msg is a window's answer, whose `value` must be a list of steps adalah jawaban jendela, yang `value`-nya harus berupa daftar langkah +@msg has a step {i} that is not a valid click, change or close memiliki langkah {i} yang bukan klik, perubahan, atau penutupan yang valid @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` hanya untuk proses tanpa orang yang dapat ditanya: di aplikasi, pengguna menjawab setiap dialog @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` harus berupa bilangan bulat dari 1 sampai {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` bersarang lebih dari 64 tingkat diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 5f47e3f117..5aab7c3e3d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8678,7 +8678,9 @@ breakText Glyphs Glifi @msg missing `picks` `picks` mancante @msg missing `word` `word` mancante @msg must be an object with `kind` and `value` deve essere un oggetto con `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve avere `kind` alert, confirm o prompt +@msg must have `kind` alert, confirm, prompt or window deve avere `kind` alert, confirm, prompt o window +@msg is a window's answer, whose `value` must be a list of steps è la risposta di una finestra, il cui `value` deve essere un elenco di passaggi +@msg has a step {i} that is not a valid click, change or close ha un passaggio {i} che non è un clic, una modifica o una chiusura validi @msg must have exactly `kind` and `value` deve avere esattamente `kind` e `value` @msg needs a closing quote after the name richiede una virgoletta di chiusura dopo il nome @msg needs a name richiede un nome diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9a1b5f6354..ef0740a8bb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7495,7 +7495,9 @@ axis Y Axis Y 軸 @msg missing `picks` `picks` がありません @msg missing `word` `word` がありません @msg must be an object with `kind` and `value` には `kind` と `value` を持つオブジェクトを指定してください -@msg must have `kind` alert, confirm or prompt の `kind` には alert、confirm、prompt のいずれかを指定してください +@msg must have `kind` alert, confirm, prompt or window の `kind` には alert、confirm、prompt、window のいずれかを指定してください +@msg is a window's answer, whose `value` must be a list of steps は window の回答で、`value` には手順のリストを指定してください +@msg has a step {i} that is not a valid click, change or close の手順 {i} は有効なクリック、変更、閉じる操作のいずれでもありません @msg must have exactly `kind` and `value` には `kind` と `value` だけを指定してください @msg needs a closing quote after the name 名前の後に閉じ引用符が必要です @msg needs a name 名前が必要です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 8eeacee621..e7223c60c8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1085,7 +1085,9 @@ @msg more than {MAX_IMPORT} presets {MAX_IMPORT}-ზე მეტი პრესეტი @msg moved must be [[x,y]…] moved უნდა იყოს [[x,y]…] @msg must be an object with `kind` and `value` უნდა იყოს ობიექტი `kind`-ით და `value`-თი -@msg must have `kind` alert, confirm or prompt `kind` უნდა იყოს alert, confirm ან prompt +@msg must have `kind` alert, confirm, prompt or window `kind` უნდა იყოს alert, confirm, prompt ან window +@msg is a window's answer, whose `value` must be a list of steps არის ფანჯრის პასუხი, რომლის `value` უნდა იყოს ნაბიჯების სია +@msg has a step {i} that is not a valid click, change or close შეიცავს ნაბიჯს {i}, რომელიც არ არის სწორი დაწკაპუნება, ცვლილება ან დახურვა @msg must have exactly `kind` and `value` უნდა ჰქონდეს ზუსტად `kind` და `value` @msg name (a toolbar's name) is required საჭიროა name (ხელსაწყოთა ზოლის სახელი) @msg name (a toolbar's name) must be a string name (ხელსაწყოთა ზოლის სახელი) უნდა იყოს სტრიქონი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 57e0b8be10..e40e7055a2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9508,7 +9508,9 @@ breakText Glyphs 글리프 @msg more than {MAX_IMPORT} presets 사전 설정이 {MAX_IMPORT}개보다 많습니다 @msg moved must be [[x,y]…] moved는 [[x,y]…]여야 합니다 @msg must be an object with `kind` and `value` `kind`와 `value`가 있는 개체여야 합니다 -@msg must have `kind` alert, confirm or prompt `kind`가 alert, confirm 또는 prompt여야 합니다 +@msg must have `kind` alert, confirm, prompt or window `kind`가 alert, confirm, prompt 또는 window여야 합니다 +@msg is a window's answer, whose `value` must be a list of steps 창의 답이며, `value`는 단계 목록이어야 합니다 +@msg has a step {i} that is not a valid click, change or close 단계 {i}이(가) 올바른 클릭, 변경 또는 닫기가 아닙니다 @msg must have exactly `kind` and `value` `kind`와 `value`만 있어야 합니다 @msg name (a toolbar's name) is required name(도구 막대 이름)이 필요합니다 @msg name (a toolbar's name) must be a string name(도구 막대 이름)은 문자열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 5ed5cdc3e0..d52992f4a9 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7380,7 +7380,9 @@ imageTrace Outline Contour @msg more than {MAX_IMPORT} presets meer dan {MAX_IMPORT} voorinstellingen @msg moved must be [[x,y]…] moved moet [[x,y]…] zijn @msg must be an object with `kind` and `value` moet een object met `kind` en `value` zijn -@msg must have `kind` alert, confirm or prompt moet `kind` alert, confirm of prompt hebben +@msg must have `kind` alert, confirm, prompt or window moet `kind` alert, confirm, prompt of window hebben +@msg is a window's answer, whose `value` must be a list of steps is het antwoord van een venster, waarvan `value` een lijst met stappen moet zijn +@msg has a step {i} that is not a valid click, change or close heeft een stap {i} die geen geldige klik, wijziging of sluiting is @msg must have exactly `kind` and `value` moet precies `kind` en `value` hebben @msg name (a toolbar's name) is required name (de naam van een werkbalk) is vereist @msg name (a toolbar's name) must be a string name (de naam van een werkbalk) moet een string zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 74029133dc..1a2148f0e1 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8882,7 +8882,9 @@ breakText Glyphs Glify @msg missing `picks` brak `picks` @msg missing `word` brak `word` @msg must be an object with `kind` and `value` musi być obiektem z `kind` i `value` -@msg must have `kind` alert, confirm or prompt `kind` musi mieć wartość alert, confirm lub prompt +@msg must have `kind` alert, confirm, prompt or window `kind` musi mieć wartość alert, confirm, prompt lub window +@msg is a window's answer, whose `value` must be a list of steps jest odpowiedzią okna, której `value` musi być listą kroków +@msg has a step {i} that is not a valid click, change or close ma krok {i}, który nie jest prawidłowym kliknięciem, zmianą ani zamknięciem @msg must have exactly `kind` and `value` musi mieć dokładnie `kind` i `value` @msg needs a closing quote after the name wymaga zamykającego cudzysłowu po nazwie @msg needs a name wymaga nazwy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index a1747af0b2..82cdb0a2b2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9930,7 +9930,9 @@ swatch Yellow Green Verde-amarelado @msg more than {MAX_IMPORT} presets mais de {MAX_IMPORT} predefinições @msg moved must be [[x,y]…] moved deve ser [[x,y]…] @msg must be an object with `kind` and `value` deve ser um objeto com `kind` e `value` -@msg must have `kind` alert, confirm or prompt deve ter `kind` alert, confirm ou prompt +@msg must have `kind` alert, confirm, prompt or window deve ter `kind` alert, confirm, prompt ou window +@msg is a window's answer, whose `value` must be a list of steps é a resposta de uma janela, cujo `value` deve ser uma lista de etapas +@msg has a step {i} that is not a valid click, change or close tem uma etapa {i} que não é um clique, uma alteração nem um fechamento válido @msg must have exactly `kind` and `value` deve ter exatamente `kind` e `value` @msg name (a toolbar's name) is required name (o nome de uma barra de ferramentas) é obrigatório @msg name (a toolbar's name) must be a string name (o nome de uma barra de ferramentas) deve ser uma string diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ca0c8d5145..6f351f1d76 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -5083,7 +5083,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a confirm's answer, whose `value` must be true or false является ответом на confirm, поэтому его `value` должно быть true или false @msg is longer than 16 KiB длиннее 16 КиБ @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null -@msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt +@msg must have `kind` alert, confirm, prompt or window должен иметь `kind` alert, confirm, prompt или window +@msg is a window's answer, whose `value` must be a list of steps является ответом окна, `value` которого должен быть списком шагов +@msg has a step {i} that is not a valid click, change or close содержит шаг {i}, который не является допустимым щелчком, изменением или закрытием @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index c26474cf93..532e1ade50 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4959,7 +4959,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a confirm's answer, whose `value` must be true or false är svaret på en confirm, vars `value` måste vara true eller false @msg is longer than 16 KiB är längre än 16 KiB @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null -@msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt +@msg must have `kind` alert, confirm, prompt or window måste ha `kind` alert, confirm, prompt eller window +@msg is a window's answer, whose `value` must be a list of steps är ett fönsters svar, vars `value` måste vara en lista med steg +@msg has a step {i} that is not a valid click, change or close har ett steg {i} som inte är ett giltigt klick, en giltig ändring eller en giltig stängning @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 2ca2c76e03..daba147a6d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -5774,12 +5774,14 @@ fn script_answers_errors_are_translated() { "is a confirm's answer, whose `value` must be true or false", "is longer than 16 KiB", "is a prompt's answer, whose `value` must be a string or null", - "must have `kind` alert, confirm or prompt", + "must have `kind` alert, confirm, prompt or window", + "is a window's answer, whose `value` must be a list of steps", ]; let in_app = "`answers` is only for a run with nobody to ask: in the app, the person answers each dialog"; let lists = ["`answers` must be a list of answers", "`answers` has more than {MAX_ANSWERS} answers", "`answers` is larger than 1 MiB"]; + let step = "has a step {i} that is not a valid click, change or close"; let scanned = message_literals(); - for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app]) { + for template in reasons.into_iter().chain(lists).chain(["`answers[{i}]` {e}", in_app, step]) { assert!(scanned.contains(template), "{template}"); } let ok = json!({"kind": "alert", "value": "ok"}); @@ -5791,6 +5793,7 @@ fn script_answers_errors_are_translated() { json!({"kind": "prompt", "value": "x".repeat(16 * 1024 + 1)}), json!({"kind": "prompt", "value": 1}), json!({"kind": "beep", "value": 1}), + json!({"kind": "window", "value": "click"}), ]; let run = |s: &mut Session, answers: Value| s.execute("script.run", &json!({"source": "1", "answers": answers})).unwrap_err(); let mut s = Session::new(); @@ -5807,6 +5810,8 @@ fn script_answers_errors_are_translated() { errors.push((run(&mut s, json!(vec![ok.clone(); 10_001])), "`answers` has more than 10000 answers".to_string(), None)); let long = json!({"kind": "prompt", "value": "x".repeat(16 * 1024)}); errors.push((run(&mut s, json!(vec![long; 70])), lists[2].to_string(), None)); + let steps = json!([{"kind": "window", "value": [{"event": "close"}, {"event": "tap"}]}]); + errors.push((run(&mut s, steps), "`answers[0]` has a step 1 that is not a valid click, change or close".to_string(), None)); s.script_frames = true; errors.push((run(&mut s, json!([ok])), in_app.to_string(), None)); for (e, want, reason) in &errors { @@ -5826,8 +5831,8 @@ fn script_answers_errors_are_translated() { let numbers: Vec<&str> = want.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty()).collect(); let names = ["`answers", "`kind`", "`value`", "true", "false", "null"]; assert!(numbers.iter().chain(&names).all(|n| !want.contains(n) || shown.contains(n)), "{code}: {shown}"); - if want.ends_with("alert, confirm or prompt") { - assert!(["alert", "confirm", "prompt"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); + if want.ends_with("alert, confirm, prompt or window") { + assert!(["alert", "confirm", "prompt", "window"].iter().all(|k| shown.contains(k)), "{code}: {shown}"); } } } diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 82186ebcdd..22568734be 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7871,7 +7871,9 @@ axis Y Axis Y ekseni @msg missing `picks` `picks` eksik @msg missing `word` `word` eksik @msg must be an object with `kind` and `value` `kind` ve `value` içeren bir nesne olmalıdır -@msg must have `kind` alert, confirm or prompt `kind` değeri alert, confirm veya prompt olmalıdır +@msg must have `kind` alert, confirm, prompt or window `kind` değeri alert, confirm, prompt veya window olmalıdır +@msg is a window's answer, whose `value` must be a list of steps bir pencerenin yanıtıdır ve `value` değeri bir adım listesi olmalıdır +@msg has a step {i} that is not a valid click, change or close içindeki {i}. adım geçerli bir tıklama, değişiklik veya kapatma değil @msg must have exactly `kind` and `value` yalnızca `kind` ve `value` içermelidir @msg needs a closing quote after the name addan sonra bir kapanış tırnağı gerekir @msg needs a name bir ad gerekir diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index de3329ef10..1c44123d26 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9509,7 +9509,9 @@ breakText Glyphs Гліфи @msg more than {MAX_IMPORT} presets понад {MAX_IMPORT} наборів @msg moved must be [[x,y]…] moved має бути [[x,y]…] @msg must be an object with `kind` and `value` має бути об’єктом із `kind` і `value` -@msg must have `kind` alert, confirm or prompt повинен мати `kind` зі значенням alert, confirm або prompt +@msg must have `kind` alert, confirm, prompt or window повинен мати `kind` зі значенням alert, confirm, prompt або window +@msg is a window's answer, whose `value` must be a list of steps є відповіддю вікна, `value` якої має бути списком кроків +@msg has a step {i} that is not a valid click, change or close має крок {i}, який не є допустимим клацанням, зміною або закриттям @msg must have exactly `kind` and `value` повинен мати рівно `kind` і `value` @msg name (a toolbar's name) is required name (ім’я панелі інструментів) є обов’язковим @msg name (a toolbar's name) must be a string name (ім’я панелі інструментів) має бути рядком diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 675143a8d6..2758865931 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5582,7 +5582,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a confirm's answer, whose `value` must be true or false là câu trả lời cho confirm, nên `value` phải là true hoặc false @msg is longer than 16 KiB dài hơn 16 KiB @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null -@msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt +@msg must have `kind` alert, confirm, prompt or window phải có `kind` là alert, confirm, prompt hoặc window +@msg is a window's answer, whose `value` must be a list of steps là câu trả lời của một cửa sổ, có `value` phải là danh sách các bước +@msg has a step {i} that is not a valid click, change or close có bước {i} không phải là một lần nhấp, thay đổi hoặc đóng hợp lệ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại @msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} @msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 57f6a4403b..dac4499a58 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8888,7 +8888,9 @@ breakText Glyphs 字形 @msg missing `picks` 缺少 `picks` @msg missing `word` 缺少 `word` @msg must be an object with `kind` and `value` 必须是包含 `kind` 和 `value` 的对象 -@msg must have `kind` alert, confirm or prompt `kind` 必须是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必须是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是窗口的回答,其 `value` 必须是步骤列表 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的点击、更改或关闭 @msg must have exactly `kind` and `value` 必须只包含 `kind` 和 `value` @msg needs a closing quote after the name 名称后需要右引号 @msg needs a name 需要名称 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 9834c17ea6..bf6ee14a81 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8824,7 +8824,9 @@ breakText Glyphs 字符 @msg missing `picks` 未提供 `picks` @msg missing `word` 未提供 `word` @msg must be an object with `kind` and `value` 必須是包含 `kind` 和 `value` 的物件 -@msg must have `kind` alert, confirm or prompt `kind` 必須是 alert、confirm 或 prompt +@msg must have `kind` alert, confirm, prompt or window `kind` 必須是 alert、confirm、prompt 或 window +@msg is a window's answer, whose `value` must be a list of steps 是視窗的回答,其 `value` 必須是步驟清單 +@msg has a step {i} that is not a valid click, change or close 的第 {i} 步不是有效的點按、變更或關閉 @msg must have exactly `kind` and `value` 只能有 `kind` 和 `value` @msg needs a closing quote after the name 名稱之後需要結尾引號 @msg needs a name 需要名稱 diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..f3d5f14912 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,12 +1,13 @@ //! A running script, advanced one slice per frame: `script.run` starts it and [`poll`] takes it to //! its end, while the app goes on drawing the documents as they were before the run. The status bar //! shows it with a Stop button; a run that has added a great deal, or that opened a dialog with -//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. +//! `alert`, `confirm`, `prompt`, a ScriptUI dialog's `show()` or a `File` or `Folder` file dialog, +//! waits for the person's answer. use serde_json::json; use crate::VectorcraftApp; -use crate::dialogs::script_run; +use crate::dialogs::{script_run, script_window}; use crate::state::Dialog; /// Advances the running script by one slice, or asks what its growth needs asked. @@ -29,7 +30,7 @@ pub fn poll(app: &mut VectorcraftApp) { if cursor_settings != (app.session.caps_lock, app.session.prefs.use_precise_cursors) { app.canvas.hover_cursor = None; } - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND) { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::GROWTH_KIND || d.kind == script_window::KIND) { app.ui.dialog = None; } script_run::settle_close(app); @@ -49,6 +50,14 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + // A ScriptUI dialog the script closed gives way to the file dialog or dialog function it waits + // at now. + if app.session.script_window().is_none() + && (app.session.script_picker().is_some() || app.session.script_dialog().is_some()) + && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) + { + app.ui.dialog = None; + } if let Some(picker) = app.session.script_picker() { if app.ui.dialog.is_none() { script_run::open_picker(app, &picker); @@ -68,6 +77,21 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { app.ui.dialog = None; } + if let Some(window) = app.session.script_window() { + // A dialog the script showed after closing the one that is open replaces it. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND && !script_window::is_open_for(d, &window)) { + app.ui.dialog = None; + } + if app.ui.dialog.is_none() { + script_window::open(app, &window); + } + return true; + } + // While a handler runs, the ScriptUI dialog stays open, until the run ends or asks about its + // growth. + if app.session.script_waiting() && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) { + app.ui.dialog = None; + } if app.session.script_waiting() { if app.ui.dialog.is_none() { app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e0619ddaf7..ac934f6d18 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -43,6 +43,7 @@ mod screenshots; mod script_check; mod script_dialogs; mod script_run; +mod script_window; mod scripts_menu; mod scrub; mod selectall; diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs new file mode 100644 index 0000000000..1cc241b049 --- /dev/null +++ b/crates/ui-egui/src/tests/script_window.rs @@ -0,0 +1,273 @@ +//! A script's ScriptUI dialog in the app: it opens when `show()` waits, takes clicks and changes +//! from the person and from `ui.dialog.confirm`, Enter and Escape, Stop, and quitting while it +//! waits. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; +use vectorcraft_engine::script::{UiEvent, UiValue}; + +use crate::dialogs::script_run::CLOSE_KIND; +use crate::dialogs::script_window::{self, KIND}; +use crate::{VectorcraftApp, dialogs, menus, script_runs}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + app +} + +fn objects(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().doc.layers.iter().map(|l| l.children().map_or(0, Vec::len)).sum() +} + +const DRAW: &str = "vc.run('shape.rectangle', {x:0,y:0,width:10,height:10});"; + +const FORM: &str = "var w = new Window('dialog', 'Make'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var bold = w.add('checkbox', undefined, 'Bold'); bold.onClick = function () { name.text = 'clicked'; }; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel');"; + +fn start(app: &mut VectorcraftApp, source: &str) { + menus::run_ui_command(app, "ui.runScript", &json!({"source": source, "name": "w.js"})).unwrap().unwrap(); +} + +/// Polls the run until it ends, or until its ScriptUI dialog is open and it waits (true). +fn until_window(app: &mut VectorcraftApp) -> bool { + for _ in 0..10_000 { + if !app.session.script_running() { + return false; + } + script_runs::poll(app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == KIND) && app.session.script_window().is_some() { + return true; + } + } + panic!("the script neither ended nor opened its dialog"); +} + +/// Gives the dialog an event as `ui.dialog.set` and `ui.dialog.confirm` do. +fn give(app: &mut VectorcraftApp, event: Value) -> Result { + let d = app.ui.dialog.as_mut().unwrap(); + for (k, v) in event.as_object().unwrap() { + d.fields.insert(k.clone(), v.clone()); + } + dialogs::confirm(app) +} + +thread_local! { + static CTX: egui::Context = { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx + }; +} + +/// One headless frame of the dialog layer and the shortcuts. Each key pressed in it is let go in a +/// second frame. +fn frame(app: &mut VectorcraftApp, events: Vec) { + let ctx = CTX.with(Clone::clone); + let released: Vec = events + .iter() + .filter_map(|e| match e { + egui::Event::Key { key, physical_key, modifiers, pressed: true, .. } => { + Some(egui::Event::Key { key: *key, physical_key: *physical_key, pressed: false, repeat: false, modifiers: *modifiers }) + } + _ => None, + }) + .collect(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let pressed = !released.is_empty(); + for events in std::iter::once(events).chain(pressed.then_some(released)) { + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + dialogs::show(app, ui.ctx()); + }); + out.textures_delta.clear(); + } +} + +fn key(k: egui::Key) -> egui::Event { + egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() } +} + +fn log(app: &VectorcraftApp) -> Value { + app.session.script_report().unwrap()["log"].clone() +} + +#[test] +fn the_dialog_takes_events_and_stays_open_while_its_handlers_run() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} var r = w.show(); vc.log([r, name.text, bold.value]);")); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "Make"); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND), "the dialog stays open for the next wait"); + assert!(until_window(&mut app)); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "clicked", "the handler changed the field"); + assert!(give(&mut app, json!({"event": "click", "control": 99})).is_err()); + assert!(give(&mut app, json!({"event": "wave"})).is_err()); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann", true]])); + assert!(app.ui.dialog.is_none()); + assert_eq!(objects(&app), 1); +} + +#[test] +fn text_still_in_a_field_reaches_the_script_before_a_click() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!("Ann")); + let mut events = vec![UiEvent::Click(3)]; + script_window::commit_drafts(&w, d, &mut events); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("Ann".into())), UiEvent::Click(3)]); + assert!(!d.fields.contains_key("text1"), "the text is given once"); + d.fields.insert("queued".into(), json!([{"event": "change", "control": 1, "value": "Ann"}, {"event": "click", "control": 3, "value": null}])); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the change and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann"]])); +} + +#[test] +fn escape_clicks_the_cancel_button_and_closes_a_dialog_without_one() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + frame(&mut app, vec![key(egui::Key::Escape)]); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([2])); + start(&mut app, "var w = new Window('dialog'); w.add('statictext', undefined, 'Hi'); vc.log(w.show());"); + assert!(until_window(&mut app)); + dialogs::cancel(&mut app); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn escape_keeps_the_dialog_open_until_the_script_closes_it() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.onClose = function () { return false; }; vc.log(w.show());"); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.fields["queued"], json!([{"event": "close", "control": null, "value": null}]), "with the close after the typed text"); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[1].text, "typed"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "onClose kept the dialog open"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued")); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +fn start_typing(app: &mut VectorcraftApp) { + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); +} + +#[test] +fn escape_gives_the_typed_text_before_the_cancel_click() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'old'); var c = w.add('button', undefined, 'Cancel'); \ + c.onClick = function () { vc.log(e.text); w.close(2); }; vc.log(w.show());", + ); + assert!(until_window(&mut app)); + start_typing(&mut app); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the script takes the text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on Cancel closes the dialog"); + assert_eq!(log(&app), json!(["typed", 2])); +} + +#[test] +fn a_second_dialog_replaces_the_first() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('edittext', undefined, 'x'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('edittext', undefined, 'y'); b.add('button', undefined, 'OK'); vc.log([b.show(), b.children[0].text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("left over")); + assert!(until_window(&mut app)); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.str("title"), "B", "the second dialog's title"); + assert!(!d.fields.contains_key("text1"), "without the first dialog's typed text"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "y"]])); +} + +#[test] +fn a_dialog_function_after_show_opens_its_own_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} w.show(); alert('done');")); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..100 { + script_runs::poll(&mut app); + if app.ui.dialog.as_ref().is_some_and(|d| d.kind != KIND) { + break; + } + } + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::NOTICE_KIND), "the alert opens"); + assert!(app.session.script_dialog().is_some()); +} + +#[test] +fn stop_in_the_dialog_rolls_the_run_back() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} w.show(); vc.log('after');")); + assert!(until_window(&mut app)); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); + assert_eq!(objects(&app), 0); + assert_eq!(app.session.script_report().unwrap()["dialogs"][0]["answer"], "stop"); + assert!(app.ui.dialog.is_none()); +} + +#[test] +fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("text1".into(), json!("typed")); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND)); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the dialog opens again"); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("text1"), "typed", "with the text typed in its field"); + dialogs::script_run::ask_to_close(&mut app); + dialogs::confirm(&mut app).unwrap(); + assert!(!app.session.script_running()); + assert_eq!(objects(&app), 0); +} + +#[test] +fn a_large_dialog_draws_in_a_small_window() { + let mut app = app(); + let source = "var w = new Window('dialog', 'Big'); var p = w.add('panel', undefined, 'Lots'); \ + for (var i = 0; i < 200; i++) p.add('checkbox', undefined, 'Option ' + i); \ + var l = w.add('listbox', undefined, ['a', 'b']); var d = w.add('dropdownlist', undefined, ['x', 'y']); \ + w.add('slider', undefined, 2, 0, 5); w.add('progressbar', undefined, 1, 4); w.add('edittext', undefined, 'm', {multiline: true}); \ + w.add('button', undefined, 'OK'); vc.log(w.show());"; + start(&mut app, source); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([1])); +} diff --git a/docs/mcp.md b/docs/mcp.md index 3c577e0356..771273aed2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2841,10 +2841,12 @@ app's own errors, syntax errors and limits. The status bar shows a `script` mess - `console` is `{lines, droppedLines, truncatedLines}`: the run's own output, `vc.log` lines and uncaught error, as text. - `dialogs` lists the run's dialogs in the order they opened, as `{kind, message, title, errorIcon, answer}` for - `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm` and `{kind, message, title, preset, answer}` - for `prompt`. `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, `"stop"` for a dialog the - run ended at, or `"missing"` for a dialog `answers` had no answer for. `dialogCount` counts every dialog, and - `dialogsTruncated` is true when the list stopped at its limit. + `alert`, `{kind, message, title, noAsDefault, answer}` for `confirm`, `{kind, message, title, preset, answer}` + for `prompt` and `{kind, title, controls, events, answer}` for a ScriptUI dialog's `show()` (kind `window`). + `answer` is `"ok"`, `true`, `false`, the prompt's text, `null` for Cancel, the number `show()` returned, `"stop"` + for a dialog the run ended at, `"missing"` for a dialog `answers` had no answer or no step for, or `"error"` for a + `show()` that ended with an error. `dialogCount` counts every dialog, and `dialogsTruncated` is true when the list + stopped at its limit. ```json {"name":"run_command","arguments":{"command":"script.run","params":{"source":"vc.run('shape.rectangle', {x: 0, y: 0, width: 10, height: 10});"}}} @@ -2895,6 +2897,67 @@ empty object are the same. vectorcraft-cli run --cmd script.run --params '{"source": "if (confirm(\"Add a frame?\")) vc.log(prompt(\"Name\", \"Frame\"));", "answers": [{"kind": "confirm", "value": true}, {"kind": "prompt", "value": "Border"}]}' ``` +The help pages https://extendscript.docsforadobe.dev/user-interface-tools/window-object/, +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. +- `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`, + and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, + minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `listbox` with + `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` + and the rest) throw that they are not available yet, and an unknown type throws too. +- A list's `add("item", text)` adds an item, `removeAll()` removes them, `items` lists them and `selection` is the + selected item or `null`; setting it to an item or an index selects it. An item has `text`, `index` and + `selected`. +- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, + `window`, `show()` and `hide()`. A container also has `children`, `orientation` (`row`, `column` or `stack`; a + group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` + (15 to start, 0 for a group) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, + `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + +`show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check +box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An +edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another +control, and a slider gives its +value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. +Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` +returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the +cancel button is clicked, while they have no `onClick`, and 0 for the close box. `onClose` runs before the dialog +closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled +OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside +a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in +function. A shown dialog can be shown again after it closes. + +`show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of +text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws +too, and a slider's minimum above its maximum. It lays the controls out from each container's `orientation`, +`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places +it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. + +In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, +which ends the run as `script.stop` does. Enter outside a field clicks the default button. Escape clicks the +cancel button, or closes the dialog when it has none. Quitting while it waits asks whether to stop the script, and +Cancel shows it again. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in +the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a disabled or +hidden control, a value out of a list's range and a click on a control that takes none are errors, and the dialog +stays open. + +A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is +`{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a +control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a +list's item index or `null`. The dialog takes the next step each time it waits. The run ends with an error that +the script cannot catch, and every document goes back, when no step is left, when a step names a control the +dialog does not have or that cannot take it, or when the dialog closes with steps it did not use. + +```sh +vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' +``` + The help pages https://extendscript.docsforadobe.dev/file-system-access/file-object/ and https://extendscript.docsforadobe.dev/file-system-access/folder-object/ describe the `File` and `Folder` objects. A script reads files with them: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3da663c191..939047032e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1066,6 +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; 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`. - 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`). From 3745b14db46fffeb568e5a5da2806d05093f35c8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 02:12:43 -0800 Subject: [PATCH 02/29] Scripts: ScriptUI dialogs keep to their limits and steps under reentrant handlers - A show() that a handler's error ended with steps left in `answers` now ends the run and rolls it back, even when the script catches the error. - A list step's value written as a whole float (1.0) is an item index, in `answers` and in ui.dialog.confirm; a fraction is still refused. - A progress bar's fraction stays finite across the widest range. - add() checks the control and item counts again after the getters and conversions it runs, refuses an initial item array longer than the items left before reading it, and counts a new list's items only once the list is added. - show() keeps the values a getter gives while their properties are read, and reads the dialog again when a getter changes a list after it was read; a list that changes again throws an Error. - A click or close from ui.dialog.confirm gives the text still typed in the dialog's fields first. - Quitting while a handler runs keeps the dialog and its queued events, so Cancel shows it again with them. - Screen readers call an edit field without a name by the visible static text just before it in its container. - The dialog's heading follows a title a handler changed while the dialog is open. - A list box gives screen readers a list box node named by its name or the static text before it, with the selected item as its value, and a drop-down list is named the same way. - The dialog closes when show() returns, also when the script goes on running. - Enter clicks the default button while the keyboard focus is on a control other than an edit field, such as a slider. --- crates/engine/src/script/dialogs.rs | 20 ++- crates/engine/src/script/mod.rs | 15 ++ crates/engine/src/script/scriptui.rs | 33 ++++- crates/engine/src/tests/script_scriptui.rs | 43 +++++- crates/js/src/scriptui.rs | 136 ++++++++++++++---- crates/js/src/scriptui_tests.rs | 78 +++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 12 +- crates/ui-egui/src/dialogs/script_window.rs | 121 ++++++++++++---- crates/ui-egui/src/script_runs.rs | 12 +- crates/ui-egui/src/tests/script_window.rs | 144 ++++++++++++++++++++ docs/mcp.md | 26 ++-- 11 files changed, 564 insertions(+), 76 deletions(-) diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index 4c0ce4a39b..fa3043b0a7 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -21,7 +21,7 @@ use std::collections::VecDeque; use std::rc::Rc; use serde_json::{Map, Value, json}; -use vectorcraft_js::{Arg, Data, HostError, HostFunction, Realm, RunError}; +use vectorcraft_js::{Arg, Data, HostError, HostFunction, LimitKind, Realm, RunError, RunErrorKind}; use super::scriptui::{self, ScriptUiDialog, Showing, UiEvent, UiStep}; use super::{Host, console}; @@ -258,6 +258,11 @@ impl Dialogs { self.window.borrow().as_ref().map(|s| s.dialog.clone()) } + /// The ScriptUI dialog whose `show()` is running, as it last waited, also while a handler runs. + pub(crate) fn showing_window(&self) -> Option { + self.window.borrow().as_ref().map(|s| s.dialog.clone()) + } + /// Gives the waiting ScriptUI dialog `event`, once it is checked against the dialog. pub(crate) fn window_answer(&self, realm: &mut Realm, event: UiEvent) -> Result<(), String> { if !self.window_waiting.get() { @@ -347,10 +352,19 @@ impl Dialogs { self.window_waiting.set(false); let Some(showing) = self.window.borrow_mut().take() else { return Ok(()) }; let left = showing.steps.as_ref().map_or(0, std::collections::VecDeque::len); + let steps = if left == 1 { "step" } else { "steps" }; + let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"); if normal && left > 0 { self.push_record(showing.record(json!("missing"))); - let steps = if left == 1 { "step" } else { "steps" }; - return Err(HostError::Abort(format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"))); + return Err(HostError::Abort(unused)); + } + // A show that a handler's error ended still ends the run when steps are left: the script + // can catch that error, and the run must not finish as if it took every step. + if left > 0 { + let mut failed = self.failed.borrow_mut(); + if failed.is_none() { + *failed = Some(RunError { kind: RunErrorKind::Limit(LimitKind::Host), message: unused, line: 0, column: 0, authored: false }); + } } let answer = match result { _ if !normal => json!("error"), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 293d77c716..cb0398500a 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1833,6 +1833,15 @@ impl Session { self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting_window())).flatten() } + /// The ScriptUI dialog whose `show()` the running script is in, whether it waits at it or runs + /// one of its handlers. A run asked to stop is in none. + pub fn script_window_showing(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.showing_window())).flatten() + } + /// Gives the ScriptUI dialog the running script waits at `event`; the next /// [`Session::script_pump`] runs the control's handler. → an error, and the dialog still /// waits, when nothing waits or the dialog cannot take the event ([`scriptui::check_event`]). @@ -2158,6 +2167,12 @@ impl Session { } job.host.calls_this_slice.set(0); let outcome = run_slice(self, &mut job); + // A failure a dialog recorded in the slice (steps a show left unused) ends the run, even + // when the script went on. + let outcome = match (outcome, job.host.dialogs.take_failure()) { + (Ok(Ok(_)), Some(e)) => Ok(Err(e)), + (outcome, _) => outcome, + }; match outcome { Err(panic) => { let e = RunError { kind: RunErrorKind::Internal, message: panic, line: 0, column: 0, authored: false }; diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 62cfaade79..2f77fbb5b8 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -148,6 +148,23 @@ pub struct UiNode { bounds: Option, } +impl UiNode { + /// How much of a progress bar is done, from 0 to 1. + pub fn fraction(&self) -> f32 { + if self.max <= self.min || self.value <= self.min { + return 0.0; + } + if self.value >= self.max { + return 1.0; + } + let span = self.max - self.min; + // A range wider than the largest number is measured at half scale. + let part = + if span.is_finite() { (self.value - self.min) / span } else { (self.value / 2.0 - self.min / 2.0) / (self.max / 2.0 - self.min / 2.0) }; + part.clamp(0.0, 1.0) as f32 + } +} + /// A dialog a run shows, checked and laid out. #[derive(Clone, Debug, PartialEq)] pub struct ScriptUiDialog { @@ -302,8 +319,8 @@ pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result UiEvent::Click(id), (_, Some(Value::String(t))) => UiEvent::Change(id, UiValue::Text(t.clone())), - (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match n.as_u64() { - Some(k) => UiEvent::Change(id, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX)))), + (_, Some(Value::Number(n))) if matches!(dialog.nodes[id].kind, UiKind::DropDownList | UiKind::ListBox) => match list_index(n) { + Some(k) => UiEvent::Change(id, UiValue::Index(Some(k))), None => return Err("a list's `value` must be an item index or null".into()), }, (_, Some(Value::Number(n))) => UiEvent::Change(id, UiValue::Number(n.as_f64().unwrap_or(f64::NAN))), @@ -313,6 +330,18 @@ pub(crate) fn step_event(dialog: &ScriptUiDialog, step: &UiStep) -> Result Option { + if let Some(k) = n.as_u64() { + return Some(usize::try_from(k).unwrap_or(usize::MAX)); + } + let f = n.as_f64()?; + // `as` saturates a whole number too large for usize at usize::MAX. + (f >= 0.0 && f.fract() == 0.0).then_some(f as usize) +} + fn field<'a>(fields: &'a [(String, Data)], name: &str) -> &'a Data { fields.iter().find(|(k, _)| k == name).map_or(&Data::Undefined, |(_, v)| v) } diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 24a6052154..19c5cf5c80 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -127,6 +127,7 @@ fn window_answers_that_do_not_parse_are_refused_before_the_run() { #[test] fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { let mut s = one_doc(); + let undo_before = art(&s).1; framed( &mut s, &format!("{EDIT} {FORM} bold.onClick = function () {{ size.enabled = !bold.value; }}; var r = w.show(); vc.log([r, name.text, size.value]);"), @@ -153,7 +154,47 @@ fn a_framed_run_waits_at_show_and_runs_each_handler_with_the_persons_events() { let r = pump(&mut s).unwrap().unwrap(); assert_eq!(r["log"], json!([[1, "Ann", 5]])); assert_eq!(r["dialogs"][0]["events"], 3); - assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script", "a finished run is one undo step"); + assert_eq!(art(&s).1, undo_before + 1, "a finished run is one undo step"); + assert_eq!(s.documents()[0].history.undo.last().unwrap().label, "Run Script"); +} + +#[test] +fn an_unused_step_after_a_handler_threw_ends_the_run_and_rolls_it_back() { + let mut s = one_doc(); + let before = art(&s); + let source = format!( + "{EDIT} var w = new Window('dialog'); var f = w.add('button', undefined, 'Fail'); f.onClick = function () {{ throw new Error('boom'); }}; \ + try {{ w.show(); }} catch (e) {{ vc.log('caught'); }}" + ); + let steps = window(json!([{"control": "Fail", "event": "click"}, {"event": "close"}])); + let e = headless(&mut s, &source, steps).unwrap_err().to_string(); + assert!(e.contains("has 1 step the dialog did not use"), "{e}"); + assert_eq!(art(&s), before, "the run is rolled back"); +} + +#[test] +fn a_list_index_written_as_a_whole_float_is_an_index_and_a_fraction_is_refused() { + let mut s = one_doc(); + let source = format!("{FORM} vc.log([w.show(), pick.selection.text]);"); + let r = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.0}, {"control": "OK", "event": "click"}]))) + .unwrap(); + assert_eq!(r["log"], json!([[1, "b"]])); + let e = headless(&mut s, &source, window(json!([{"control": "pick", "event": "change", "value": 1.5}]))).unwrap_err().to_string(); + assert!(e.contains("a list's `value` must be an item index or null"), "{e}"); +} + +#[test] +fn a_progress_bar_s_fraction_stays_finite_over_the_widest_range() { + let bar = |min: f64, max: f64, value: f64| { + let n = + with(with(with(node("progressbar", 0.0), "minvalue", Data::Number(min)), "maxvalue", Data::Number(max)), "value", Data::Number(value)); + scriptui::parse(&description(vec![node("dialog", -1.0), n])).unwrap().nodes[1].fraction() + }; + assert_eq!(bar(-1e308, 1e308, 1e308), 1.0); + assert_eq!(bar(-1e308, 1e308, -1e308), 0.0); + assert_eq!(bar(-1e308, 1e308, 0.0), 0.5); + assert_eq!(bar(0.0, 10.0, 3.0), 0.3); + assert_eq!(bar(5.0, 5.0, 5.0), 0.0, "an empty range shows nothing done"); } #[test] diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 9afc647960..f2f8a33b2c 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -28,7 +28,9 @@ //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] //! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a -//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. A +//! getter that changes a list's items after the list was read makes `show()` read the dialog again, +//! and a list that changes again throws an `Error`. use crate::HostItem; use crate::builtins::{arg, constructor, method, native, pausable_method}; @@ -363,33 +365,66 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } _ => {} } + // A new list's items take their places in the dialog only once the list is added. + let mut staged = 0usize; if list_kind { match arg(args, 2) { Value::Undefined | Value::Null => {} Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { - for item in list_values(i, a)? { - add_item(i, c, &item)?; + let length = match &i.object(a)?.class { + Class::Array { length, .. } => *length as usize, + _ => 0, + }; + if length > MAX_ITEMS.saturating_sub(number_slot(i, win, ITEM_COUNT)? as usize) { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let values = list_values(i, a)?; + i.temp_roots.extend(values.iter().cloned()); + for item in &values { + let text = text_arg(i, item)?; + new_item(i, c, text)?; + staged += 1; } } _ => return Err(i.type_error("add: give a list's items as an array")), } } + // A getter or a conversion above may have added controls or items itself. + let count = number_slot(i, win, COUNT)?; + if count as usize >= MAX_CONTROLS { + return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); + } + let items = number_slot(i, win, ITEM_COUNT)?; + if items as usize + staged > MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } append(i, o, KIDS, "children", Value::Object(c))?; set_slot(i, win, COUNT, Value::Number(count + 1.0))?; + set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); r } -/// Adds an item with `text` to the list `o`. +/// Adds an item with `text` to the list `o`, which the dialog holds. fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; - let count = number_slot(i, win, ITEM_COUNT)?; - if count as usize >= MAX_ITEMS { - return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); - } + // The conversion runs first: it may add or remove items itself. let text = text_arg(i, text)?; + i.rooted(std::slice::from_ref(&text), |i| { + let count = number_slot(i, win, ITEM_COUNT)?; + if count as usize >= MAX_ITEMS { + return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); + } + let item = new_item(i, o, text.clone())?; + i.rooted(std::slice::from_ref(&item), |i| set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0)))?; + Ok(item) + }) +} + +/// Adds an item with `text` to the end of the list `o`, without counting it in the dialog's items. +fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { let proto = classes(i)?.item_proto; i.rooted(std::slice::from_ref(&text), |i| { i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; @@ -398,7 +433,6 @@ fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; append(i, o, ITEMS, "items", Value::Object(item))?; - set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0))?; Ok(Value::Object(item)) }) }) @@ -610,7 +644,7 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { set_showing(i, Some(win)); set_slot(i, win, CLOSING, Value::Undefined)?; let described = describe(i, win); - let (desc, nodes, def, cancel) = match described { + let (desc, nodes, def, cancel, lists) = match described { Ok(d) => d, Err(e) => { set_showing(i, None); @@ -621,7 +655,7 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { Ok(Pause { host: open, args: vec![desc], - keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)], resume: opened, failed: Some(failed), }) @@ -664,12 +698,12 @@ fn next(i: &mut Interp, win: ObjId) -> JsResult { } continue; } - let (desc, nodes, def, cancel) = describe(i, win)?; + let (desc, nodes, def, cancel, lists) = describe(i, win)?; let wait = host_fn(i, "wait")?; i.again = Some(Pause { host: wait, args: vec![desc], - keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel)], + keep: vec![Value::Object(win), Value::Object(nodes), Value::Number(def), Value::Number(cancel), Value::Object(lists)], resume: answered, failed: Some(failed), }); @@ -761,6 +795,14 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { Value::Number(n) => n, _ => -1.0, }; + // The index is into the items the person saw. + let shown = match arg(keep, 4).as_object() { + Some(lists) => list_values(i, lists)?.get(id).cloned().unwrap_or(Value::Undefined), + None => Value::Undefined, + }; + if !same(&slot(i, c, ITEMS)?, &shown) { + return Err(error(i, "show: a list's items changed before the person's choice was taken")); + } set_slot(i, c, SELECTION, Value::Number(n))?; } } @@ -785,6 +827,13 @@ fn get(i: &mut Interp, o: ObjId, name: &str) -> JsResult { i.get_value(&Value::Object(o), &key(name)) } +/// [`get`], keeping the value in the roots [`describe`] lets go of when it returns. +fn get_kept(i: &mut Interp, o: ObjId, name: &str) -> JsResult { + let v = get(i, o, name)?; + i.temp_roots.push(v.clone()); + Ok(v) +} + fn number_of(i: &mut Interp, o: ObjId, name: &str) -> JsResult { let v = get(i, o, name)?; Ok(Data::Number(number_arg(i, &v, &format!("show: a control's {name}"))?)) @@ -850,15 +899,35 @@ fn margins(i: &mut Interp, v: &Value) -> JsResult { /// The dialog's description: its elements in order, each after the container that holds it, as /// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of -/// its default and cancel elements (-1 for none). -fn describe(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { - let mark = i.temp_roots.len(); - let r = describe_rooted(i, win); - i.temp_roots.truncate(mark); - r +/// its default and cancel elements (-1 for none), and each element's array of list items as it +/// was described (`undefined` for an element that is not a list). When a getter changes a list +/// after it was read, the dialog is read again once; a list that changes again throws an `Error`. +fn describe(i: &mut Interp, win: ObjId) -> JsResult { + for _ in 0..2 { + let mark = i.temp_roots.len(); + let r = describe_rooted(i, win); + i.temp_roots.truncate(mark); + if let Some(d) = r? { + return Ok(d); + } + } + Err(error(i, "show: a list's items changed while the dialog was read")) } -fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f64)> { +/// A description, the elements in its order, the default and cancel elements, and the lists' items. +type Described = (Value, ObjId, f64, f64, ObjId); + +/// Has each list in `order` the array of items it had when it was described? +fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value]) -> JsResult { + for ((o, ..), kept) in order.iter().zip(snapshot) { + if !matches!(kept, Value::Undefined) && !same(&slot(i, *o, ITEMS)?, kept) { + return Ok(false); + } + } + Ok(true) +} + +fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let mut order: Vec<(ObjId, String, f64)> = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; @@ -885,8 +954,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f let mut nodes = Vec::with_capacity(order.len()); let mut names = Vec::with_capacity(order.len()); let mut items_total = 0usize; + // Each list's array of items as it is read; a change to it means a later getter changed the list. + let mut snapshot = Vec::with_capacity(order.len()); for (o, kind, parent) in &order { let o = *o; + let mut listed = Value::Undefined; let name_v = get(i, o, "name")?; let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; @@ -902,19 +974,20 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f let visible = get(i, o, "visible")?.truthy(); d.push(("enabled".into(), Data::Bool(enabled))); d.push(("visible".into(), Data::Bool(visible))); - let b = get(i, o, "bounds")?; + // A value a getter gives is kept from collection while its own properties are read. + let b = get_kept(i, o, "bounds")?; d.push(("bounds".into(), bounds(i, &b)?)); - let size = get(i, o, "preferredSize")?; + let size = get_kept(i, o, "preferredSize")?; d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); - let a = get(i, o, "alignment")?; + let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); if matches!(kind.as_str(), "dialog" | "group" | "panel") { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); - let ac = get(i, o, "alignChildren")?; + let ac = get_kept(i, o, "alignChildren")?; d.push(("alignChildren".into(), alignment(i, &ac)?)); d.push(("spacing".into(), number_of(i, o, "spacing")?)); - let m = get(i, o, "margins")?; + let m = get_kept(i, o, "margins")?; d.push(("margins".into(), margins(i, &m)?)); } match kind.as_str() { @@ -928,7 +1001,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f d.push(("maxvalue".into(), number_of(i, o, "maxvalue")?)); } "edittext" => { - let props = get(i, o, "properties")?; + let props = get_kept(i, o, "properties")?; let (multiline, readonly) = match props { Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), _ => (false, false), @@ -937,6 +1010,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f d.push(("readonly".into(), Data::Bool(readonly))); } "dropdownlist" | "listbox" => { + let kept = slot(i, o, ITEMS)?; + i.temp_roots.push(kept.clone()); + listed = kept; let items = items_of(i, o)?; items_total = items_total.saturating_add(items.len()); if items_total > MAX_ITEMS { @@ -954,6 +1030,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f _ => {} } nodes.push(Data::Object(d)); + snapshot.push(listed); } let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { let given = get(i, win, name)?; @@ -968,6 +1045,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f }; let def = target(i, "defaultElement", "ok")?; let cancel = target(i, "cancelElement", "cancel")?; + if !lists_unchanged(i, &order, &snapshot)? { + return Ok(None); + } let desc = Data::Object(vec![ ("nodes".into(), Data::Array(nodes)), ("defaultElement".into(), Data::Number(def)), @@ -976,7 +1056,9 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult<(Value, ObjId, f64, f let desc = i.write_data(desc, 0, true)?; i.temp_roots.push(desc.clone()); let kept = list(i, &objects, false)?; - Ok((desc, kept, def, cancel)) + i.temp_roots.push(Value::Object(kept)); + let lists = list(i, &snapshot, false)?; + Ok(Some((desc, kept, def, cancel, lists))) } /// Adds `Window`, its prototype's methods, and the host functions in `items`. diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 18067d6375..7d0d8376a3 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -265,6 +265,84 @@ fn too_many_controls_too_deep_a_nesting_and_too_long_a_text_are_refused() { assert_eq!(long, JsValue::String("show: a control's text is longer than 16 KiB".into())); } +#[test] +fn an_add_that_a_getter_or_a_conversion_reenters_keeps_to_the_limits() { + let (mut r, _, _) = realm(Vec::new()); + let controls = r + .run( + "var w = new Window('dialog'); for (var i = 0; i < 511; i++) w.add('button'); \ + var props = {}; Object.defineProperty(props, 'name', {get: function () { w.add('button'); return 'n'; }}); \ + var e = ''; try { w.add('button', undefined, 'x', props); } catch (x) { e = x.name; } [e, w.children.length].join()", + ) + .unwrap(); + assert_eq!(controls, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS)), "the getter took the last place"); + let items = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1023; n++) l.add('item', 'i'); \ + var t = {toString: function () { l.add('item', 'inner'); return 'outer'; }}; \ + var e = ''; try { l.add('item', t); } catch (x) { e = x.name; } [e, l.items.length].join()", + ) + .unwrap(); + assert_eq!(items, JsValue::String(format!("RangeError,{}", scriptui::MAX_ITEMS)), "the conversion took the last place"); +} + +#[test] +fn a_new_list_s_items_count_only_once_it_is_added_and_too_many_are_refused_unread() { + let (mut r, _, _) = realm(Vec::new()); + let failed = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1022; n++) l.add('item', 'i'); \ + var bad = {toString: function () { throw new Error('no text'); }}; \ + var e = ''; try { w.add('dropdownlist', undefined, ['a', bad]); } catch (x) { e = x.message; } \ + l.add('item', 'y'); l.add('item', 'z'); [e, l.items.length, w.children.length].join()", + ) + .unwrap(); + assert_eq!(failed, JsValue::String(format!("no text,{},1", scriptui::MAX_ITEMS)), "the list that was not added took no places"); + let long = r + .run( + "var w = new Window('dialog'); var read = false; var a = new Array(5000); a[0] = {toString: function () { read = true; return 'x'; }}; \ + var e = ''; try { w.add('listbox', undefined, a); } catch (x) { e = x.name; } [e, read, w.children.length].join()", + ) + .unwrap(); + assert_eq!(long, JsValue::String("RangeError,false,0".into()), "an array longer than the limit is refused before its items are read"); +} + +#[test] +fn a_collection_while_a_bounds_or_margins_value_is_read_keeps_that_value() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "function heavy(n) { return {valueOf: function () { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); return n; }}; } \ + var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + Object.defineProperty(b, 'bounds', {get: function () { return {left: heavy(1), top: 2, right: 30, bottom: 40}; }}); \ + Object.defineProperty(w, 'margins', {get: function () { return [heavy(3), 4, 5, 6]; }}); \ + w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let numbers = |v: &[f64]| Data::Array(v.iter().map(|n| Data::Number(*n)).collect()); + assert_eq!(field(&first[1], "bounds"), &numbers(&[1.0, 2.0, 30.0, 40.0])); + assert_eq!(field(&first[0], "margins"), &numbers(&[3.0, 4.0, 5.0, 6.0])); +} + +#[test] +fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() { + let (mut r, seen, _) = realm(vec![change(1, Data::Number(0.0)), click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + var swapped = false; Object.defineProperty(b, 'text', {get: function () { if (!swapped) { swapped = true; l.removeAll(); l.add('item', 'B'); } return 'OK'; }}); \ + var picked = ''; l.onChange = function () { picked = l.selection.text; }; w.show(); picked"; + assert_eq!(r.run(source).unwrap(), JsValue::String("B".into())); + let seen = seen.borrow(); + assert_eq!( + field(&nodes(&seen.descriptions[0])[1], "items"), + &Data::Array(vec![Data::String("B".into())]), + "the description shows the list as it is" + ); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + Object.defineProperty(b, 'text', {get: function () { l.removeAll(); l.add('item', 'B'); return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items changed while the dialog was read".into())); +} + #[test] fn a_bounds_value_that_is_not_finite_is_refused_when_shown() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index fcf80916ae..8a43c064a4 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -209,8 +209,8 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { } /// Closes the question quitting asks once the run it asks about has ended, and forgets the -/// script's dialog it was asked over once the run no longer waits at that dialog, so Cancel does -/// not show it again. +/// script's dialog it was asked over once the run no longer waits at that dialog (or, for a +/// ScriptUI dialog, once its `show()` has ended), so Cancel does not show it again. pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == CLOSE_KIND) { return; @@ -220,12 +220,20 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { } else if app.session.script_dialog().is_none() && app.session.script_picker().is_none() && app.session.script_window().is_none() + && !over_running_show(app) && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); } } +/// Was the question asked over the ScriptUI dialog of the `show()` the run is still in (one of its +/// handlers runs)? Cancel then shows that dialog again, with the events it has not given yet. +fn over_running_show(app: &VectorcraftApp) -> bool { + let Some(w) = app.session.script_window_showing() else { return false }; + app.ui.dialog.as_ref().and_then(super::parent).is_some_and(|p| super::script_window::is_open_for(&p, &w)) +} + /// Shows the dialog the running script waits at. pub(crate) fn open_notice(app: &mut VectorcraftApp, d: &ScriptDialog) { let fields = json!({ diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 443f3e96cb..2a1b31bf1d 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -5,8 +5,9 @@ //! Its fields are `title` and, for `ui.dialog.set` and `ui.dialog.confirm`, `event` (`click`, //! `change` or `close`), `control` (a control's index in the dialog's list of elements, or its //! name or text) and `value` (an edit field's text, a slider's number, or a list's item index or -//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open; an event the -//! dialog cannot take is an error. An edit field gives its text when it loses the keyboard focus, +//! null). `ui.dialog.confirm` gives the script that event and leaves the dialog open, giving the +//! text still typed in its fields first when the event is a click or a close; an event the dialog +//! cannot take is an error. An edit field gives its text when it loses the keyboard focus, //! when Enter is pressed in a one-line field, or before a click on another control or a close. Events given in //! one frame reach the script one at a time, in order. Enter outside a field clicks the default button, //! and Escape or `ui.dialog.cancel` clicks the cancel button, or closes the dialog when it has @@ -83,7 +84,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc ui.add_enabled_ui(waiting, |ui| { for (i, n) in w.nodes.iter().enumerate().skip(1) { if n.visible - && let Some(e) = control(ui, d, area.min, i, n, w.default_element == Some(i)) + && let Some(e) = control(ui, d, area.min, (i, n, prompt_of(&w, i)), w.default_element == Some(i)) { events.push(e); } @@ -101,7 +102,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc app.ui.dialog = None; return DialogAction::None; } - let typing = ui.ctx().memory(|m| m.focused().is_some()); + // Enter in a field belongs to the field; with the focus on any other control, it clicks the + // default button. + let typing = ui.ctx().memory(egui::Memory::focused).is_some_and(|id| egui::TextEdit::load_state(ui.ctx(), id).is_some()); if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { events.extend(w.default_element.map(UiEvent::Click)); } @@ -158,8 +161,20 @@ fn draft_key(i: usize) -> String { format!("text{i}") } -/// Draws control `i` at its place from `origin`. → the event it gives. -fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: &UiNode, default: bool) -> Option { +/// The text of the visible static text just before control `i` in its container: the visible prompt +/// of an edit field, a list box or a drop-down list, which screen readers call one without a name +/// by. Empty when there is none. +pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { + let Some(parent) = w.nodes.get(i).map(|n| n.parent) else { return "" }; + match w.nodes[..i].iter().skip(1).rev().find(|n| n.parent == parent && n.visible) { + Some(n) if n.kind == UiKind::StaticText => &n.text, + _ => "", + } +} + +/// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place from `origin`. → the +/// event it gives. +fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt): (usize, &UiNode, &str), default: bool) -> Option { let rect = egui::Rect::from_min_size(origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); let t = Tokens::get(ui.ctx()); let mut event = None; @@ -199,18 +214,23 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: & event = Some(UiEvent::Click(i)); } } - UiKind::EditText => event = edit(ui, d, rect, i, n), + UiKind::EditText => event = edit(ui, d, rect, (i, n, prompt)), UiKind::DropDownList => { let shown = n.selection.and_then(|k| n.items.get(k)).cloned().unwrap_or_default(); let mut picked = None; ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| { - craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| { + let r = craft_ui::ComboBox::from_id_salt(("script-window-list", i)).selected_text(shown).width(rect.width()).show_ui(ui, |ui| { for (k, item) in n.items.iter().enumerate() { if ui.selectable_label(n.selection == Some(k), item).clicked() { picked = Some(k); } } }); + // Screen readers call the drop-down by its name or the static text before it. + let label = list_name(n, prompt); + if !label.is_empty() { + ui.ctx().accesskit_node_builder(r.response.id, |node| node.set_label(label)); + } }); if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); @@ -219,6 +239,19 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: & UiKind::ListBox => { ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside); ui.scope_builder(egui::UiBuilder::new().max_rect(rect.shrink(3.0)), |ui| { + // Screen readers read the box as a list box, by its name or the static text + // before it, with the selected item as its value. + let label = list_name(n, prompt); + let selected = n.selection.and_then(|k| n.items.get(k)).cloned(); + ui.ctx().accesskit_node_builder(ui.unique_id(), |node| { + node.set_role(egui::accesskit::Role::ListBox); + if !label.is_empty() { + node.set_label(label); + } + if let Some(item) = selected { + node.set_value(item); + } + }); egui::ScrollArea::vertical().id_salt(("script-window-listbox", i)).max_height(rect.height() - 6.0).show(ui, |ui| { for (k, item) in n.items.iter().enumerate() { if ui.selectable_label(n.selection == Some(k), item).clicked() && n.selection != Some(k) { @@ -231,16 +264,14 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: & UiKind::Slider => { let mut v = n.value; let r = ui.put(rect, egui::Slider::new(&mut v, n.min..=n.max).show_value(false)); - name_for_screen_readers(ui, &r, n); + name_for_screen_readers(ui, &r, n, prompt); if (r.drag_stopped() || (r.changed() && !r.dragged())) && v != n.value { event = Some(UiEvent::Change(i, UiValue::Number(v))); } } UiKind::ProgressBar => { - let span = n.max - n.min; - let part = if span > 0.0 { ((n.value - n.min) / span) as f32 } else { 0.0 }; - let r = ui.put(rect, egui::ProgressBar::new(part)); - name_for_screen_readers(ui, &r, n); + let r = ui.put(rect, egui::ProgressBar::new(n.fraction())); + name_for_screen_readers(ui, &r, n, prompt); } }); }); @@ -248,28 +279,40 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, i: usize, n: & } /// Screen readers call a control with no visible label of its own (an edit field, a slider or a -/// progress bar) by the name the script gave it, or else a slider or progress bar by its text. -fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode) { - let label = if !n.name.is_empty() { - n.name.clone() - } else if n.kind != UiKind::EditText { - n.text.clone() - } else { - String::new() - }; +/// progress bar) by the name the script gave it, or else a slider or progress bar by its text, and +/// an edit field by the visible static text just before it in its container. +fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode, prompt: &str) { + let label = screen_reader_name(n, prompt); if !label.is_empty() { ui.ctx().accesskit_node_builder(r.id, |node| node.set_label(label)); } } +/// The name screen readers call a list box or a drop-down list `n` by: the name the script gave it, +/// or else the visible static text just before it. Empty for none. +fn list_name(n: &UiNode, prompt: &str) -> String { + if n.name.is_empty() { prompt.to_string() } else { n.name.clone() } +} + +/// The name [`name_for_screen_readers`] gives control `n`; empty for none. +pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { + if !n.name.is_empty() { + n.name.clone() + } else if n.kind != UiKind::EditText { + n.text.clone() + } else { + prompt.to_string() + } +} + /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, i: usize, n: &UiNode) -> Option { +fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (usize, &UiNode, &str)) -> Option { let key = draft_key(i); let mut text = d.fields.get(&key).and_then(Value::as_str).map_or_else(|| n.text.clone(), str::to_string); let field = if n.multiline { egui::TextEdit::multiline(&mut text) } else { egui::TextEdit::singleline(&mut text) }; let r = ui.put(rect, field.interactive(!n.readonly).desired_width(rect.width())); - name_for_screen_readers(ui, &r, n); + name_for_screen_readers(ui, &r, n, prompt); if r.changed() { d.fields.insert(key.clone(), json!(text)); } @@ -310,8 +353,8 @@ fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { ("close", _) => Ok(UiEvent::Close), ("click", _) => Ok(UiEvent::Click(control)), ("change", Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), - ("change", Some(Value::Number(v))) if list => match v.as_u64() { - Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(usize::try_from(k).unwrap_or(usize::MAX))))), + ("change", Some(Value::Number(v))) if list => match vectorcraft_engine::script::scriptui::list_index(v) { + Some(k) => Ok(UiEvent::Change(control, UiValue::Index(Some(k)))), None => Err("a list's `value` must be an item index or null".into()), }, ("change", Some(Value::Number(v))) => Ok(UiEvent::Change(control, UiValue::Number(v.as_f64().unwrap_or(f64::NAN)))), @@ -322,15 +365,37 @@ fn event_of(w: &ScriptUiDialog, d: &Dialog) -> Result { } /// Gives the running script the event in the dialog's fields. The dialog stays open for the -/// script's next wait; an event it cannot take is an error. +/// script's next wait; an event it cannot take is an error. Before a click or a close, the script +/// is given the text still typed in the dialog's fields first, and the click or close waits for +/// its next wait. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; let event = event_of(&w, d)?; - app.session.script_window_answer(event)?; + vectorcraft_engine::script::scriptui::check_event(&w, event.clone())?; + let mut events = vec![event]; + let open = app.ui.dialog.as_mut().filter(|open| open.kind == KIND); + if let Some(open) = open + && matches!(events[0], UiEvent::Click(_) | UiEvent::Close) + { + commit_drafts(&w, open, &mut events); + } + let mut events = events.into_iter(); + if let Some(first) = events.next() { + app.session.script_window_answer(first)?; + } if let Some(open) = app.ui.dialog.as_mut().filter(|open| open.kind == KIND) { for k in ["event", "control", "value"] { open.fields.remove(k); } + let later: Vec = events.map(|e| event_fields(&e)).collect(); + if !later.is_empty() { + let mut queue = match open.fields.remove(QUEUE_KEY) { + Some(Value::Array(queue)) => queue, + _ => Vec::new(), + }; + queue.splice(0..0, later); + open.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); + } } Ok(Value::Null) } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index f3d5f14912..27e74d820e 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -85,11 +85,17 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.is_none() { script_window::open(app, &window); } + // Its heading follows a title a handler changed. + if let Some(d) = app.ui.dialog.as_mut().filter(|d| d.kind == script_window::KIND) { + d.fields.insert("title".into(), serde_json::Value::from(window.title())); + } return true; } - // While a handler runs, the ScriptUI dialog stays open, until the run ends or asks about its - // growth. - if app.session.script_waiting() && app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) { + // While a handler runs, the ScriptUI dialog stays open, until its show() ends or the run asks + // about its growth. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) + && (app.session.script_waiting() || app.session.script_window_showing().is_none()) + { app.ui.dialog = None; } if app.session.script_waiting() { diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 1cc241b049..8b8b68a41b 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -255,6 +255,150 @@ fn quitting_while_the_dialog_waits_asks_and_cancel_shows_it_again() { assert_eq!(objects(&app), 0); } +#[test] +fn quitting_while_a_handler_runs_keeps_the_events_still_queued() { + let mut app = app(); + start(&mut app, &format!("{DRAW} {FORM} name.onChange = function () {{ name.text = name.text + '!'; }}; vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("queued".into(), json!([{"event": "click", "control": 3, "value": null}])); + give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND)); + script_runs::poll(&mut app); + dialogs::cancel(&mut app); + assert!(until_window(&mut app), "the dialog opens again"); + assert!(app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "with the click still queued"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "Ann!"]])); +} + +#[test] +fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + start_typing(&mut app); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("text1"), "the text is given once"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn ui_dialog_confirm_takes_a_whole_float_as_a_list_index_and_refuses_a_fraction() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('dropdownlist', undefined, ['a', 'b'], {name: 'pick'}); w.add('button', undefined, 'OK'); \ + vc.log([w.show(), l.selection.text]);", + ); + assert!(until_window(&mut app)); + assert!(give(&mut app, json!({"event": "change", "control": "pick", "value": 1.5})).is_err()); + give(&mut app, json!({"event": "change", "control": "pick", "value": 1.0})).unwrap(); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "b"]])); +} + +#[test] +fn an_unnamed_edit_field_is_called_by_the_static_text_before_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group'); g.add('statictext', undefined, 'Width:'); g.add('edittext', undefined, '5'); \ + w.add('edittext', undefined, 'x', {name: 'height'}); w.add('edittext', undefined, 'y'); \ + var h = w.add('statictext', undefined, 'Secret'); h.visible = false; w.add('edittext', undefined, 'z'); \ + w.add('statictext', undefined, 'Account'); w.add('edittext', undefined, 'a', {name: 'user'}); w.add('button', undefined, 'OK'); w.show();", + ); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let name = |i: usize| script_window::screen_reader_name(&w.nodes[i], script_window::prompt_of(&w, i)); + assert_eq!(name(3), "Width:", "the static text before it in its group"); + assert_eq!(name(4), "height", "the name the script gave it"); + assert_eq!(name(5), "", "the control before it is no static text"); + assert_eq!(name(7), "", "a hidden static text is no prompt"); + assert_eq!(name(9), "user", "a name the script gave goes before the text before it"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn a_title_a_handler_changes_and_a_list_box_reach_the_dialog() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog', 'First'); w.add('statictext', undefined, 'Fruit:'); var l = w.add('listbox', undefined, ['apple', 'pear']); \ + l.selection = 1; w.add('statictext', undefined, 'Size:'); w.add('dropdownlist', undefined, ['small', 'large']); \ + var b = w.add('button', undefined, 'Rename'); b.onClick = function () { w.text = 'Renamed'; }; \ + w.add('button', undefined, 'OK'); w.show();", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Rename"})).unwrap(); + assert!(until_window(&mut app)); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("title"), "Renamed", "the heading follows the handler's title"); + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut nodes = Vec::new(); + for _ in 0..2 { + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + nodes = out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default(); + } + let list = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ListBox && n.label() == Some("Fruit:") && n.value() == Some("pear")); + assert!(list, "screen readers read the list box by its prompt, with its selected item"); + let drop = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ComboBox && n.label() == Some("Size:")); + assert!(drop, "screen readers read the drop-down list by its prompt"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn enter_with_the_focus_on_a_slider_clicks_the_default_button() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('slider', undefined, 2, 0, 5); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut on_slider = false; + for _ in 0..8 { + frame(&mut app, vec![key(egui::Key::Tab)]); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + on_slider = out + .platform_output + .accesskit_update + .is_some_and(|u| u.nodes.iter().any(|(id, n)| *id == u.focus && n.role() == egui::accesskit::Role::Slider)); + if on_slider { + break; + } + } + assert!(on_slider, "Tab puts the focus on the slider"); + frame(&mut app, vec![key(egui::Key::Enter)]); + assert!(!until_window(&mut app), "Enter clicks OK, which closes the dialog"); + assert_eq!(log(&app), json!([1])); +} + +#[test] +fn the_dialog_closes_when_its_show_ends_and_the_script_runs_on() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('button', undefined, 'OK'); w.show(); while (true) {}"); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + for _ in 0..3 { + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the script still runs"); + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != KIND), "the dialog its show() ended is closed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn a_large_dialog_draws_in_a_small_window() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 771273aed2..546f865d5f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2935,24 +2935,30 @@ function. A shown dialog can be shown again after it closes. `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws -too, and a slider's minimum above its maximum. It lays the controls out from each container's `orientation`, +too, and a slider's minimum above its maximum. When a getter changes a list's items after the list was read, it +reads the dialog again, and throws an `Error` when a list changes again. It lays the controls out from each container's `orientation`, `alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, -which ends the run as `script.stop` does. Enter outside a field clicks the default button. Escape clicks the -cancel button, or closes the dialog when it has none. Quitting while it waits asks whether to stop the script, and -Cancel shows it again. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in -the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a disabled or -hidden control, a value out of a list's range and a click on a control that takes none are errors, and the dialog -stays open. +which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()` +returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another +control that Enter does not click. Escape clicks the +cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs, +asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. +`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or +its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the +script the text still typed in the dialog's fields. A disabled or hidden control, a value out of a list's range, a +list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays +open. A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is `{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a -list's item index or `null`. The dialog takes the next step each time it waits. The run ends with an error that -the script cannot catch, and every document goes back, when no step is left, when a step names a control the -dialog does not have or that cannot take it, or when the dialog closes with steps it did not use. +list's item index (a whole number, such as `2` or `2.0`) or `null`. The dialog takes the next step each time it +waits. The run ends with an error that the script cannot catch, and every document goes back, when no step is +left, when a step names a control the dialog does not have or that cannot take it, or when the dialog closes, or +an error in a handler ends `show()`, with steps it did not use. ```sh vectorcraft-cli run --cmd script.run --params '{"source": "var w = new Window(\"dialog\", \"Frame\"); var name = w.add(\"edittext\", undefined, \"Frame\", {name: \"name\"}); w.add(\"button\", undefined, \"OK\"); w.add(\"button\", undefined, \"Cancel\"); if (w.show() == 1) vc.log(name.text);", "answers": [{"kind": "window", "value": [{"control": "name", "event": "change", "value": "Border"}, {"control": "OK", "event": "click"}]}]}' From 9eaacbbaf9708e8bedefd878cc296e5695759eb3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 05:37:55 -0800 Subject: [PATCH 03/29] Scripts: a refused typed text keeps the ScriptUI dialog's fields, and quitting forgets an ended show() - OK, Cancel, Escape, ui.dialog.confirm and ui.dialog.cancel now check every text still typed in the dialog's edit fields before giving the script any event. When one is longer than 16 KiB, every field keeps its text, nothing is queued, and the click or cancel returns an error (Escape and the dialog's own buttons show it in the status bar). A disabled or hidden field keeps its typed text and is not sent. - The quit question forgets the ScriptUI dialog it was asked over once the run has gone on to a different show(), so Cancel does not show the old dialog again. --- crates/ui-egui/src/dialogs.rs | 6 +- crates/ui-egui/src/dialogs/script_run.rs | 19 +++--- crates/ui-egui/src/dialogs/script_window.rs | 50 +++++++++++----- crates/ui-egui/src/tests/script_window.rs | 66 ++++++++++++++++++++- docs/mcp.md | 4 +- 5 files changed, 118 insertions(+), 27 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index eba418f360..cc98a59374 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -813,8 +813,10 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } - if d.kind == script_window::KIND { - script_window::cancel(app, &mut d); + if d.kind == script_window::KIND + && let Err(e) = script_window::cancel(app, &mut d) + { + app.status(e); } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 8a43c064a4..9b65d0b96a 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -210,25 +210,26 @@ pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { /// Closes the question quitting asks once the run it asks about has ended, and forgets the /// script's dialog it was asked over once the run no longer waits at that dialog (or, for a -/// ScriptUI dialog, once its `show()` has ended), so Cancel does not show it again. +/// ScriptUI dialog, once its `show()` has ended, also when the run has gone on to another +/// `show()`), so Cancel does not show it again. pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.ui.dialog.as_ref().is_some_and(|d| d.kind == CLOSE_KIND) { return; } if !app.session.script_running() { app.ui.dialog = None; - } else if app.session.script_dialog().is_none() - && app.session.script_picker().is_none() - && app.session.script_window().is_none() - && !over_running_show(app) - && let Some(d) = app.ui.dialog.as_mut() - { + return; + } + let over_window = app.ui.dialog.as_ref().and_then(super::parent).is_some_and(|p| p.kind == super::script_window::KIND); + let keep = if over_window { over_running_show(app) } else { app.session.script_dialog().is_some() || app.session.script_picker().is_some() }; + if !keep && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); } } -/// Was the question asked over the ScriptUI dialog of the `show()` the run is still in (one of its -/// handlers runs)? Cancel then shows that dialog again, with the events it has not given yet. +/// Was the question asked over the ScriptUI dialog of the `show()` the run is still in (it waits +/// there, or one of its handlers runs)? Cancel then shows that dialog again, with the events it +/// has not given yet. fn over_running_show(app: &VectorcraftApp) -> bool { let Some(w) = app.session.script_window_showing() else { return false }; app.ui.dialog.as_ref().and_then(super::parent).is_some_and(|p| super::script_window::is_open_for(&p, &w)) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 2a1b31bf1d..7bebdbf174 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -108,8 +108,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { events.extend(w.default_element.map(UiEvent::Click)); } - if events.iter().any(|e| matches!(e, UiEvent::Click(_))) { - commit_drafts(&w, d, &mut events); + if events.iter().any(|e| matches!(e, UiEvent::Click(_))) + && let Err(e) = commit_drafts(&w, d, &mut events) + { + // A refused text stays in its field, and the click waits for the person to fix it. + events.retain(|e| !matches!(e, UiEvent::Click(_))); + app.status(e); } let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, @@ -137,23 +141,39 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc const QUEUE_KEY: &str = "queued"; /// Before a click or a close, gives the script the text typed in each edit field that has not left -/// the field yet, so the handler of a button that closes the dialog, or `onClose`, reads it. -pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) { +/// the field yet, so the handler of a button that closes the dialog, or `onClose`, reads it. A +/// disabled or hidden field keeps its text for later. Each text is checked as the script would +/// check it first; when one is refused, every field keeps its text, `events` stays as it was and +/// the error is returned. +pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) -> Result<(), String> { + let mut drafts = Vec::new(); let mut changes = Vec::new(); for (i, n) in w.nodes.iter().enumerate() { - if n.kind != UiKind::EditText || n.readonly || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) { + if n.kind != UiKind::EditText + || n.readonly + || !n.enabled + || !n.visible + || events.iter().any(|e| matches!(e, UiEvent::Change(c, _) if *c == i)) + { continue; } - if let Some(Value::String(text)) = d.fields.remove(&draft_key(i)) - && text != n.text - { - changes.push(UiEvent::Change(i, UiValue::Text(text))); + let key = draft_key(i); + if let Some(Value::String(text)) = d.fields.get(&key) { + if *text != n.text { + let change = UiEvent::Change(i, UiValue::Text(text.clone())); + changes.push(vectorcraft_engine::script::scriptui::check_event(w, change)?); + } + drafts.push(key); } } + for key in drafts { + d.fields.remove(&key); + } let closing = |e: &UiEvent| matches!(e, UiEvent::Click(_) | UiEvent::Close); events.sort_by_key(closing); let at = events.iter().position(closing).unwrap_or(events.len()); events.splice(at..at, changes); + Ok(()) } /// The field that holds an edit field's text while it is typed. @@ -377,7 +397,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(open) = open && matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { - commit_drafts(&w, open, &mut events); + commit_drafts(&w, open, &mut events)?; } let mut events = events.into_iter(); if let Some(first) = events.next() { @@ -402,12 +422,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { /// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog /// has none or it cannot be clicked, after the text still typed in its fields. Events the script -/// has not had yet go after the ones before them. -pub(super) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) { - let Some(w) = app.session.script_window() else { return }; +/// has not had yet go after the ones before them. A typed text the script would refuse is an +/// error, and the dialog is left as it was. +pub(crate) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), String> { + let Some(w) = app.session.script_window() else { return Ok(()) }; let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); let mut events = vec![click.unwrap_or(UiEvent::Close)]; - commit_drafts(&w, d, &mut events); + commit_drafts(&w, d, &mut events)?; let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, _ => Vec::new(), @@ -422,4 +443,5 @@ pub(super) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) { if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } + Ok(()) } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 8b8b68a41b..49ef7abd18 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -125,7 +125,7 @@ fn text_still_in_a_field_reaches_the_script_before_a_click() { let d = app.ui.dialog.as_mut().unwrap(); d.fields.insert("text1".into(), json!("Ann")); let mut events = vec![UiEvent::Click(3)]; - script_window::commit_drafts(&w, d, &mut events); + script_window::commit_drafts(&w, d, &mut events).unwrap(); assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("Ann".into())), UiEvent::Click(3)]); assert!(!d.fields.contains_key("text1"), "the text is given once"); d.fields.insert("queued".into(), json!([{"event": "change", "control": 1, "value": "Ann"}, {"event": "click", "control": 3, "value": null}])); @@ -287,6 +287,70 @@ fn a_click_from_ui_dialog_confirm_gives_the_typed_text_first() { assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn a_typed_text_the_script_refuses_keeps_every_field_and_queues_nothing() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('edittext', undefined, 'b'); \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + let long = "x".repeat(16 * 1024 + 1); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!(long)); + d.fields.insert("text2".into(), json!("fine")); + let kept = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.kind, KIND); + assert_eq!(d.fields.get("text1"), Some(&json!(long)), "the refused text stays in its field"); + assert_eq!(d.fields.get("text2"), Some(&json!("fine")), "and so does the other one"); + assert!(!d.fields.contains_key("queued"), "nothing is queued"); + }; + assert!(give(&mut app, json!({"event": "click", "control": "OK"})).is_err(), "OK is an error"); + kept(&app); + let mut d = app.ui.dialog.clone().unwrap(); + assert!(script_window::cancel(&mut app, &mut d).is_err(), "Cancel is an error"); + dialogs::cancel(&mut app); + kept(&app); + assert!(app.session.script_window().is_some(), "the script still waits"); + app.ui.dialog.as_mut().unwrap().fields.remove("text1"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the other text and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[2].text, "fine"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([1])); +} + +#[test] +fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { + let mut app = app(); + start( + &mut app, + "var a = new Window('dialog', 'A'); a.add('button', undefined, 'OK'); a.show(); \ + var b = new Window('dialog', 'B'); b.add('button', undefined, 'OK'); vc.log(b.show());", + ); + assert!(until_window(&mut app)); + let first = app.session.script_window().unwrap().shown; + dialogs::script_run::ask_to_close(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(CLOSE_KIND)); + app.session.script_window_answer(UiEvent::Click(1)).unwrap(); + for _ in 0..10_000 { + if app.session.script_window().is_some_and(|w| w.shown != first) { + break; + } + script_runs::poll(&mut app); + } + assert_eq!(app.session.script_window().map(|w| w.title().to_string()), Some("B".to_string()), "the run waits at the second show()"); + dialogs::script_run::settle_close(&mut app); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.kind, CLOSE_KIND); + assert!(!d.fields.contains_key(dialogs::PARENT), "the first dialog is forgotten"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn ui_dialog_confirm_takes_a_whole_float_as_a_list_index_and_refuses_a_fraction() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 546f865d5f..6c14c23906 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2948,7 +2948,9 @@ cancel button, or closes the dialog when it has none. Quitting while it waits, o asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the -script the text still typed in the dialog's fields. A disabled or hidden control, a value out of a list's range, a +script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets +no event and every field keeps its text: `ui.dialog.confirm` returns an error, and Escape and `ui.dialog.cancel` show +it in the status bar. A disabled or hidden control, a value out of a list's range, a list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays open. From d1ba7d4f021b4224b9b65ffd59a7d9f75929a9a1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:08:12 -0800 Subject: [PATCH 04/29] Scripts: ui.dialog.cancel returns the error of a refused typed text ui.dialog.cancel, and ui.dialog.set with action cancel, now return the error when a ScriptUI dialog holds a typed text longer than 16 KiB, as ui.dialog.confirm does. The dialog stays open with every field as it was. Escape still shows the error in the status bar. --- crates/ui-egui/src/control.rs | 13 +++++-------- crates/ui-egui/src/dialogs.rs | 21 +++++++++++++++------ crates/ui-egui/src/tests/script_window.rs | 7 +++++++ docs/mcp.md | 4 ++-- 4 files changed, 29 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 218312750d..f14186a1b4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1647,19 +1647,16 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlRequest) Ok(result) => ok(json!({"dialog": dialog, "result": result})), Err(e) => err(e), }, - Some(DialogAnswer::Cancel) => { - crate::dialogs::cancel(app); - ok(json!({"dialog": dialog, "result": null})) - } + Some(DialogAnswer::Cancel) => match crate::dialogs::try_cancel(app) { + Ok(()) => ok(json!({"dialog": dialog, "result": null})), + Err(e) => err(e), + }, } } None => err("no dialog open"), }, "ui.dialog.confirm" => wrap(crate::dialogs::confirm(app)), - "ui.dialog.cancel" => { - crate::dialogs::cancel(app); - ok(Value::Null) - } + "ui.dialog.cancel" => wrap(crate::dialogs::try_cancel(app).map(|()| Value::Null)), "ui.resize" => { let (w, h) = match coord(p, "width", 1440.0).and_then(|w| Ok((w, coord(p, "height", 900.0)?))) { Ok(size) => size, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index cc98a59374..6b59f7bd88 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -770,14 +770,24 @@ pub(crate) fn field_set(app: &mut VectorcraftApp, field: &str, old: Option<&Valu } /// Close the open dialog as Cancel does, rolling back a live preview and showing the dialog it was -/// opened over (`ui.dialog.cancel`). +/// opened over (Escape and the dialog's Cancel button). An error from [`try_cancel`] goes to the +/// status bar. pub fn cancel(app: &mut VectorcraftApp) { + if let Err(e) = try_cancel(app) { + app.status(e); + } +} + +/// [`cancel`], returning the error of a ScriptUI dialog whose typed text the script would refuse +/// (`ui.dialog.cancel`). That dialog stays open with its fields as they were. +pub fn try_cancel(app: &mut VectorcraftApp) -> Result<(), String> { cancel_brush_key_color(app, true); missing_fonts::requeue_replaced(app); // More Settings' pop-up and Save Preset end on their own; New Document stays. if app.ui.dialog.as_mut().is_some_and(new_document::close_popup) { - return; + return Ok(()); } + let mut result = Ok(()); if let Some(mut d) = app.ui.dialog.take() { if d.kind == "preferences" { crate::original_editor::cancel(app); @@ -813,10 +823,8 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::PICKER_KIND { script_run::picker_cancel(app, &d); } - if d.kind == script_window::KIND - && let Err(e) = script_window::cancel(app, &mut d) - { - app.status(e); + if d.kind == script_window::KIND { + result = script_window::cancel(app, &mut d); } missing_links::cancelled(app, &d); // Cancel discards Recolor Artwork's own history of color edits with them. @@ -844,6 +852,7 @@ pub fn cancel(app: &mut VectorcraftApp) { } } settle(app); + result } /// Whether the open dialog has a Reset ([`DialogSpec::reset`]). diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 49ef7abd18..e6221eb092 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -313,6 +313,13 @@ fn a_typed_text_the_script_refuses_keeps_every_field_and_queues_nothing() { assert!(script_window::cancel(&mut app, &mut d).is_err(), "Cancel is an error"); dialogs::cancel(&mut app); kept(&app); + let ctx = egui::Context::default(); + for (method, params) in [("ui.dialog.cancel", json!({})), ("ui.dialog.set", json!({"fields": [], "action": "cancel"}))] { + let (req, _) = crate::control::ControlRequest::new(method, params); + let crate::control::Outcome::Done(r) = crate::control::handle(&mut app, &ctx, &req) else { panic!("{method}: not done") }; + assert_eq!(r["ok"], false, "{method} answers with the error: {r}"); + kept(&app); + } assert!(app.session.script_window().is_some(), "the script still waits"); app.ui.dialog.as_mut().unwrap().fields.remove("text1"); give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); diff --git a/docs/mcp.md b/docs/mcp.md index 6c14c23906..11fded84c1 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2949,8 +2949,8 @@ asks whether to stop the script, and Cancel shows it again with the events it ha `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets -no event and every field keeps its text: `ui.dialog.confirm` returns an error, and Escape and `ui.dialog.cancel` show -it in the status bar. A disabled or hidden control, a value out of a list's range, a +no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action` +return an error, and Escape shows it in the status bar. A disabled or hidden control, a value out of a list's range, a list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays open. From 7578da1824f94ce16fd329de611168433f1f3886 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:23:48 -0800 Subject: [PATCH 05/29] Scripts: screen readers call a ScriptUI control by its visible prompt first An edit field, list, slider or progress bar with a visible static text just before it in its container is now named by that text, and by the name the script gave it only when there is none. Before, a script's name replaced the visible prompt. --- crates/ui-egui/src/dialogs/script_window.rs | 20 ++++++++++---------- crates/ui-egui/src/tests/script_window.rs | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 7bebdbf174..93a81f417f 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -299,8 +299,8 @@ fn control(ui: &mut egui::Ui, d: &mut Dialog, origin: egui::Pos2, (i, n, prompt) } /// Screen readers call a control with no visible label of its own (an edit field, a slider or a -/// progress bar) by the name the script gave it, or else a slider or progress bar by its text, and -/// an edit field by the visible static text just before it in its container. +/// progress bar) by the visible static text just before it in its container, or else by the name +/// the script gave it, or else a slider or progress bar by its text. fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode, prompt: &str) { let label = screen_reader_name(n, prompt); if !label.is_empty() { @@ -308,20 +308,20 @@ fn name_for_screen_readers(ui: &egui::Ui, r: &egui::Response, n: &UiNode, prompt } } -/// The name screen readers call a list box or a drop-down list `n` by: the name the script gave it, -/// or else the visible static text just before it. Empty for none. +/// The name screen readers call a list box or a drop-down list `n` by: the visible static text +/// just before it, or else the name the script gave it. Empty for none. fn list_name(n: &UiNode, prompt: &str) -> String { - if n.name.is_empty() { prompt.to_string() } else { n.name.clone() } + if prompt.is_empty() { n.name.clone() } else { prompt.to_string() } } /// The name [`name_for_screen_readers`] gives control `n`; empty for none. pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { - if !n.name.is_empty() { - n.name.clone() - } else if n.kind != UiKind::EditText { - n.text.clone() - } else { + if !prompt.is_empty() { prompt.to_string() + } else if !n.name.is_empty() || n.kind == UiKind::EditText { + n.name.clone() + } else { + n.text.clone() } } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index e6221eb092..2d68a9e6a6 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -392,7 +392,7 @@ fn an_unnamed_edit_field_is_called_by_the_static_text_before_it() { assert_eq!(name(4), "height", "the name the script gave it"); assert_eq!(name(5), "", "the control before it is no static text"); assert_eq!(name(7), "", "a hidden static text is no prompt"); - assert_eq!(name(9), "user", "a name the script gave goes before the text before it"); + assert_eq!(name(9), "Account", "the visible text before it goes before the name the script gave"); app.session.script_request_stop(); assert!(!until_window(&mut app)); } From cd646a9b344b2d2029ffc0293d2c720cd26b2d6c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 06:41:16 -0800 Subject: [PATCH 06/29] Scripts: a ScriptUI edit field keeps a refused text after it loses the focus A text longer than 16 KiB that an edit field gives as it loses the focus now goes back in the field, with the error in the status bar, instead of being dropped when the next frame draws the script's old text. The field keeps it until the person changes it. --- crates/ui-egui/src/dialogs/script_window.rs | 24 ++++++++++++++++++++- crates/ui-egui/src/tests/script_window.rs | 22 +++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 93a81f417f..158a86ea5b 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -108,6 +108,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if events.is_empty() && waiting && !typing && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { events.extend(w.default_element.map(UiEvent::Click)); } + if let Some(e) = keep_refused_texts(&w, d, &mut events) { + app.status(e); + } if events.iter().any(|e| matches!(e, UiEvent::Click(_))) && let Err(e) = commit_drafts(&w, d, &mut events) { @@ -176,6 +179,24 @@ pub(crate) fn commit_drafts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec Ok(()) } +/// Takes out of `events` each text an edit field gave as it lost the focus that the script would +/// refuse, and puts it back in its field, so the person can fix it. → the error of the last one. +pub(crate) fn keep_refused_texts(w: &ScriptUiDialog, d: &mut Dialog, events: &mut Vec) -> Option { + let mut refused = None; + events.retain(|e| { + let UiEvent::Change(i, UiValue::Text(text)) = e else { return true }; + match vectorcraft_engine::script::scriptui::check_event(w, e.clone()) { + Ok(_) => true, + Err(error) => { + d.fields.insert(draft_key(*i), json!(text)); + refused = Some(error); + false + } + } + }); + refused +} + /// The field that holds an edit field's text while it is typed. fn draft_key(i: usize) -> String { format!("text{i}") @@ -341,7 +362,8 @@ fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (us d.fields.remove(&key); return Some(UiEvent::Change(i, UiValue::Text(text))); } - if !r.has_focus() && !r.changed() { + // A text the script refused stays in the field until the person changes it. + if !r.has_focus() && !r.changed() && (text == n.text || n.readonly) { d.fields.remove(&key); } None diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 2d68a9e6a6..2e2cd186ca 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -330,6 +330,28 @@ fn a_typed_text_the_script_refuses_keeps_every_field_and_queues_nothing() { assert_eq!(log(&app), json!([1])); } +#[test] +fn a_typed_text_the_script_refuses_stays_in_its_field_after_it_loses_the_focus() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let long = "x".repeat(16 * 1024 + 1); + let d = app.ui.dialog.as_mut().unwrap(); + let mut events = vec![UiEvent::Change(1, UiValue::Text(long.clone())), UiEvent::Change(1, UiValue::Text("fine".into()))]; + assert!(script_window::keep_refused_texts(&w, d, &mut events).is_some(), "the long text is an error"); + assert_eq!(events, vec![UiEvent::Change(1, UiValue::Text("fine".into()))], "a text the script takes is still given"); + assert!(d.fields.get("text1") == Some(&json!(long)), "the refused text goes back in its field"); + frame(&mut app, Vec::new()); + frame(&mut app, Vec::new()); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert!(d.fields.get("text1") == Some(&json!(long)), "and stays there while the field has no focus"); + assert!(app.session.script_window().is_some(), "the script still waits"); + assert!(give(&mut app, json!({"event": "click", "control": "OK"})).is_err(), "OK is an error until it is fixed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 11fded84c1..951edebb05 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2950,7 +2950,8 @@ asks whether to stop the script, and Cancel shows it again with the events it ha its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action` -return an error, and Escape shows it in the status bar. A disabled or hidden control, a value out of a list's range, a +return an error, and Escape shows it in the status bar. Such a text stays in its field when the field loses the +focus too, with the error in the status bar. A disabled or hidden control, a value out of a list's range, a list index that is not a whole number and a click on a control that takes none are errors, and the dialog stays open. From 405f59325a3d0a7d3ba14647e1f41b353fdcc661 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 07:39:02 -0800 Subject: [PATCH 07/29] Tests: a refused ScriptUI text stays in its field when a click on a button takes the focus The test clicks into an edit field, types a text longer than 16 KiB and clicks OK with egui pointer events. It checks that the text stays in the field, that nothing is queued for the script, that the status bar shows the error and that the script still waits. --- crates/ui-egui/src/tests/script_window.rs | 43 +++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 2e2cd186ca..0b750438b0 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -352,6 +352,49 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_after_it_loses_the_focus() assert!(!until_window(&mut app)); } +#[test] +fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_takes_the_focus() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + let ctx = CTX.with(Clone::clone); + ctx.enable_accesskit(); + frame(&mut app, Vec::new()); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let nodes = out.platform_output.accesskit_update.expect("an accessibility tree").nodes; + let center = |found: Option<&egui::accesskit::Node>, what: &str| { + let b = found.and_then(egui::accesskit::Node::bounds).unwrap_or_else(|| panic!("no {what}")); + egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) + }; + let field = center(nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput), "edit field"); + let ok = center(nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Button && n.label() == Some("OK")), "OK button"); + let click = |app: &mut VectorcraftApp, at: egui::Pos2| { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![button(true)]); + frame(app, vec![button(false)]); + }; + click(&mut app, field); + let long = "x".repeat(16 * 1024 + 1); + frame(&mut app, vec![egui::Event::Text(long.clone())]); + let typed = app.ui.dialog.as_ref().and_then(|d| d.fields.get("text1")).and_then(Value::as_str).map(str::to_string); + let typed = typed.expect("the typed text is kept while the field has the focus"); + assert!(typed.len() > 16 * 1024 && typed.contains(&long), "the field holds the long text"); + click(&mut app, ok); + frame(&mut app, Vec::new()); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.kind, KIND); + assert!(d.fields.get("text1") == Some(&json!(typed)), "the refused text stays in its field"); + assert!(!d.fields.contains_key("queued"), "nothing is queued"); + assert!(app.ui.status.contains("16 KiB"), "the error is in the status bar: {}", app.ui.status); + assert!(app.session.script_window().is_some(), "the script still waits"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); From b8c37560febbad8f5e9f36ac64016e78897e5aca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 22 Nov 2026 10:41:30 -0800 Subject: [PATCH 08/29] Scripts: queued ScriptUI events and typed texts survive the growth question and added controls When a handler takes the run past its growth limit, the question to continue now opens over the ScriptUI dialog, and Continue shows the dialog again with the events the script has not had yet and the text typed in its fields. A queued click or change keeps where its control sits in the dialog, and a typed text keeps where its field sits, so both reach the same control after a handler adds controls before it. --- crates/ui-egui/src/dialogs/script_run.rs | 7 +- crates/ui-egui/src/dialogs/script_window.rs | 112 +++++++++++++++++--- crates/ui-egui/src/script_runs.rs | 28 +++-- crates/ui-egui/src/tests/script_window.rs | 89 ++++++++++++++++ docs/mcp.md | 5 +- 5 files changed, 210 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index 9b65d0b96a..c7317f1a6b 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -177,8 +177,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { app.run("script.run", script) } -fn growth_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result { - app.ui.dialog = None; +/// Continue: the run goes on, and the ScriptUI dialog the question was asked over, when its +/// `show()` has not ended, opens again as it was. +fn growth_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let showing = app.session.script_window_showing(); + app.ui.dialog = super::parent(d).filter(|p| showing.as_ref().is_some_and(|w| super::script_window::is_open_for(p, w))); app.session.script_continue(); Ok(Value::Null) } diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 158a86ea5b..88d53cac21 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -76,6 +76,7 @@ fn shown(app: &VectorcraftApp, ctx: &egui::Context) -> Option<(Arc DialogAction { let Some((w, waiting)) = shown(app, ui.ctx()) else { return DialogAction::None }; + move_drafts(&w, d); let mut events = Vec::new(); let (width, height) = w.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); @@ -118,11 +119,12 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc events.retain(|e| !matches!(e, UiEvent::Click(_))); app.status(e); } + note_draft_places(&w, d); let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, _ => Vec::new(), }; - queue.extend(events.iter().map(event_fields)); + queue.extend(events.iter().map(|e| event_fields(&w, e))); if !waiting || queue.is_empty() { if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); @@ -133,12 +135,48 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } - if let Value::Object(fields) = next { + if let Value::Object(mut fields) = next { + // The control the event was given to, found again in the dialog as the handlers that ran + // since left it. + let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); + if let Some(i) = at { + fields.insert("control".into(), json!(i)); + } d.fields.extend(fields); } DialogAction::Confirm } +/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). +const PLACE_KEY: &str = "place"; + +/// Where control `i` sits in the dialog `w`: its position among its container's controls, after +/// its container's own position, and so on up to the dialog. `add` puts a new control after the +/// others in its container, so a handler that adds controls leaves the place of every other one +/// as it was, while its index in the dialog's list of elements can move. +fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { + let mut place = Vec::new(); + while i > 0 { + let Some(n) = w.nodes.get(i) else { return Vec::new() }; + place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); + if n.parent >= i { + return Vec::new(); + } + i = n.parent; + } + place.reverse(); + place +} + +/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. +fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { + let mut at = 0; + for &k in place { + at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; + } + (at > 0).then_some(at) +} + /// The field that holds the events the person gave in one frame that the script has not had yet; /// the script takes one event each time it waits. const QUEUE_KEY: &str = "queued"; @@ -202,6 +240,37 @@ fn draft_key(i: usize) -> String { format!("text{i}") } +/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) +/// in the dialog the text was typed in. +const DRAFT_PLACES_KEY: &str = "draftPlaces"; + +/// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. +fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { + let places: serde_json::Map = + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + if places.is_empty() { + d.fields.remove(DRAFT_PLACES_KEY); + } else { + d.fields.insert(DRAFT_PLACES_KEY.into(), Value::Object(places)); + } +} + +/// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the +/// dialog `w`, which moves when a handler adds controls before the field. A text whose field the +/// dialog no longer has is dropped. +fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { + let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; + let mut moved = Vec::new(); + for (key, place) in places { + let Some(text) = d.fields.remove(&key) else { continue }; + let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { + moved.push((draft_key(i), text)); + } + } + d.fields.extend(moved); +} + /// The text of the visible static text just before control `i` in its container: the visible prompt /// of an edit field, a list box or a drop-down list, which screen readers call one without a name /// by. Empty when there is none. @@ -369,16 +438,21 @@ fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (us None } -/// `event` as the dialog's `event`, `control` and `value` fields. -fn event_fields(event: &UiEvent) -> Value { +/// `event` in the dialog `w` as the dialog's `event`, `control` and `value` fields, and for a +/// click or a change, the control's place ([`PLACE_KEY`]). +fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { let (name, control, value) = match event { - UiEvent::Click(i) => ("click", json!(i), Value::Null), - UiEvent::Change(i, UiValue::Text(t)) => ("change", json!(i), json!(t)), - UiEvent::Change(i, UiValue::Number(v)) => ("change", json!(i), json!(v)), - UiEvent::Change(i, UiValue::Index(k)) => ("change", json!(i), json!(k)), - UiEvent::Close => ("close", Value::Null, Value::Null), + UiEvent::Click(i) => ("click", Some(*i), Value::Null), + UiEvent::Change(i, UiValue::Text(t)) => ("change", Some(*i), json!(t)), + UiEvent::Change(i, UiValue::Number(v)) => ("change", Some(*i), json!(v)), + UiEvent::Change(i, UiValue::Index(k)) => ("change", Some(*i), json!(k)), + UiEvent::Close => ("close", None, Value::Null), }; - json!({"event": name, "control": control, "value": value}) + let mut fields = json!({"event": name, "control": control, "value": value}); + if let Some(i) = control { + fields[PLACE_KEY] = json!(place_of(w, i)); + } + fields } /// The event in the dialog's fields, for the dialog `w`. @@ -416,10 +490,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { vectorcraft_engine::script::scriptui::check_event(&w, event.clone())?; let mut events = vec![event]; let open = app.ui.dialog.as_mut().filter(|open| open.kind == KIND); - if let Some(open) = open - && matches!(events[0], UiEvent::Click(_) | UiEvent::Close) - { - commit_drafts(&w, open, &mut events)?; + if let Some(open) = open { + move_drafts(&w, open); + let committed = if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { commit_drafts(&w, open, &mut events) } else { Ok(()) }; + note_draft_places(&w, open); + committed?; } let mut events = events.into_iter(); if let Some(first) = events.next() { @@ -429,7 +504,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { for k in ["event", "control", "value"] { open.fields.remove(k); } - let later: Vec = events.map(|e| event_fields(&e)).collect(); + let later: Vec = events.map(|e| event_fields(&w, &e)).collect(); if !later.is_empty() { let mut queue = match open.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, @@ -450,7 +525,10 @@ pub(crate) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str let Some(w) = app.session.script_window() else { return Ok(()) }; let click = w.cancel_element.map(UiEvent::Click).filter(|e| vectorcraft_engine::script::scriptui::check_event(&w, e.clone()).is_ok()); let mut events = vec![click.unwrap_or(UiEvent::Close)]; - commit_drafts(&w, d, &mut events)?; + move_drafts(&w, d); + let committed = commit_drafts(&w, d, &mut events); + note_draft_places(&w, d); + committed?; let mut queue: Vec = match d.fields.remove(QUEUE_KEY) { Some(Value::Array(queue)) => queue, _ => Vec::new(), @@ -461,7 +539,7 @@ pub(crate) fn cancel(app: &mut VectorcraftApp, d: &mut Dialog) -> Result<(), Str { let _ = app.session.script_window_answer(first); } - queue.extend(events.map(|e| event_fields(&e))); + queue.extend(events.map(|e| event_fields(&w, &e))); if !queue.is_empty() { d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 27e74d820e..b51385713a 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -77,6 +77,21 @@ fn ask(app: &mut VectorcraftApp) -> bool { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::NOTICE_KIND) { app.ui.dialog = None; } + // A run past its growth allowance asks about it first, also when its ScriptUI dialog waits + // again. The question keeps the dialog of the show() the run is in, with its queued events and + // typed text, for Continue to show again. + if app.session.script_waiting() { + let window = app.ui.dialog.take_if(|d| d.kind == script_window::KIND); + if app.ui.dialog.is_none() { + let showing = app.session.script_window_showing(); + let mut fields = json!({}); + if let Some(window) = window.filter(|d| showing.as_ref().is_some_and(|w| script_window::is_open_for(d, w))) { + fields[crate::dialogs::PARENT] = serde_json::to_value(window).unwrap_or_default(); + } + app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, fields)); + } + return true; + } if let Some(window) = app.session.script_window() { // A dialog the script showed after closing the one that is open replaces it. if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND && !script_window::is_open_for(d, &window)) { @@ -91,19 +106,10 @@ fn ask(app: &mut VectorcraftApp) -> bool { } return true; } - // While a handler runs, the ScriptUI dialog stays open, until its show() ends or the run asks - // about its growth. - if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) - && (app.session.script_waiting() || app.session.script_window_showing().is_none()) - { + // While a handler runs, the ScriptUI dialog stays open, until its show() ends. + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_window::KIND) && app.session.script_window_showing().is_none() { app.ui.dialog = None; } - if app.session.script_waiting() { - if app.ui.dialog.is_none() { - app.ui.dialog = Some(Dialog::new(script_run::GROWTH_KIND, json!({}))); - } - return true; - } false } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 0b750438b0..ad6533004a 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -395,6 +395,95 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t assert!(!until_window(&mut app)); } +#[test] +fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); \ + e.onChange = function () { p.add('statictext', undefined, 'Added'); }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + app.ui.dialog.as_mut().unwrap().fields.insert("text2".into(), json!("typed")); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(until_window(&mut app), "the script takes the text and waits again"); + let w = app.session.script_window().unwrap(); + assert_eq!(w.nodes[4].text, "OK", "the handler added a control before OK"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_and_typed_text() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var g = w.add('button', undefined, 'Grow'); \ + w.add('button', undefined, 'OK'); g.onClick = function () { vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text1".into(), json!("typed")); + d.fields.insert("queued".into(), json!([{"event": "click", "control": 3, "value": null}])); + for _ in 0..10_000 { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::script_run::GROWTH_KIND) { + break; + } + assert!(app.session.script_running(), "the run asks about its growth"); + script_runs::poll(&mut app); + } + let question = app.ui.dialog.clone().expect("the growth question"); + assert_eq!(question.kind, dialogs::script_run::GROWTH_KIND); + dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().expect("Continue shows the dialog again"); + assert_eq!(d.kind, KIND); + assert_eq!(d.fields.get("text1"), Some(&json!("typed")), "with the text typed in its field"); + assert!(d.fields.contains_key("queued"), "and the click still queued"); + assert!(until_window(&mut app), "the script waits at its dialog again"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the typed text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + +#[test] +fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_and_the_run_grows() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var p = w.add('panel'); var e = w.add('edittext', undefined, 'a'); \ + var g = w.add('button', undefined, 'Grow'); w.add('button', undefined, 'OK'); g.onClick = function () { \ + p.add('statictext', undefined, 'Added'); vc.run('shape.rectangle', {x:0,y:0,width:10,height:10}); \ + for (var k = 0; k < 17; k++) { vc.run('select.all'); vc.run('edit.duplicate'); } }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + frame(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("text2".into(), json!("typed")); + d.fields.insert("queued".into(), json!([{"event": "click", "control": 4, "value": null, "place": [3]}])); + frame(&mut app, Vec::new()); + for _ in 0..10_000 { + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::script_run::GROWTH_KIND) { + break; + } + assert!(app.session.script_running(), "the run asks about its growth"); + script_runs::poll(&mut app); + } + dialogs::confirm(&mut app).unwrap(); + assert!(until_window(&mut app), "the script waits at its dialog again"); + assert_eq!(app.session.script_window().unwrap().nodes[3].text, "a", "the handler added a control before the edit field"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script takes the typed text and waits again"); + frame(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + assert_eq!(log(&app), json!([[1, "typed"]])); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 951edebb05..d376a5623b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2945,7 +2945,10 @@ which ends the run as `script.stop` does. It stays open while one of its handler returns. Enter outside a field clicks the default button, also with the keyboard focus on a slider or another control that Enter does not click. Escape clicks the cancel button, or closes the dialog when it has none. Quitting while it waits, or while one of its handlers runs, -asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. +asks whether to stop the script, and Cancel shows it again with the events it has not given the script yet. When a +handler takes the run past the growth limit, the question to continue opens over the dialog, and Continue shows the +dialog again with those events and the text typed in its fields. An event that waits for the script goes to the control +it was given to, and a typed text stays in its field, also after a handler adds controls before that one. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets From 29153af625af105cf3d0b4d3d1fcb5852ba85706 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 11:35:40 -0800 Subject: [PATCH 09/29] Scripts: ScriptUI controls take size objects, event listeners, list find and remove, and Window.alert - Every element starts with preferredSize, size, minimumSize and maximumSize objects whose width and height are -1, so a script can set one side, as in preferredSize.width = 100. A positive side of size takes the place of preferredSize's, and the layout keeps a control within its minimum and maximum. - Controls and the dialog take addEventListener and removeEventListener for click, change, changing and show. Handlers run in the capture phase on the containers, on the control after its onClick, onChange or onChanging, then on the containers again until one calls stopPropagation(). A button with a click listener no longer closes the dialog by itself. - Window.alert, Window.confirm and Window.prompt open the same dialogs as alert, confirm and prompt. - A list has find(text) and remove(what), and takes its items in properties.items; a container has remove(what). - A group takes its creation properties as the third argument of add(), and orientation, alignChildren, spacing, margins and alignment given there are its first values. - Setting a radio button's value to true turns off the radio buttons added next to it in its container, and notify("onClick") turns a radio button on and a check box over before onClick runs. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/scriptui.rs | 21 +- crates/engine/src/tests/script_scriptui.rs | 22 + .../tests/it/script_host_vs_scriptcheck.rs | 4 +- crates/js/src/scriptui.rs | 530 ++++++++++++++++-- crates/js/src/scriptui_tests.rs | 109 ++++ docs/mcp.md | 59 +- docs/target-app-parity.md | 2 +- 8 files changed, 681 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index fd02b3a9a1..6729537b5a 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, 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); show() waits like a dialog function, runs onClick, onChanging, onChange, onShow and onClose 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 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, 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 acts as a click or change, addEventListener and removeEventListener take click, change, changing and show (other event types throw that they are not available yet), 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, 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/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 2f77fbb5b8..f3520b41cc 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -11,8 +11,9 @@ //! or progress bar's value to its range. //! //! The layout follows each container's `orientation` (row, column or stack), `alignChildren`, -//! `spacing` and `margins`, a control's `alignment`, `preferredSize` and `bounds` (left, top, right -//! and bottom in its container). A control's size comes from its text, items and kind, by +//! `spacing` and `margins`, a control's `alignment`, `preferredSize` (or `size`), `minimumSize`, +//! `maximumSize` and `bounds` (left, top, right and bottom in its container); a width or height of +//! 0 or less in a size leaves that side to the layout. A control's size comes from its text, items and kind, by //! VectorCraft's own estimates of a 7-pixel character and a 16-pixel line. The layout is worked out //! with loops over the list, from the last control to the first for sizes and from the first to the //! last for places, so a description's nesting takes no native stack. @@ -145,6 +146,8 @@ pub struct UiNode { spacing: f32, margins: [f32; 4], size: [Option; 2], + min_size: [Option; 2], + max_size: [Option; 2], bounds: Option, } @@ -482,7 +485,11 @@ pub fn parse(d: &Data) -> Result { let (l, t) = (extent(l), extent(t)); UiRect { x: l, y: t, w: (extent(r) - l).clamp(0.0, MAX_EXTENT), h: (extent(b) - t).clamp(0.0, MAX_EXTENT) } }); - let size = numbers::<2>(field(f, "size"))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))]); + // A width or height of 0 or less leaves that side to the layout. + let sides = |name: &str| -> Result<[Option; 2], HostError> { + Ok(numbers::<2>(field(f, name))?.map_or([None, None], |[w, h]| [(w > 0.0).then(|| extent(w)), (h > 0.0).then(|| extent(h))])) + }; + let (size, min_size, max_size) = (sides("size")?, sides("min")?, sides("max")?); let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); nodes.push(UiNode { kind, @@ -506,6 +513,8 @@ pub fn parse(d: &Data) -> Result { spacing: number(field(f, "spacing")).map_or(0.0, |s| extent(s).max(0.0)), margins, size, + min_size, + max_size, bounds, }); } @@ -578,6 +587,12 @@ fn layout(d: &mut ScriptUiDialog) { if let Some(v) = node.size[axis] { s[axis] = v; } + if let Some(v) = node.min_size[axis] { + s[axis] = s[axis].max(v); + } + if let Some(v) = node.max_size[axis] { + s[axis] = s[axis].min(v); + } } if let Some(b) = node.bounds { s = [b.w, b.h]; diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 19c5cf5c80..7536020534 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -316,6 +316,28 @@ fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); } +#[test] +fn a_control_s_size_keeps_within_its_minimum_and_maximum() { + let dialog = node("dialog", -1.0); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let wide = with(with(node("button", 0.0), "size", pair(300.0, -1.0)), "max", pair(120.0, -1.0)); + let tall = with(with(node("button", 0.0), "size", pair(-1.0, -1.0)), "min", pair(-1.0, 60.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), wide, tall])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 120.0, "the maximum width holds over a larger size"); + assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate"); + let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap(); + assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate"); +} + +#[test] +fn window_s_alert_confirm_and_prompt_open_the_script_dialogs() { + let mut s = one_doc(); + let answers = json!([{"kind": "alert", "value": "ok"}, {"kind": "confirm", "value": false}, {"kind": "prompt", "value": "typed"}]); + let r = headless(&mut s, "vc.log([typeof Window.alert('Hi'), Window.confirm('Go?'), Window.prompt('Name', 'x')]);", answers).unwrap(); + assert_eq!(r["log"], json!([["undefined", false, "typed"]]), "{r}"); + assert_eq!(r["dialogCount"], 3); +} + /// A description of arbitrary kinds, containers in any order, numbers of any size (infinite and /// not-a-number ones included) and texts of any length. fn any_description() -> impl proptest::strategy::Strategy { diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 800b0f35df..07c92f5682 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -44,8 +44,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[ /// change anything outside it. const INSIDE: &[(&str, &str)] = &[ ("", "$ File Folder Window alert confirm localize prompt toSource"), - ("Window.", "length prototype"), - ("Window.prototype.", "add center close constructor findElement hide show"), + ("Window.", "alert confirm length prompt prototype"), + ("Window.prototype.", "add addEventListener center close constructor findElement hide remove removeEventListener show"), ("Object.prototype.", "toSource"), ("localize.", "length"), ("toSource.", "length"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index f2f8a33b2c..76d4911632 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -9,8 +9,21 @@ //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet. A -//! list's `add("item", text)` adds an item; its `selection` is an item or `null`, and takes an -//! item, an index or `null`. +//! group takes its creation properties as the third argument, and a list takes them there in place +//! of its items, with the items in `properties.items`. A list's `add("item", text)` adds an item, +//! `find(text)` finds one and `remove(what)` removes one; its `selection` is an item or `null`, and +//! takes an item, an index or `null`. A container's `remove(what)` removes a control. Each element +//! starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose `width` and +//! `height` are -1, which leaves the size to the layout. Setting a radio button's `value` to true +//! sets the other radio buttons next to it in its container to false, as a click does. +//! +//! `addEventListener(type, handler[, capture])` and `removeEventListener` register handlers for +//! the events `show()` runs: `click`, `change`, `changing` and `show`. A handler gets an event +//! object, in the capture phase on the containers above the control, then on the control after its +//! `onClick`, `onChange` or `onChanging`, then in the bubbling phase on the containers again, until +//! one calls `stopPropagation()`. `notify(event)` runs the same handlers, and `notify("onClick")` +//! turns a check box over and turns a radio button on first. `Window.alert`, `Window.confirm` and +//! `Window.prompt` are the global functions of those names, when the host defines them. //! //! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the //! dialog closes, it gives the host's `wait` the description again, and `wait` gives back what the @@ -33,8 +46,8 @@ //! and a list that changes again throws an `Error`. use crate::HostItem; -use crate::builtins::{arg, constructor, method, native, pausable_method}; -use crate::heap::{Class, ENUMERABLE, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key}; +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::value::{Value, index_key}; @@ -66,6 +79,32 @@ const CLOSING: &str = "__vcClosing"; const ITEMS: &str = "__vcItems"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; +const VALUE: &str = "__vcValue"; +const LISTENERS: &str = "__vcListeners"; +const STOPPED: &str = "__vcStopped"; +const PREVENTED: &str = "__vcPrevented"; + +/// The size properties every element starts with, as objects with `width` and `height`. +const SIZES: [&str; 4] = ["preferredSize", "size", "minimumSize", "maximumSize"]; +/// The events `addEventListener` takes, which `show()` and `notify` run. +const EVENTS: [&str; 4] = ["click", "change", "changing", "show"]; +/// The other documented events, which nothing runs yet. +const EVENTS_LATER: [&str; 14] = [ + "move", + "moving", + "resize", + "resizing", + "enterKey", + "focus", + "blur", + "mousedown", + "mouseup", + "mousemove", + "mouseover", + "mouseout", + "keyup", + "keydown", +]; /// The objects of `Window`, kept by the realm, and the dialog that is showing. #[derive(Clone, Debug)] @@ -73,17 +112,31 @@ pub(crate) struct Classes { window_proto: ObjId, control_proto: ObjId, item_proto: ObjId, + event_proto: ObjId, layout: ObjId, host: ObjId, selection_get: ObjId, selection_set: ObjId, + radio_get: ObjId, + radio_set: ObjId, showing: Option, } impl Classes { /// The objects a collection keeps. pub(crate) fn objects(&self) -> Vec { - let mut all = vec![self.window_proto, self.control_proto, self.item_proto, self.layout, self.host, self.selection_get, self.selection_set]; + let mut all = vec![ + self.window_proto, + self.control_proto, + self.item_proto, + self.event_proto, + self.layout, + self.host, + self.selection_get, + self.selection_set, + self.radio_get, + self.radio_set, + ]; all.extend(self.showing); all } @@ -254,7 +307,12 @@ fn new_element( set_open(i, o, "bounds", bounds.clone())?; } set_open(i, o, "layout", Value::Object(layout))?; - if matches!(kind, "dialog" | "group" | "panel") { + for name in SIZES { + let d = dimension(i, -1.0, -1.0)?; + set_open(i, o, name, d)?; + } + let container = matches!(kind, "dialog" | "group" | "panel"); + if container { let kids = list(i, &[], false)?; set_slot(i, o, KIDS, Value::Object(kids))?; let children = list(i, &[], true)?; @@ -264,9 +322,28 @@ fn new_element( set_open(i, o, "spacing", Value::Number(10.0))?; set_open(i, o, "margins", Value::Number(if kind == "group" { 0.0 } else { 15.0 }))?; } + // Layout properties given with the creation properties start the element with those values. + let layout_names: &[&str] = if container { &["alignment", "orientation", "alignChildren", "spacing", "margins"] } else { &["alignment"] }; + for name in layout_names { + let v = i.get_value(&props, &key(name))?; + if !matches!(v, Value::Undefined) { + set_open(i, o, name, v)?; + } + } Ok(o) } +/// A new size object with `width` and `height`. +fn dimension(i: &mut Interp, width: f64, height: f64) -> JsResult { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(2)))?; + let o = i.new_object(); + i.rooted(&[Value::Object(o)], |i| { + set_open(i, o, "width", Value::Number(width))?; + set_open(i, o, "height", Value::Number(height))?; + Ok(Value::Object(o)) + }) +} + /// `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(); @@ -330,19 +407,44 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); } - let props = arg(args, 3); let list_kind = ty == "dropdownlist" || ty == "listbox"; - if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { - return Err(error(i, "add: a list box that selects several items is not available yet")); - } + let third = arg(args, 2); + let is_array = |i: &Interp, v: &Value| -> JsResult { + Ok(match v.as_object() { + Some(a) => matches!(i.object(a)?.class, Class::Array { .. }), + None => false, + }) + }; + // A group takes its creation properties third, and so may a list in place of its items. + let props_third = ty == "group" || (list_kind && third.as_object().is_some() && !is_array(i, &third)?); + let props = if props_third { third.clone() } else { arg(args, 3) }; let proto = classes(i)?.control_proto; let mark = i.temp_roots.len(); let r = (|| { + let mut given_items = if list_kind && !props_third { third.clone() } else { Value::Undefined }; + if list_kind && props.as_object().is_some() { + let listed = i.get_value(&props, &key("items"))?; + i.temp_roots.push(listed.clone()); + if !matches!(listed, Value::Undefined | Value::Null) { + if !matches!(given_items, Value::Undefined | Value::Null) { + return Err(i.type_error("add: give a list's items as the third argument or in properties.items, not both")); + } + given_items = listed; + } + } + if ty == "listbox" && props.as_object().is_some() && i.get_value(&props, &key("multiselect"))?.truthy() { + return Err(error(i, "add: a list box that selects several items is not available yet")); + } let creation = if matches!(ty, "slider" | "progressbar") { Value::Undefined } else { props.clone() }; - let text = if list_kind || matches!(ty, "slider" | "progressbar") { Value::Undefined } else { arg(args, 2) }; + let text = if list_kind || matches!(ty, "group" | "slider" | "progressbar") { Value::Undefined } else { third.clone() }; let c = new_element(i, proto, ty, Some(o), Some(win), depth, [&arg(args, 1), &text, &creation])?; match ty { - "checkbox" | "radiobutton" => set_open(i, c, "value", Value::Bool(false))?, + "checkbox" => set_open(i, c, "value", Value::Bool(false))?, + "radiobutton" => { + set_slot(i, c, VALUE, Value::Bool(false))?; + let cl = classes(i)?; + i.define(c, key("value"), Prop::Accessor { get: Some(cl.radio_get), set: Some(cl.radio_set), flags: ENUMERABLE })?; + } "slider" | "progressbar" => { let (value, min, max) = if ty == "slider" { (arg(args, 2), arg(args, 3), arg(args, 4)) } else { (arg(args, 2), Value::Undefined, arg(args, 3)) }; @@ -368,7 +470,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult // A new list's items take their places in the dialog only once the list is added. let mut staged = 0usize; if list_kind { - match arg(args, 2) { + match given_items.clone() { Value::Undefined | Value::Null => {} Value::Object(a) if matches!(i.object(a)?.class, Class::Array { .. }) => { let length = match &i.object(a)?.class { @@ -566,7 +668,202 @@ fn handler(i: &mut Interp, o: ObjId, name: &str) -> JsResult> { i.call(&f, &Value::Object(o), &[]).map(Some) } -/// `notify([event])`: runs the control's `onClick`, `onChange` or `onChanging`. +/// The radio buttons that form a set with `c`: it and the radio buttons next to it in its +/// container, up to the first control of another kind on each side. +fn radio_set_of(i: &Interp, c: ObjId) -> JsResult> { + let Some(parent) = object_slot(i, c, PARENT)? else { return Ok(vec![c]) }; + let kids = kids_of(i, parent)?; + let Some(at) = kids.iter().position(|k| same(k, &Value::Object(c))) else { return Ok(vec![c]) }; + let radio = |v: &Value| -> JsResult> { + Ok(match kind_of(i, v)? { + Some((o, k)) if k == "radiobutton" => Some(o), + _ => None, + }) + }; + let mut set = vec![c]; + for k in kids[..at].iter().rev() { + let Some(o) = radio(k)? else { break }; + set.push(o); + } + for k in &kids[at + 1..] { + let Some(o) = radio(k)? else { break }; + set.push(o); + } + Ok(set) +} + +fn radio_get(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "value")?; + Ok(Value::Bool(slot(i, o, VALUE)?.truthy())) +} + +/// A radio button's `value`: true turns the other radio buttons of its set off. +fn radio_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "value")?; + let on = arg(args, 0).truthy(); + if on { + for other in radio_set_of(i, o)? { + if other != o { + set_slot(i, other, VALUE, Value::Bool(false))?; + } + } + } + set_slot(i, o, VALUE, Value::Bool(on))?; + Ok(Value::Undefined) +} + +/// The listeners registered on `o`: each event type, handler and capture flag. +fn listeners_of(i: &Interp, o: ObjId) -> JsResult> { + let flat = match object_slot(i, o, LISTENERS)? { + Some(a) => list_values(i, a)?, + None => Vec::new(), + }; + Ok(flat.as_chunks::<3>().0.iter().map(|[t, f, c]| (t.clone(), f.clone(), c.truthy())).collect()) +} + +fn set_listeners(i: &mut Interp, o: ObjId, all: &[(Value, Value, bool)]) -> JsResult<()> { + let flat: Vec = all.iter().flat_map(|(t, f, c)| [t.clone(), f.clone(), Value::Bool(*c)]).collect(); + i.rooted(&flat.clone(), |i| { + let kept = list(i, &flat, false)?; + set_slot(i, o, LISTENERS, Value::Object(kept)) + }) +} + +/// Is the stored event type `t` the type `ty`? +fn is_type(t: &Value, ty: &str) -> bool { + matches!(t, Value::String(s) if s.to_rust_string() == ty) +} + +/// The event type `addEventListener` and `removeEventListener` were given, checked. +fn event_type(i: &mut Interp, v: &Value, what: &str) -> JsResult<&'static str> { + let text = i.to_str(v)?.to_rust_string(); + if let Some(name) = EVENTS.iter().find(|e| **e == text) { + return Ok(name); + } + if EVENTS_LATER.contains(&text.as_str()) { + return Err(error(i, &format!("{what}: the event {text} is not available yet"))); + } + Err(error(i, &format!("{what}: there is no event {}", text.chars().take(64).collect::()))) +} + +/// `addEventListener(type, handler[, capture])`. +fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "addEventListener")?; + let ty = event_type(i, &arg(args, 0), "addEventListener")?; + let f = arg(args, 1); + if !i.is_callable(&f) { + return Err(i.type_error("addEventListener: give the handler as a function")); + } + let capture = arg(args, 2).truthy(); + let mut all = listeners_of(i, o)?; + if !all.iter().any(|(t, g, c)| is_type(t, ty) && same(g, &f) && *c == capture) { + all.push((Value::str(ty), f, capture)); + set_listeners(i, o, &all)?; + } + Ok(Value::Undefined) +} + +/// `removeEventListener(type, handler[, capture])`. +fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, _) = element(i, &this, "removeEventListener")?; + let ty = event_type(i, &arg(args, 0), "removeEventListener")?; + let f = arg(args, 1); + let capture = arg(args, 2).truthy(); + let mut all = listeners_of(i, o)?; + let before = all.len(); + all.retain(|(t, g, c)| !(is_type(t, ty) && same(g, &f) && *c == capture)); + if all.len() != before { + set_listeners(i, o, &all)?; + } + Ok(Value::Undefined) +} + +fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if let Some(o) = this.as_object() { + set_slot(i, o, STOPPED, Value::Bool(true))?; + } + Ok(Value::Undefined) +} + +fn event_prevent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + if let Some(o) = this.as_object() { + set_slot(i, o, PREVENTED, Value::Bool(true))?; + } + Ok(Value::Undefined) +} + +/// Runs the listeners for `ty` on `at` (only those for `capture` unless it is `None`), with `event`. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, event: ObjId, phase: f64) -> JsResult { + let wanted: Vec = + listeners_of(i, at)?.into_iter().filter(|(t, _, c)| is_type(t, ty) && capture.is_none_or(|want| *c == want)).map(|(_, f, _)| f).collect(); + if wanted.is_empty() { + return Ok(false); + } + i.rooted(&wanted.clone(), |i| { + set_open(i, event, "currentTarget", Value::Object(at))?; + set_open(i, event, "eventPhase", Value::Number(phase))?; + for f in &wanted { + i.call(f, &Value::Object(at), &[Value::Object(event)])?; + } + Ok(true) + }) +} + +/// Runs the event `ty` on the element `target`: the listeners of the containers above it that +/// capture, its `callback`, its own listeners, then the listeners of the containers that do not +/// capture, until one stops it. → whether the element had a callback or a listener for it. +fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { + let mut above = Vec::new(); + let mut at = object_slot(i, target, PARENT)?; + while let Some(p) = at { + i.use_fuel()?; + above.push(p); + at = object_slot(i, p, PARENT)?; + } + let proto = classes(i)?.event_proto; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; + let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.rooted(&[Value::Object(event)], |i| { + let bubbles = ty != "show"; + set_open(i, event, "type", Value::str(ty))?; + set_open(i, event, "target", Value::Object(target))?; + set_open(i, event, "bubbles", Value::Bool(bubbles))?; + set_open(i, event, "cancelable", Value::Bool(false))?; + set_open(i, event, "detail", Value::Number(if ty == "click" { 1.0 } else { 0.0 }))?; + let stopped = |i: &Interp| -> JsResult { Ok(slot(i, event, STOPPED)?.truthy()) }; + for p in above.iter().rev() { + run_listeners(i, *p, ty, Some(true), event, 1.0)?; + if stopped(i)? { + return Ok(false); + } + } + let had = handler(i, target, callback)?.is_some(); + let heard = run_listeners(i, target, ty, None, event, 2.0)?; + if bubbles && !stopped(i)? { + for p in &above { + run_listeners(i, *p, ty, Some(false), event, 3.0)?; + if stopped(i)? { + break; + } + } + } + Ok(had || heard) + }) +} + +/// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then +/// the click runs. → whether the control had a callback or a listener for it. +fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { + if kind == "checkbox" { + let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); + i.put(c, key("value"), Value::Bool(!on), true)?; + } else if kind == "radiobutton" { + i.put(c, key("value"), Value::Bool(true), true)?; + } + dispatch(i, c, "click", "onClick") +} + +/// `notify([event])`: simulates the control's `onClick`, `onChange` or `onChanging`. fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "notify")?; let event = match arg(args, 0) { @@ -574,10 +871,112 @@ fn notify(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult "onChange".to_string(), v => i.to_str(&v)?.to_rust_string(), }; - if !matches!(event.as_str(), "onClick" | "onChange" | "onChanging") { - return Err(error(i, "notify: give onClick, onChange or onChanging")); + match event.as_str() { + "onClick" => click_control(i, o, &kind)?, + "onChange" => dispatch(i, o, "change", "onChange")?, + "onChanging" => dispatch(i, o, "changing", "onChanging")?, + _ => return Err(error(i, "notify: give onClick, onChange or onChanging")), + }; + Ok(Value::Undefined) +} + +/// The index in `values` that `what` names: an index, one of the values, or a text that an +/// element's `text` equals. A text is converted before the values are read. +fn index_named(i: &mut Interp, what: &Value, values: impl Fn(&Interp) -> JsResult>) -> JsResult<(Vec, Option)> { + match what { + Value::Number(n) => { + let all = values(i)?; + let at = (*n >= 0.0 && n.fract() == 0.0 && (*n as usize) < all.len()).then_some(*n as usize); + Ok((all, at)) + } + Value::Object(_) => { + let all = values(i)?; + let at = all.iter().position(|v| same(v, what)); + Ok((all, at)) + } + v => { + let want = i.to_str(v)?; + let all = values(i)?; + i.rooted(&all.clone(), |i| { + for (n, item) in all.iter().enumerate() { + i.use_fuel()?; + let t = i.get_value(item, &key("text"))?; + if matches!(&t, Value::String(s) if *s == want) { + return Ok((all.clone(), Some(n))); + } + } + Ok((all.clone(), None)) + }) + } } - handler(i, o, &event)?; +} + +/// `list.find(text)`: the first item whose text is `text`, or `null`. +fn find(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let o = list_of(i, &this, "find")?; + let text = Value::String(i.to_str(&arg(args, 0))?); + let (items, at) = index_named(i, &text, |i| items_of(i, o))?; + Ok(at.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) +} + +/// The controls in `c` and in the containers it holds, `c` included, and their list items. +fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { + let (mut controls, mut items) = (0.0, 0.0); + let mut stack = vec![c.clone()]; + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(o) = v.as_object() else { continue }; + controls += 1.0; + items += items_of(i, o)?.len() as f64; + stack.extend(kids_of(i, o)?); + } + Ok((controls, items)) +} + +/// `remove(what)`: removes a list's item, or a container's control, given by its index, the +/// object itself or its text. Nothing happens when there is no such item or control. +fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, kind) = element(i, &this, "remove")?; + let what = arg(args, 0); + let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("an element without its window".into())) }; + if kind == "dropdownlist" || kind == "listbox" { + let (mut items, at) = index_named(i, &what, |i| items_of(i, o))?; + let Some(at) = at else { return Ok(Value::Undefined) }; + items.remove(at); + i.rooted(&items.clone(), |i| { + let kept = list(i, &items, false)?; + set_slot(i, o, ITEMS, Value::Object(kept))?; + let copy = list(i, &items, true)?; + set_open(i, o, "items", Value::Object(copy)) + })?; + let count = number_slot(i, win, ITEM_COUNT)?; + set_slot(i, win, ITEM_COUNT, Value::Number((count - 1.0).max(0.0)))?; + match selection_index(i, o)? { + Some(n) if n == at => set_slot(i, o, SELECTION, Value::Number(-1.0))?, + Some(n) if n > at => set_slot(i, o, SELECTION, Value::Number((n - 1) as f64))?, + _ => {} + } + return Ok(Value::Undefined); + } + if !matches!(kind.as_str(), "dialog" | "group" | "panel") { + return Err(error(i, &format!("remove: a {kind} holds no controls or items"))); + } + let (mut kids, at) = index_named(i, &what, |i| kids_of(i, o))?; + let Some(at) = at else { return Ok(Value::Undefined) }; + let gone = kids.remove(at); + i.rooted(std::slice::from_ref(&gone), |i| { + i.rooted(&kids.clone(), |i| { + let kept = list(i, &kids, false)?; + set_slot(i, o, KIDS, Value::Object(kept))?; + let copy = list(i, &kids, true)?; + set_open(i, o, "children", Value::Object(copy)) + })?; + let (controls, items) = subtree_counts(i, &gone)?; + let count = number_slot(i, win, COUNT)?; + set_slot(i, win, COUNT, Value::Number((count - controls).max(0.0)))?; + let total = number_slot(i, win, ITEM_COUNT)?; + set_slot(i, win, ITEM_COUNT, Value::Number((total - items).max(0.0))) + })?; Ok(Value::Undefined) } @@ -723,7 +1122,7 @@ fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResu fn opened(i: &mut Interp, keep: &[Value], _: Value) -> JsResult { guarded(i, keep, |i| { let Some(win) = arg(keep, 0).as_object() else { return Err(Abrupt::Internal("show lost its dialog".into())) }; - handler(i, win, "onShow")?; + dispatch(i, win, "show", "onShow")?; next(i, win) }) } @@ -756,22 +1155,7 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { let value = slot(i, ev, "value")?; match event.as_str() { "click" => { - if kind == "checkbox" { - let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); - i.put(c, key("value"), Value::Bool(!on), true)?; - } else if kind == "radiobutton" { - let parent = object_slot(i, c, PARENT)?; - for other in parent.map(|p| kids_of(i, p)).transpose()?.unwrap_or_default() { - if !same(&other, &Value::Object(c)) - && let Some((o, k)) = kind_of(i, &other)? - && k == "radiobutton" - { - i.put(o, key("value"), Value::Bool(false), true)?; - } - } - i.put(c, key("value"), Value::Bool(true), true)?; - } - if handler(i, c, "onClick")?.is_none() && kind == "button" { + if !click_control(i, c, &kind)? && kind == "button" { let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); if is(2) { set_slot(i, win, CLOSING, Value::Number(1.0))?; @@ -784,11 +1168,11 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { match kind.as_str() { "edittext" => { i.put(c, key("text"), value, true)?; - handler(i, c, "onChanging")?; + dispatch(i, c, "changing", "onChanging")?; } "slider" => { i.put(c, key("value"), value, true)?; - handler(i, c, "onChanging")?; + dispatch(i, c, "changing", "onChanging")?; } _ => { let n = match value { @@ -806,7 +1190,7 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { set_slot(i, c, SELECTION, Value::Number(n))?; } } - handler(i, c, "onChange")?; + dispatch(i, c, "change", "onChange")?; } _ => return Err(Abrupt::Internal(format!("the host gave show the event {event}"))), } @@ -889,6 +1273,21 @@ fn bounds(i: &mut Interp, v: &Value) -> JsResult { numbers(i, v, &["left", "top", "right", "bottom"], "bounds") } +/// `base`'s width and height, each replaced by `over`'s when that is above 0. +fn overridden(base: Data, over: Data) -> Data { + let Data::Array(over) = over else { return base }; + let mut out = match base { + Data::Array(b) => b, + _ => vec![Data::Number(-1.0), Data::Number(-1.0)], + }; + for (o, v) in out.iter_mut().zip(over) { + if matches!(v, Data::Number(n) if n > 0.0) { + *o = v; + } + } + Data::Array(out) +} + fn margins(i: &mut Interp, v: &Value) -> JsResult { if v.as_object().is_some() { return numbers(i, v, &["left", "top", "right", "bottom"], "margins"); @@ -977,8 +1376,16 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { // A value a getter gives is kept from collection while its own properties are read. let b = get_kept(i, o, "bounds")?; d.push(("bounds".into(), bounds(i, &b)?)); - let size = get_kept(i, o, "preferredSize")?; - d.push(("size".into(), numbers(i, &size, &["width", "height"], "preferredSize")?)); + // `size` set to a positive width or height takes the place of `preferredSize`'s. + let preferred = get_kept(i, o, "preferredSize")?; + let preferred = numbers(i, &preferred, &["width", "height"], "preferredSize")?; + let set = get_kept(i, o, "size")?; + let set = numbers(i, &set, &["width", "height"], "size")?; + d.push(("size".into(), overridden(preferred, set))); + for (name, field) in [("minimumSize", "min"), ("maximumSize", "max")] { + let v = get_kept(i, o, name)?; + d.push((field.into(), numbers(i, &v, &["width", "height"], name)?)); + } let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); if matches!(kind.as_str(), "dialog" | "group" | "panel") { @@ -1066,7 +1473,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul let host = i.host_object("Window", items)?; let object_proto = i.intrinsics.object_proto; i.rooted(&[Value::Object(host)], |i| { - i.reserve_heap(OBJECT_BYTES.saturating_mul(4))?; + i.reserve_heap(OBJECT_BYTES.saturating_mul(5))?; let window_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); i.temp_roots.push(Value::Object(window_proto)); let control_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); @@ -1079,21 +1486,54 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul i.temp_roots.push(Value::Object(selection_get)); let selection_set = native(i, "selection", selection_set, 1, NativeKind::Plain, false)?; i.temp_roots.push(Value::Object(selection_set)); - i.script_ui = Some(Classes { window_proto, control_proto, item_proto, layout, host, selection_get, selection_set, showing: None }); + let event_proto = i.heap.alloc_object(Object::new(Class::Ordinary, Some(object_proto))); + i.temp_roots.push(Value::Object(event_proto)); + let radio_get = native(i, "value", radio_get, 0, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(radio_get)); + let radio_set = native(i, "value", radio_set, 1, NativeKind::Plain, false)?; + i.temp_roots.push(Value::Object(radio_set)); + i.script_ui = Some(Classes { + window_proto, + control_proto, + item_proto, + event_proto, + layout, + host, + selection_get, + selection_set, + radio_get, + radio_set, + showing: None, + }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; - method(i, window_proto, "add", add, 4)?; - method(i, window_proto, "findElement", find_element, 1)?; + // `Window.alert`, `Window.confirm` and `Window.prompt` are the host's global functions. + let global = i.global; + for name in ["alert", "confirm", "prompt"] { + if let Some(Prop::Data { value, .. }) = i.get_own_property(global, &key(name))? + && i.is_callable(&value) + { + data(i, window, name, value, HIDDEN)?; + } + } + for proto in [window_proto, control_proto] { + method(i, proto, "add", add, 4)?; + method(i, proto, "findElement", find_element, 1)?; + method(i, proto, "remove", remove, 1)?; + method(i, proto, "addEventListener", add_event_listener, 3)?; + method(i, proto, "removeEventListener", remove_event_listener, 3)?; + } method(i, window_proto, "close", close, 1)?; method(i, window_proto, "hide", hide, 0)?; method(i, window_proto, "center", nothing, 1)?; pausable_method(i, window_proto, "show", show, 0)?; - method(i, control_proto, "add", add, 4)?; - method(i, control_proto, "findElement", find_element, 1)?; method(i, control_proto, "removeAll", remove_all, 0)?; + method(i, control_proto, "find", find, 1)?; method(i, control_proto, "notify", notify, 1)?; method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; + method(i, event_proto, "stopPropagation", event_stop, 0)?; + method(i, event_proto, "preventDefault", event_prevent, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 7d0d8376a3..5ee096a608 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -385,3 +385,112 @@ fn findelement_items_and_selection_follow_the_list() { .unwrap(); assert_eq!(v, JsValue::String("true,b,,,0,b".into())); } + +#[test] +fn a_new_control_s_sizes_can_be_set_a_side_at_a_time_and_reach_the_description() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); \ + b.preferredSize.width = 100; b.minimumSize.height = 30; b.maximumSize.width = 90; w.size.height = 200; w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + let numbers = |v: &[f64]| Data::Array(v.iter().map(|n| Data::Number(*n)).collect()); + assert_eq!(field(&first[1], "size"), &numbers(&[100.0, -1.0]), "the side left alone stays to the layout"); + assert_eq!(field(&first[1], "min"), &numbers(&[-1.0, 30.0])); + assert_eq!(field(&first[1], "max"), &numbers(&[90.0, -1.0])); + assert_eq!(field(&first[0], "size"), &numbers(&[-1.0, 200.0]), "size takes the place of preferredSize"); +} + +#[test] +fn listeners_run_in_the_capture_target_and_bubbling_phases_until_one_stops() { + let (mut r, _, _) = realm(vec![click(2)]); + let source = "var w = new Window('dialog'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var log = []; \ + w.addEventListener('click', function (e) { log.push('capture ' + e.eventPhase); }, true); \ + b.onClick = function () { log.push('onClick'); }; \ + b.addEventListener('click', function (e) { log.push(e.type + ' ' + (e.target === b) + ' ' + (this === b)); }); \ + g.addEventListener('click', function (e) { log.push('group ' + (e.currentTarget === g)); }); \ + w.addEventListener('click', function () { log.push('dialog'); w.close(3); }); \ + [w.show(), log.join()].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("3|capture 1,onClick,click true true,group true,dialog".into())); + let (mut r, _, _) = realm(vec![click(1), close(), click(1), close()]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'OK'); var log = []; \ + function count() { log.push('count'); } b.addEventListener('click', count); b.addEventListener('click', count); \ + b.addEventListener('click', function (e) { e.stopPropagation(); }); \ + w.addEventListener('click', function () { log.push('dialog'); }); \ + w.addEventListener('show', function (e) { log.push('show ' + e.bubbles); }); \ + var first = w.show(); b.removeEventListener('click', count); var second = w.show(); [first, second, log.join()].join('|')"; + assert_eq!( + r.run(source).unwrap(), + JsValue::String("0|0|show false,count,show false".into()), + "a button with a click listener does not close the dialog by itself, and the same listener is added once" + ); + for (source, want) in [ + ("new Window('dialog').addEventListener('mouseover', function () {})", "addEventListener: the event mouseover is not available yet"), + ("new Window('dialog').addEventListener('wobble', function () {})", "addEventListener: there is no event wobble"), + ("new Window('dialog').addEventListener('click', 'code')", "addEventListener: give the handler as a function"), + ] { + let (mut r, _, _) = realm(Vec::new()); + let e = r.run(&format!("try {{ {source}; 'added' }} catch (e) {{ e.message }}")).unwrap(); + assert_eq!(e, JsValue::String(want.into()), "{source}"); + } +} + +#[test] +fn lists_find_and_remove_items_and_take_their_items_in_the_creation_properties() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var d = w.add('dropdownlist', undefined, undefined, {items: ['a', 'b', 'c']}); \ + var x = w.add('listbox', undefined, {items: ['x'], name: 'xs'}); \ + d.selection = 2; var b = d.find('b'); d.remove('b'); d.remove(0); d.remove('zzz'); d.remove(7); \ + [d.items.length, d.items[0].text, d.selection.text, b.index, d.find('q'), x.items[0].text, x.name].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,c,c,-1,,x,xs".into())); + let both = r.run("try { new Window('dialog').add('listbox', undefined, ['a'], {items: ['b']}); 'made' } catch (e) { e.name }").unwrap(); + assert_eq!(both, JsValue::String("TypeError".into())); + let freed = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox'); for (var n = 0; n < 1024; n++) l.add('item', 'i'); \ + l.remove(0); l.add('item', 'again'); var g = w.add('group'); g.add('button', undefined, 'A'); g.add('button', undefined, 'B'); \ + g.remove('A'); g.remove(g.children[0]); w.remove(l); var m = w.add('listbox'); \ + for (var k = 0; k < 1024; k++) m.add('item', 'j'); for (var i = 0; i < 510; i++) w.add('button'); \ + [g.children.length, w.children.length, m.items.length].join()", + ) + .unwrap(); + assert_eq!(freed, JsValue::String("0,512,1024".into()), "a removed item or control frees its place"); +} + +#[test] +fn a_group_takes_its_creation_properties_third() { + let (mut r, seen, _) = realm(vec![close()]); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group', undefined, {orientation: 'column', alignChildren: 'left', name: 'g'}); \ + var p = w.add('panel', undefined, 'Title', {margins: 4}); w.show(); [g.orientation, g.alignChildren, g.name, g.text, p.text, p.margins].join()", + ) + .unwrap(); + assert_eq!(v, JsValue::String("column,left,g,,Title,4".into())); + let seen = seen.borrow(); + assert_eq!(field(&nodes(&seen.descriptions[0])[1], "orientation"), &Data::String("column".into())); +} + +#[test] +fn a_radio_button_turned_on_turns_off_the_others_of_its_set() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var r1 = w.add('radiobutton', undefined, 'A'); var r2 = w.add('radiobutton', undefined, 'B'); \ + var r3 = w.add('radiobutton', undefined, 'C'); w.add('statictext', undefined, 'Other'); var r4 = w.add('radiobutton', undefined, 'D'); \ + var c = w.add('checkbox', undefined, 'E'); var clicks = 0; r3.onClick = function () { clicks++; }; \ + r1.value = true; r2.value = true; var set = [r1.value, r2.value, r3.value]; r4.value = true; \ + r3.notify('onClick'); r3.notify(); c.notify('onClick'); \ + set.concat([r1.value, r2.value, r3.value, r4.value, c.value, clicks]).join()", + ) + .unwrap(); + assert_eq!( + v, + JsValue::String("false,true,false,false,false,true,true,true,2".into()), + "a radio button after another kind of control starts a new set" + ); +} diff --git a/docs/mcp.md b/docs/mcp.md index d376a5623b..88a9489bc2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2908,26 +2908,52 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s 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`, and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, - minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `listbox` with - `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` - and the rest) throw that they are not available yet, and an unknown type throws too. -- A list's `add("item", text)` adds an item, `removeAll()` removes them, `items` lists them and `selection` is the - selected item or `null`; setting it to an item or an index selects it. An item has `text`, `index` and - `selected`. -- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `alignment`, `parent`, - `window`, `show()` and `hide()`. A container also has `children`, `orientation` (`row`, `column` or `stack`; a - group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` - (15 to start, 0 for a group) and `findElement(name)`. The dialog has `defaultElement`, `cancelElement`, - `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. + minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes + `properties` right after `bounds`, and a list may take `properties` there in place of its items, with the item + texts in `properties.items`; a list given items both ways throws a `TypeError`. The `alignment` in `properties`, + and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values + (VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`, + `scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an + unknown type throws too. +- A list's `add("item", text)` adds an item, `find(text)` gives the first item with that text or `null`, + `remove(what)` removes the item given by its index, the item itself or its text, `removeAll()` removes them all, + `items` lists them and `selection` is the selected item or `null`; setting it to an item or an index selects it. + An item has `text`, `index` and `selected`. +- A control has `text`, `value`, `enabled`, `visible`, `name`, `bounds`, `preferredSize`, `size`, `minimumSize`, + `maximumSize`, `alignment`, `parent`, `window`, `show()`, `hide()` and `notify([event])`. Each size starts as an + object whose `width` and `height` are -1, so a script can set one side, as in `preferredSize.width = 100`; a side + of 0 or less is left to the layout (VectorCraft's own starting values). A container also has `children`, + `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), + `alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and + `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item + or a control that is not there does nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` + and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. +- Radio buttons added one after another in a container form a set: setting one's `value` to true, or clicking it, + sets the others in the set to false. A control of another kind between two radio buttons starts a new set, as + the JavaScript Tools Guide describes radio buttons + (https://raw.githubusercontent.com/Adobe-CEP/CEP-Resources/master/ExtendScript-Toolkit/Guides/JavaScript%20Tools%20Guide%20CC.pdf). +- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` act as the person's click or change would: + a click turns a check box over and turns a radio button on, then runs `onClick` and the `click` listeners. + `notify()` gives a click for a button, a check box and a radio button, and a change for the others. +- `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`, + and `removeEventListener` with the same arguments removes it; a function registered twice for the same type and + phase runs once. A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, + `detail` (1 for a click), `stopPropagation()` and `preventDefault()`. The containers above the control run their + `capture` handlers first, then the control runs its `onClick`, `onChange` or `onChanging` and its own handlers, + then the containers run their other handlers, from the nearest out, until a handler calls `stopPropagation()`; + `show` runs only on the dialog. The other documented event types (`focus`, `mouseover`, `keydown` and the rest) + throw that they are not available yet, and a handler that is not a function throws a `TypeError`. +- `Window.alert`, `Window.confirm` and `Window.prompt` open the same dialogs as `alert`, `confirm` and `prompt`. -`show()` opens the dialog, runs `onShow`, and waits for the person. A click runs the control's `onClick`; a check -box turns its value over first, and a radio button turns on and the other radio buttons in its container off. An +`show()` opens the dialog, runs `onShow` and the `show` handlers, and waits for the person. A click runs the +control's `onClick` and `click` handlers; a check box turns its value over first, and a radio button turns on and +the other radio buttons of its set off. An edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another control, and a slider gives its value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the -cancel button is clicked, while they have no `onClick`, and 0 for the close box. `onClose` runs before the dialog +cancel button is clicked, while they have no `onClick` and no `click` handler of their own, and 0 for the close box. `onClose` runs before the dialog closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in @@ -2937,8 +2963,9 @@ function. A shown dialog can be shown again after it closes. text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws too, and a slider's minimum above its maximum. When a getter changes a list's items after the list was read, it reads the dialog again, and throws an `Error` when a list changes again. It lays the controls out from each container's `orientation`, -`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` and `bounds`, which places -it in its container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. +`alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that +is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its +container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()` diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 939047032e..ead7d36125 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; 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 `addEventListener` for clicks, changes and `show`, `notify`, size objects a script can set one side of, and lists' `find` and `remove`, and `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`. - 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`). From 3089ed73a5ba2778b96d2187e397ef84a1440a6f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 12:25:38 -0800 Subject: [PATCH 10/29] Scripts: ScriptUI listeners are limited and removed controls leave their dialog - A control with alignment fill stays within its maximumSize when its container's room is larger. - A window or control takes at most 256 event listeners (VectorCraft's own limit); one more throws a RangeError. A show listener can be added only to the dialog, and on a control it throws an Error. - A capturing listener on a container that stops a click keeps the default or cancel button from closing the dialog. Listeners on the containers that do not capture still leave the button to close it. - stopPropagation() acts only on an event whose listeners are running, and preventDefault() does nothing, since the events are not cancelable. - A control removed from its container has no parent, its events no longer reach the containers it was in, and add and remove on it, or on a control it holds, throw an Error. Its controls are no longer counted toward the dialog's limits. - remove(text) throws an Error, and removes nothing, when a text getter changes the list or container while it looks for a match. - A group takes its creation properties fourth again when the third argument is not an object, as in add("group", undefined, undefined, {name: "g"}). - A click on a radio button now turns off only the radio buttons of its set, the ones added next to it with no other kind of control between them. It used to turn off every radio button in its container. Docs: docs/mcp.md now says that notify runs the handlers without closing the dialog. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/scriptui.rs | 14 +- crates/engine/src/tests/script_scriptui.rs | 6 + crates/js/src/scriptui.rs | 170 +++++++++++++++------ crates/js/src/scriptui_tests.rs | 84 ++++++++++ docs/mcp.md | 55 ++++--- 6 files changed, 254 insertions(+), 77 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 6729537b5a..1c569c99a3 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, 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 acts as a click or change, addEventListener and removeEventListener take click, change, changing and show (other event types throw that they are not available yet), 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, 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, 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; other event types throw that they are not available yet), a removed control leaves the dialog, 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/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index f3520b41cc..11475fb832 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -617,28 +617,30 @@ fn layout(d: &mut ScriptUiDialog) { let [w, h] = size[k]; let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); - let place = |align: Align, own: f32, room: f32| match align { + let max = kid.max_size; + // A control that fills its container's room stays within its maximum. + let place = |align: Align, own: f32, room: f32, axis: usize| match align { Align::Start => (0.0, own), Align::End => ((room - own).max(0.0), own), Align::Center => (((room - own) / 2.0).max(0.0), own), - Align::Fill => (0.0, room.max(own)), + Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))), }; match node.orientation { Orientation::Row => { - let (dy, kh) = place(v_align, h, ch); + let (dy, kh) = place(v_align, h, ch, 1); let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; cursor += w + node.spacing; r } Orientation::Column => { - let (dx, kw) = place(h_align, w, cw); + let (dx, kw) = place(h_align, w, cw, 0); let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; cursor += h + node.spacing; r } Orientation::Stack => { - let (dx, kw) = place(h_align, w, cw); - let (dy, kh) = place(v_align, h, ch); + let (dx, kw) = place(h_align, w, cw, 0); + let (dy, kh) = place(v_align, h, ch, 1); UiRect { x: x + dx, y: y + dy, w: kw, h: kh } } } diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 7536020534..e572d01f64 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -327,6 +327,12 @@ fn a_control_s_size_keeps_within_its_minimum_and_maximum() { assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate"); let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap(); assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate"); + let column = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "size", pair(300.0, -1.0)); + let fill = |n: Data| with(n, "alignment", Data::String("fill".into())); + let capped = with(fill(node("button", 0.0)), "max", pair(90.0, -1.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![column, capped, fill(node("button", 0.0))])).unwrap(); + assert!(d.nodes[2].rect.w > 90.0, "a control that fills its column takes the column's width"); + assert_eq!(d.nodes[1].rect.w, 90.0, "a control that fills its column stays within its maximum width"); } #[test] diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 76d4911632..912de3e685 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -9,20 +9,25 @@ //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet. A -//! group takes its creation properties as the third argument, and a list takes them there in place -//! of its items, with the items in `properties.items`. A list's `add("item", text)` adds an item, -//! `find(text)` finds one and `remove(what)` removes one; its `selection` is an item or `null`, and -//! takes an item, an index or `null`. A container's `remove(what)` removes a control. Each element -//! starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose `width` and -//! `height` are -1, which leaves the size to the layout. Setting a radio button's `value` to true -//! sets the other radio buttons next to it in its container to false, as a click does. +//! group takes its creation properties as the third argument (or the fourth when the third is not +//! an object), and a list takes them there in place of its items, with the items in +//! `properties.items`. A list's `add("item", text)` adds an item, `find(text)` finds one and +//! `remove(what)` removes one; its `selection` is an item or `null`, and takes an item, an index or +//! `null`. A container's `remove(what)` removes a control, which then has no `parent` and no longer +//! belongs to the dialog: `add` and `remove` on it, or on a control it holds, throw an `Error`. +//! Each element starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose +//! `width` and `height` are -1, which leaves the size to the layout. Setting a radio button's +//! `value` to true sets the other radio buttons next to it in its container to false, as a click +//! does. //! //! `addEventListener(type, handler[, capture])` and `removeEventListener` register handlers for -//! the events `show()` runs: `click`, `change`, `changing` and `show`. A handler gets an event -//! object, in the capture phase on the containers above the control, then on the control after its -//! `onClick`, `onChange` or `onChanging`, then in the bubbling phase on the containers again, until -//! one calls `stopPropagation()`. `notify(event)` runs the same handlers, and `notify("onClick")` -//! turns a check box over and turns a radio button on first. `Window.alert`, `Window.confirm` and +//! the events `show()` runs: `click`, `change`, `changing`, and `show` on a dialog only; a window +//! or control takes at most [`MAX_LISTENERS`] of them. A handler gets an event object, in the +//! capture phase on the containers above the control, then on the control after its `onClick`, +//! `onChange` or `onChanging`, then in the bubbling phase on the containers again, until one calls +//! `stopPropagation()`. Events are not cancelable, and `preventDefault()` does nothing. +//! `notify(event)` runs the same handlers, and `notify("onClick")` turns a check box over and turns +//! a radio button on first; it does not close the dialog. `Window.alert`, `Window.confirm` and //! `Window.prompt` are the global functions of those names, when the host defines them. //! //! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the @@ -30,20 +35,23 @@ //! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a //! `change` with its new value, or a `close`. The control takes the change, its `onClick`, //! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A -//! button without `onClick` closes the dialog with 1 when it is the dialog's default element and -//! with 2 when it is its cancel element. `close(result)` closes the dialog after the running handler -//! returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps the dialog -//! open when it returns `false`. A dialog that is showing cannot be shown again, and no other dialog -//! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether -//! it ended normally. +//! button without `onClick` and without a `click` listener of its own closes the dialog with 1 when +//! it is the dialog's default element and with 2 when it is its cancel element, unless a capturing +//! listener on a container stopped the click. `close(result)` closes the dialog after the running +//! handler returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps +//! the dialog open when it returns `false`. A dialog that is showing cannot be shown again, and no +//! other dialog can be shown while one is. When `show()` ends, the host's `end` is given its result +//! and whether it ended normally. //! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] //! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a -//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. A -//! getter that changes a list's items after the list was read makes `show()` read the dialog again, -//! and a list that changes again throws an `Error`. +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These and [`MAX_LISTENERS`] are +//! VectorCraft's own limits. A getter that changes a list's items after the list was read makes +//! `show()` read the dialog again, and a list that changes again throws an `Error`. A `text` getter +//! that changes a list or a container while `remove(text)` looks for an item or a control makes +//! `remove` throw an `Error`. use crate::HostItem; use crate::builtins::{arg, constructor, data, method, native, pausable_method}; @@ -60,6 +68,8 @@ pub const MAX_DEPTH: usize = 16; pub const MAX_ITEMS: usize = 1024; /// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. pub const MAX_TEXT_BYTES: usize = 16 << 10; +/// The most event listeners one window or control holds. +pub const MAX_LISTENERS: usize = 256; /// The control types `add` makes. pub const BUILT: [&str; 11] = @@ -82,7 +92,6 @@ const LIST: &str = "__vcList"; const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; -const PREVENTED: &str = "__vcPrevented"; /// The size properties every element starts with, as objects with `width` and `height`. const SIZES: [&str; 4] = ["preferredSize", "size", "minimumSize", "maximumSize"]; @@ -120,6 +129,8 @@ pub(crate) struct Classes { radio_get: ObjId, radio_set: ObjId, showing: Option, + /// The event objects whose listeners are running, innermost last. + dispatching: Vec, } impl Classes { @@ -138,14 +149,17 @@ impl Classes { self.radio_set, ]; all.extend(self.showing); + all.extend(self.dispatching.iter().copied()); all } } -/// Forgets the dialog that was showing when a run ended where it was. +/// Forgets the dialog that was showing, and the events that were running, when a run ended where +/// it was. pub(crate) fn end_run(i: &mut Interp) { if let Some(c) = i.script_ui.as_mut() { c.showing = None; + c.dispatching.clear(); } } @@ -209,6 +223,15 @@ fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String) } } +/// The dialog that holds the element `o`, or an `Error` naming `what` for a control that was +/// removed from its dialog. +fn window_of(i: &mut Interp, o: ObjId, what: &str) -> JsResult { + match object_slot(i, o, WINDOW)? { + Some(w) => Ok(w), + None => Err(error(i, &format!("{what}: the control was removed from its dialog"))), + } +} + /// Are `a` and `b` the same object? fn same(a: &Value, b: &Value) -> bool { matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) @@ -380,6 +403,7 @@ fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { /// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "add")?; + window_of(i, o, "add")?; let ty = i.to_str(&arg(args, 0))?.to_rust_string(); if kind == "dropdownlist" || kind == "listbox" { if ty.to_lowercase() != "item" { @@ -402,7 +426,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if depth > MAX_DEPTH { return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); } - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a control without its window".into())) }; + let win = window_of(i, o, "add")?; let count = number_slot(i, win, COUNT)?; if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); @@ -415,8 +439,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult None => false, }) }; - // A group takes its creation properties third, and so may a list in place of its items. - let props_third = ty == "group" || (list_kind && third.as_object().is_some() && !is_array(i, &third)?); + // A group takes its creation properties third, and so may a list in place of its items; when + // the third argument is not an object, they are the fourth. + let props_third = third.as_object().is_some() && (ty == "group" || (list_kind && !is_array(i, &third)?)); let props = if props_third { third.clone() } else { arg(args, 3) }; let proto = classes(i)?.control_proto; let mark = i.temp_roots.len(); @@ -491,7 +516,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult _ => return Err(i.type_error("add: give a list's items as an array")), } } - // A getter or a conversion above may have added controls or items itself. + // A getter or a conversion above may have added controls or items itself, or removed the + // container from its dialog. + window_of(i, o, "add")?; let count = number_slot(i, win, COUNT)?; if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); @@ -511,10 +538,10 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult /// Adds an item with `text` to the list `o`, which the dialog holds. fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; // The conversion runs first: it may add or remove items itself. let text = text_arg(i, text)?; i.rooted(std::slice::from_ref(&text), |i| { + let win = window_of(i, o, "add")?; let count = number_slot(i, win, ITEM_COUNT)?; if count as usize >= MAX_ITEMS { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); @@ -624,7 +651,7 @@ fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let o = list_of(i, &this, "removeAll")?; let n = items_of(i, o)?.len() as f64; - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let win = window_of(i, o, "removeAll")?; let count = number_slot(i, win, ITEM_COUNT)?; set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; let kept = list(i, &[], false)?; @@ -748,8 +775,11 @@ fn event_type(i: &mut Interp, v: &Value, what: &str) -> JsResult<&'static str> { /// `addEventListener(type, handler[, capture])`. fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (o, _) = element(i, &this, "addEventListener")?; + let (o, kind) = element(i, &this, "addEventListener")?; let ty = event_type(i, &arg(args, 0), "addEventListener")?; + if ty == "show" && kind != "dialog" { + return Err(error(i, "addEventListener: the event show runs only on a dialog")); + } let f = arg(args, 1); if !i.is_callable(&f) { return Err(i.type_error("addEventListener: give the handler as a function")); @@ -757,6 +787,9 @@ fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let capture = arg(args, 2).truthy(); let mut all = listeners_of(i, o)?; if !all.iter().any(|(t, g, c)| is_type(t, ty) && same(g, &f) && *c == capture) { + if all.len() >= MAX_LISTENERS { + return Err(range(i, &format!("addEventListener: a window or control takes at most {MAX_LISTENERS} listeners"))); + } all.push((Value::str(ty), f, capture)); set_listeners(i, o, &all)?; } @@ -778,20 +811,17 @@ fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) - Ok(Value::Undefined) } +/// `event.stopPropagation()`: stops an event whose listeners are running; it does nothing to any +/// other object. fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - if let Some(o) = this.as_object() { + if let Some(o) = this.as_object() + && classes(i)?.dispatching.contains(&o) + { set_slot(i, o, STOPPED, Value::Bool(true))?; } Ok(Value::Undefined) } -fn event_prevent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - if let Some(o) = this.as_object() { - set_slot(i, o, PREVENTED, Value::Bool(true))?; - } - Ok(Value::Undefined) -} - /// Runs the listeners for `ty` on `at` (only those for `capture` unless it is `None`), with `event`. fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, event: ObjId, phase: f64) -> JsResult { let wanted: Vec = @@ -811,7 +841,9 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve /// Runs the event `ty` on the element `target`: the listeners of the containers above it that /// capture, its `callback`, its own listeners, then the listeners of the containers that do not -/// capture, until one stops it. → whether the element had a callback or a listener for it. +/// capture, until one stops it. → whether the event was handled: the element had a callback or a +/// listener for it, or a capturing listener above it stopped it. Listeners of the containers that +/// do not capture do not count. fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { let mut above = Vec::new(); let mut at = object_slot(i, target, PARENT)?; @@ -823,6 +855,20 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult let proto = classes(i)?.event_proto; i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + if let Some(c) = i.script_ui.as_mut() { + c.dispatching.push(event); + } + let r = run_event(i, event, target, &above, ty, callback); + if let Some(c) = i.script_ui.as_mut() + && let Some(n) = c.dispatching.iter().rposition(|e| *e == event) + { + c.dispatching.remove(n); + } + r +} + +/// The phases of [`dispatch`] for the event object `event`. +fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str) -> JsResult { i.rooted(&[Value::Object(event)], |i| { let bubbles = ty != "show"; set_open(i, event, "type", Value::str(ty))?; @@ -834,13 +880,13 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult for p in above.iter().rev() { run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { - return Ok(false); + return Ok(true); } } let had = handler(i, target, callback)?.is_some(); let heard = run_listeners(i, target, ty, None, event, 2.0)?; if bubbles && !stopped(i)? { - for p in &above { + for p in above { run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; @@ -852,7 +898,7 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult } /// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then -/// the click runs. → whether the control had a callback or a listener for it. +/// the click runs. → whether the click was handled, as [`dispatch`] says. fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); @@ -938,9 +984,15 @@ fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "remove")?; let what = arg(args, 0); - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("an element without its window".into())) }; + window_of(i, o, "remove")?; if kind == "dropdownlist" || kind == "listbox" { - let (mut items, at) = index_named(i, &what, |i| items_of(i, o))?; + let before = slot(i, o, ITEMS)?; + let (mut items, at) = i.rooted(std::slice::from_ref(&before), |i| index_named(i, &what, |i| items_of(i, o)))?; + // A `text` getter read during the lookup may have changed the list or removed it. + if !same(&slot(i, o, ITEMS)?, &before) { + return Err(error(i, "remove: the list changed while the item was looked up")); + } + let win = window_of(i, o, "remove")?; let Some(at) = at else { return Ok(Value::Undefined) }; items.remove(at); i.rooted(&items.clone(), |i| { @@ -961,7 +1013,13 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult<()> { + let Some(root) = c.as_object() else { return Ok(()) }; + set_slot(i, root, PARENT, Value::Null)?; + set_open(i, root, "parent", Value::Null)?; + let mut stack = vec![c.clone()]; + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(o) = v.as_object() else { continue }; + set_slot(i, o, WINDOW, Value::Null)?; + stack.extend(kids_of(i, o)?); + } + Ok(()) +} + fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let (o, _) = element(i, &this, "show")?; i.put(o, key("visible"), Value::Bool(true), true)?; @@ -1504,6 +1579,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul radio_get, radio_set, showing: None, + dispatching: Vec::new(), }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; @@ -1533,7 +1609,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; method(i, event_proto, "stopPropagation", event_stop, 0)?; - method(i, event_proto, "preventDefault", event_prevent, 0)?; + method(i, event_proto, "preventDefault", nothing, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 5ee096a608..4847ba5ac3 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -494,3 +494,87 @@ fn a_radio_button_turned_on_turns_off_the_others_of_its_set() { "a radio button after another kind of control starts a new set" ); } + +#[test] +fn a_click_on_a_radio_button_turns_off_only_the_radio_buttons_of_its_set() { + let (mut r, _, _) = realm(vec![click(4), close()]); + let source = "var w = new Window('dialog'); var r1 = w.add('radiobutton', undefined, 'A'); w.add('statictext', undefined, 'Other'); \ + var r2 = w.add('radiobutton', undefined, 'B'); var r3 = w.add('radiobutton', undefined, 'C'); r1.value = true; r2.value = true; \ + [w.show(), r1.value, r2.value, r3.value].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("0,true,false,true".into())); +} + +#[test] +fn a_group_takes_its_creation_properties_fourth_after_an_empty_third_argument() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run("var g = new Window('dialog').add('group', undefined, undefined, {name: 'g', orientation: 'column'}); [g.name, g.orientation].join()") + .unwrap(); + assert_eq!(v, JsValue::String("g,column".into())); +} + +#[test] +fn a_capturing_listener_that_stops_a_click_keeps_the_default_button_open() { + let (mut r, _, _) = realm(vec![click(1), close()]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var log = []; \ + w.addEventListener('click', function (e) { log.push('stopped'); e.stopPropagation(); }, true); [w.show(), log.join()].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("0|stopped".into())); + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var seen = 0; \ + w.addEventListener('click', function () { seen++; }); [w.show(), seen].join()"; + assert_eq!( + r.run(source).unwrap(), + JsValue::String("1,1".into()), + "a listener on the dialog that does not capture leaves the default button to close it" + ); +} + +#[test] +fn listeners_are_limited_show_is_the_dialog_s_and_stop_propagation_reaches_only_running_events() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); \ + for (var n = 0; n < 256; n++) b.addEventListener('click', function () {}); \ + var more; try { b.addEventListener('click', function () {}); more = 'added'; } catch (e) { more = e.name; } \ + var shown; try { b.addEventListener('show', function () {}); shown = 'added'; } catch (e) { shown = e.message; } \ + var kept, o = Object.freeze({}); var c = w.add('button'); c.addEventListener('click', function (e) { kept = e; }); c.notify(); \ + kept.stopPropagation.call(o); kept.stopPropagation(); kept.preventDefault(); \ + [more, shown, Object.getOwnPropertyNames(o).length, kept.cancelable].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("RangeError|addEventListener: the event show runs only on a dialog|0|false".into())); +} + +#[test] +fn a_removed_control_leaves_its_dialog() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); w.add('statictext'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var heard = 0; \ + w.addEventListener('click', function () { heard++; }, true); w.addEventListener('click', function () { heard++; }); \ + w.remove(g); b.notify('onClick'); var errors = []; \ + try { g.remove(0); } catch (e) { errors.push(e.message); } try { g.add('button'); } catch (e) { errors.push(e.message); } \ + var added = 0; try { while (true) { w.add('button'); added++; } } catch (e) {} \ + [g.parent, heard, added, errors.join(';')].join('|')", + ) + .unwrap(); + assert_eq!( + v, + JsValue::String("|0|511|remove: the control was removed from its dialog;add: the control was removed from its dialog".into()), + "a removed group's controls no longer count toward the dialog's limit and cannot be counted off it twice" + ); +} + +#[test] +fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); \ + Object.defineProperty(l.items[0], 'text', {get: function () { l.remove(1); return 'a'; }}); \ + var m; try { l.remove('c'); m = 'removed'; } catch (e) { m = e.message; } [m, l.items.length, l.items[1].text].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("remove: the list changed while the item was looked up|2|c".into())); +} diff --git a/docs/mcp.md b/docs/mcp.md index 88a9489bc2..63813fbe7f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2909,8 +2909,9 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes - `properties` right after `bounds`, and a list may take `properties` there in place of its items, with the item - texts in `properties.items`; a list given items both ways throws a `TypeError`. The `alignment` in `properties`, + `properties` right after `bounds`, or after an empty third argument, and a list may take `properties` right + after `bounds` in place of its items, with the item texts in `properties.items`; a list given items both ways + throws a `TypeError`. The `alignment` in `properties`, and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values (VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an @@ -2926,38 +2927,46 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item - or a control that is not there does nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` + or a control that is not there does nothing. A removed control has no `parent` and its handlers no longer reach + the containers it was in; `add` and `remove` on it, or on a control it holds, throw an `Error`. When a `text` + getter changes the list or container while `remove(text)` looks for a match, `remove` throws an `Error` and + removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. - Radio buttons added one after another in a container form a set: setting one's `value` to true, or clicking it, sets the others in the set to false. A control of another kind between two radio buttons starts a new set, as the JavaScript Tools Guide describes radio buttons (https://raw.githubusercontent.com/Adobe-CEP/CEP-Resources/master/ExtendScript-Toolkit/Guides/JavaScript%20Tools%20Guide%20CC.pdf). -- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` act as the person's click or change would: - a click turns a check box over and turns a radio button on, then runs `onClick` and the `click` listeners. - `notify()` gives a click for a button, a check box and a radio button, and a change for the others. +- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` run the handlers that the person's click or + change would run: a click turns a check box over and turns a radio button on, then runs `onClick` and the + `click` listeners. `notify` does not close the dialog, even for the default or cancel button. `notify()` gives a + click for a button, a check box and a radio button, and a change for the others. - `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`, and `removeEventListener` with the same arguments removes it; a function registered twice for the same type and - phase runs once. A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, - `detail` (1 for a click), `stopPropagation()` and `preventDefault()`. The containers above the control run their - `capture` handlers first, then the control runs its `onClick`, `onChange` or `onChanging` and its own handlers, - then the containers run their other handlers, from the nearest out, until a handler calls `stopPropagation()`; - `show` runs only on the dialog. The other documented event types (`focus`, `mouseover`, `keydown` and the rest) - throw that they are not available yet, and a handler that is not a function throws a `TypeError`. + phase runs once. `show` can be registered only on the dialog, and on a control it throws an `Error`. A window or + control takes at most 256 handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own + limit). A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, `cancelable` + (always false), `detail` (1 for a click), `stopPropagation()` and `preventDefault()`, which does nothing. The + containers above the control run their `capture` handlers first, then the control runs its `onClick`, + `onChange` or `onChanging` and its own handlers, then the containers run their other handlers, from the nearest + out, until a handler calls `stopPropagation()`. The other documented event types (`focus`, `mouseover`, + `keydown` and the rest) throw that they are not available yet, and a handler that is not a function throws a + `TypeError`. - `Window.alert`, `Window.confirm` and `Window.prompt` open the same dialogs as `alert`, `confirm` and `prompt`. `show()` opens the dialog, runs `onShow` and the `show` handlers, and waits for the person. A click runs the control's `onClick` and `click` handlers; a check box turns its value over first, and a radio button turns on and -the other radio buttons of its set off. An -edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another -control, and a slider gives its -value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. -Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` -returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the -cancel button is clicked, while they have no `onClick` and no `click` handler of their own, and 0 for the close box. `onClose` runs before the dialog -closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled -OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside -a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in -function. A shown dialog can be shown again after it closes. +the other radio buttons of its set off. An edit field gives its text when it loses the keyboard focus, at Enter in +a one-line field, or before a click on another control, and a slider gives its value when it is let go: each runs +`onChanging` and then `onChange`. A list's new selection runs `onChange`. Handlers run in the run's instructions, +and a handler that does not end stops the run at its limit. `show()` returns the number given to `close(result)` +(0 when left out), 1 when the default button is clicked and 2 when the cancel button is clicked, and 0 for the +close box. The default or cancel button closes the dialog only when it has no `onClick` and no `click` handler of +its own and no `capture` handler on a container stopped the click; `click` handlers on the containers that do not +capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and +returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the +cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside a handler, +or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. A +shown dialog can be shown again after it closes. `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws From 66f081428acf7ee5d44d8aeb823d127d01695782 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:08:15 -0800 Subject: [PATCH 11/29] Scripts: queued ScriptUI events follow their control by id after a handler removes one - Each ScriptUI element gets an id that the dialog's description carries. The app keeps a queued click or change, and each typed text, with its control's id instead of the control's position in its container, so a handler that removes a control no longer sends a later click or typed text to the control that moved into its place. An event whose control was removed is dropped, and so is a queued list change when a handler changed the list's items. - A container that no longer holds the control when its turn comes does not get the event, and a listener that an earlier one removed in the same event does not run. The containers above the target stay kept from collection while the listeners run. - A removed control and the controls it holds have no `window`; `removeAll` throws on them like `add` and `remove`. - Every element starts with its listener list, which a script cannot replace, and `remove` and `removeAll` refuse an object made to look like an element of a real dialog. - docs/mcp.md says a group takes its properties fourth when the third argument is not an object, as the code does. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/scriptui.rs | 4 + crates/js/src/scriptui.rs | 172 ++++++++++++++++---- crates/js/src/scriptui_tests.rs | 69 ++++++++ crates/ui-egui/src/dialogs/script_window.rs | 91 +++++------ crates/ui-egui/src/tests/script_window.rs | 58 ++++++- docs/mcp.md | 15 +- 7 files changed, 322 insertions(+), 89 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 1c569c99a3..5d6147b564 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, 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; other event types throw that they are not available yet), a removed control leaves the dialog, 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, 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; other event types throw that they are not available yet), 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/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 11475fb832..bdc7e993b7 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -121,6 +121,9 @@ pub struct UiRect { #[derive(Clone, Debug, PartialEq)] pub struct UiNode { pub kind: UiKind, + /// A number no other element of the run has, which stays with the element while the script + /// adds and removes controls; its index in the description when the description gives none. + pub id: u64, /// The index of its container; the dialog's own is 0. pub parent: usize, pub name: String, @@ -493,6 +496,7 @@ pub fn parse(d: &Data) -> Result { let margins = numbers::<4>(field(f, "margins"))?.map_or([0.0; 4], |m| m.map(|v| extent(v).max(0.0))); nodes.push(UiNode { kind, + id: number(field(f, "id")).filter(|n| *n >= 0.0 && n.fract() == 0.0 && *n < 9.0e15).map_or(i as u64, |n| n as u64), parent, name: text(field(f, "name"), "a control's name")?, text: text(field(f, "text"), "a control's text")?, diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 912de3e685..95a2ea9527 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -14,7 +14,9 @@ //! `properties.items`. A list's `add("item", text)` adds an item, `find(text)` finds one and //! `remove(what)` removes one; its `selection` is an item or `null`, and takes an item, an index or //! `null`. A container's `remove(what)` removes a control, which then has no `parent` and no longer -//! belongs to the dialog: `add` and `remove` on it, or on a control it holds, throw an `Error`. +//! belongs to the dialog: its `window`, and that of each control it holds, is `null`, and `add`, +//! `remove` and `removeAll` on them throw an `Error`. Each element has an id, which the description +//! gives, that no other element of the run has. //! Each element starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose //! `width` and `height` are -1, which leaves the size to the layout. Setting a radio button's //! `value` to true sets the other radio buttons next to it in its container to false, as a click @@ -25,7 +27,9 @@ //! or control takes at most [`MAX_LISTENERS`] of them. A handler gets an event object, in the //! capture phase on the containers above the control, then on the control after its `onClick`, //! `onChange` or `onChanging`, then in the bubbling phase on the containers again, until one calls -//! `stopPropagation()`. Events are not cancelable, and `preventDefault()` does nothing. +//! `stopPropagation()`. A handler removed before its turn does not run, and a container that no +//! longer holds the control when its turn comes does not get the event. Events are not cancelable, +//! and `preventDefault()` does nothing. //! `notify(event)` runs the same handlers, and `notify("onClick")` turns a check box over and turns //! a radio button on first; it does not close the dialog. `Window.alert`, `Window.confirm` and //! `Window.prompt` are the global functions of those names, when the host defines them. @@ -92,6 +96,15 @@ const LIST: &str = "__vcList"; const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; +const ID: &str = "__vcId"; + +/// The longest array an element keeps in a slot: a list's items, a container's controls, its +/// listeners (three values each), and the elements of a description. +const LIST_CAP: u32 = { + let most = if MAX_ITEMS > MAX_CONTROLS + 1 { MAX_ITEMS } else { MAX_CONTROLS + 1 }; + let most = if most > 3 * MAX_LISTENERS { most } else { 3 * MAX_LISTENERS }; + most as u32 +}; /// The size properties every element starts with, as objects with `width` and `height`. const SIZES: [&str; 4] = ["preferredSize", "size", "minimumSize", "maximumSize"]; @@ -131,6 +144,10 @@ pub(crate) struct Classes { showing: Option, /// The event objects whose listeners are running, innermost last. dispatching: Vec, + /// The containers above the targets of the running events. + above: Vec, + /// The id the next element gets: a number no other element of the run has. + next_id: f64, } impl Classes { @@ -150,6 +167,7 @@ impl Classes { ]; all.extend(self.showing); all.extend(self.dispatching.iter().copied()); + all.extend(self.above.iter().copied()); all } } @@ -160,6 +178,7 @@ pub(crate) fn end_run(i: &mut Interp) { if let Some(c) = i.script_ui.as_mut() { c.showing = None; c.dispatching.clear(); + c.above.clear(); } } @@ -232,15 +251,38 @@ fn window_of(i: &mut Interp, o: ObjId, what: &str) -> JsResult { } } +/// [`window_of`] for an element whose controls or items are to be removed, checked to be in that +/// dialog: each container from it up to the dialog holds the one below. An object a script made to +/// look like an element is a `TypeError` naming `what`. +fn window_in(i: &mut Interp, o: ObjId, what: &str) -> JsResult { + let win = window_of(i, o, what)?; + let mut at = o; + for _ in 0..=MAX_DEPTH { + if at == win { + break; + } + let Some(p) = object_slot(i, at, PARENT)? else { break }; + if !kids_of(i, p)?.iter().any(|k| same(k, &Value::Object(at))) { + break; + } + at = p; + } + if at == win && object_slot(i, win, WINDOW)? == Some(win) { + return Ok(win); + } + Err(i.type_error(&format!("{what}: this is not a ScriptUI window or control"))) +} + /// Are `a` and `b` the same object? fn same(a: &Value, b: &Value) -> bool { matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) } -/// The values of an array made by [`list`]. +/// The values of an array made by [`list`]. An array longer than any such array ([`LIST_CAP`]), +/// which only an object a script made to look like an element holds, reads as empty. fn list_values(i: &Interp, a: ObjId) -> JsResult> { let length = match &i.object(a)?.class { - Class::Array { length, .. } => *length, + Class::Array { length, .. } if *length <= LIST_CAP => *length, _ => return Ok(Vec::new()), }; (0..length) @@ -311,6 +353,16 @@ fn new_element( set_slot(i, o, PARENT, parent.clone())?; set_slot(i, o, WINDOW, Value::Object(window))?; set_slot(i, o, DEPTH, Value::Number(depth as f64))?; + let id = match i.script_ui.as_mut() { + Some(c) => { + c.next_id += 1.0; + c.next_id + } + None => 0.0, + }; + set_slot(i, o, ID, Value::Number(id))?; + let listeners = list(i, &[], false)?; + set_slot(i, o, LISTENERS, Value::Object(listeners))?; set_open(i, o, "type", Value::str(kind))?; set_open(i, o, "parent", parent)?; set_open(i, o, "window", Value::Object(window))?; @@ -650,8 +702,8 @@ fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult /// `list.removeAll()`. fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let o = list_of(i, &this, "removeAll")?; + let win = window_in(i, o, "removeAll")?; let n = items_of(i, o)?.len() as f64; - let win = window_of(i, o, "removeAll")?; let count = number_slot(i, win, ITEM_COUNT)?; set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; let kept = list(i, &[], false)?; @@ -822,17 +874,28 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, event: ObjId, phase: f64) -> JsResult { - let wanted: Vec = - listeners_of(i, at)?.into_iter().filter(|(t, _, c)| is_type(t, ty) && capture.is_none_or(|want| *c == want)).map(|(_, f, _)| f).collect(); - if wanted.is_empty() { + let wanted = |i: &Interp| -> JsResult> { + Ok(listeners_of(i, at)? + .into_iter() + .filter(|(t, _, c)| is_type(t, ty) && capture.is_none_or(|want| *c == want)) + .map(|(_, f, c)| (f, c)) + .collect()) + }; + let first = wanted(i)?; + if first.is_empty() { return Ok(false); } - i.rooted(&wanted.clone(), |i| { + let functions: Vec = first.iter().map(|(f, _)| f.clone()).collect(); + i.rooted(&functions, |i| { set_open(i, event, "currentTarget", Value::Object(at))?; set_open(i, event, "eventPhase", Value::Number(phase))?; - for f in &wanted { + for (f, c) in &first { + if !wanted(i)?.iter().any(|(g, d)| same(g, f) && d == c) { + continue; + } i.call(f, &Value::Object(at), &[Value::Object(event)])?; } Ok(true) @@ -843,8 +906,35 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve /// capture, its `callback`, its own listeners, then the listeners of the containers that do not /// capture, until one stops it. → whether the event was handled: the element had a callback or a /// listener for it, or a capturing listener above it stopped it. Listeners of the containers that -/// do not capture do not count. +/// do not capture do not count. A container that a listener took the element out of before its +/// turn does not hear the event. fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { + let above = containers_above(i, target)?; + let proto = classes(i)?.event_proto; + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; + let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + // The event and the containers stay kept from collection while the listeners run. + let kept = match i.script_ui.as_mut() { + Some(c) => { + c.dispatching.push(event); + let mark = c.above.len(); + c.above.extend(above.iter().copied()); + mark + } + None => 0, + }; + let r = run_event(i, event, target, &above, ty, callback); + if let Some(c) = i.script_ui.as_mut() { + if let Some(n) = c.dispatching.iter().rposition(|e| *e == event) { + c.dispatching.remove(n); + } + c.above.truncate(kept); + } + r +} + +/// The containers that hold `target`, innermost first. +fn containers_above(i: &mut Interp, target: ObjId) -> JsResult> { let mut above = Vec::new(); let mut at = object_slot(i, target, PARENT)?; while let Some(p) = at { @@ -852,19 +942,7 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult above.push(p); at = object_slot(i, p, PARENT)?; } - let proto = classes(i)?.event_proto; - i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; - let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); - if let Some(c) = i.script_ui.as_mut() { - c.dispatching.push(event); - } - let r = run_event(i, event, target, &above, ty, callback); - if let Some(c) = i.script_ui.as_mut() - && let Some(n) = c.dispatching.iter().rposition(|e| *e == event) - { - c.dispatching.remove(n); - } - r + Ok(above) } /// The phases of [`dispatch`] for the event object `event`. @@ -878,6 +956,9 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & set_open(i, event, "detail", Value::Number(if ty == "click" { 1.0 } else { 0.0 }))?; let stopped = |i: &Interp| -> JsResult { Ok(slot(i, event, STOPPED)?.truthy()) }; for p in above.iter().rev() { + if !containers_above(i, target)?.contains(p) { + continue; + } run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { return Ok(true); @@ -887,6 +968,9 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & let heard = run_listeners(i, target, ty, None, event, 2.0)?; if bubbles && !stopped(i)? { for p in above { + if !containers_above(i, target)?.contains(p) { + continue; + } run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; @@ -965,6 +1049,19 @@ fn find(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult Ok(at.and_then(|n| items.get(n).cloned()).unwrap_or(Value::Null)) } +/// The controls `o` holds whose container is `o`. +fn own_kids(i: &Interp, o: ObjId) -> JsResult> { + let mut own = Vec::new(); + for k in kids_of(i, o)? { + if let Some(c) = k.as_object() + && object_slot(i, c, PARENT)? == Some(o) + { + own.push(k); + } + } + Ok(own) +} + /// The controls in `c` and in the containers it holds, `c` included, and their list items. fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { let (mut controls, mut items) = (0.0, 0.0); @@ -974,7 +1071,7 @@ fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { let Some(o) = v.as_object() else { continue }; controls += 1.0; items += items_of(i, o)?.len() as f64; - stack.extend(kids_of(i, o)?); + stack.extend(own_kids(i, o)?); } Ok((controls, items)) } @@ -984,7 +1081,7 @@ fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "remove")?; let what = arg(args, 0); - window_of(i, o, "remove")?; + window_in(i, o, "remove")?; if kind == "dropdownlist" || kind == "listbox" { let before = slot(i, o, ITEMS)?; let (mut items, at) = i.rooted(std::slice::from_ref(&before), |i| index_named(i, &what, |i| items_of(i, o)))?; @@ -992,7 +1089,7 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult JsResult<()> { let Some(root) = c.as_object() else { return Ok(()) }; - set_slot(i, root, PARENT, Value::Null)?; - set_open(i, root, "parent", Value::Null)?; let mut stack = vec![c.clone()]; while let Some(v) = stack.pop() { i.use_fuel()?; let Some(o) = v.as_object() else { continue }; + stack.extend(own_kids(i, o)?); set_slot(i, o, WINDOW, Value::Null)?; - stack.extend(kids_of(i, o)?); + set_open(i, o, "window", Value::Null)?; } - Ok(()) + set_slot(i, root, PARENT, Value::Null)?; + set_open(i, root, "parent", Value::Null) } fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { @@ -1439,6 +1540,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let text = text_of(i, &text_v, "a control's text")?; let mut d: Vec<(String, Data)> = vec![ ("kind".into(), Data::String(kind.clone())), + ("id".into(), Data::Number(number_slot(i, o, ID)?)), ("parent".into(), Data::Number(*parent)), ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), @@ -1580,6 +1682,8 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul radio_set, showing: None, dispatching: Vec::new(), + above: Vec::new(), + next_id: 0.0, }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 4847ba5ac3..1fbf739cdb 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -578,3 +578,72 @@ fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw .unwrap(); assert_eq!(v, JsValue::String("remove: the list changed while the item was looked up|2|c".into())); } + +#[test] +fn a_control_a_listener_removes_while_its_click_runs_no_longer_reaches_its_containers() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var heard = []; \ + b.addEventListener('click', function () { g.remove(b); }); \ + g.addEventListener('click', function () { heard.push('g'); }); w.addEventListener('click', function () { heard.push('w'); }); \ + b.notify('onClick'); [heard.length, b.parent, b.window].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("0||".into())); +} + +#[test] +fn a_listener_removed_by_an_earlier_one_in_the_same_event_does_not_run() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var ran = []; function second() { ran.push(2); } \ + b.addEventListener('click', function () { ran.push(1); b.removeEventListener('click', second); }); \ + b.addEventListener('click', second); b.notify('onClick'); ran.join(',')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1".into())); +} + +#[test] +fn a_script_cannot_put_its_own_listener_list_on_a_control() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var a = []; a.length = 4000000000; \ + var m; try { Object.defineProperty(b, '__vcListeners', {value: a}); m = 'defined'; } catch (e) { m = e.name; } \ + b.notify('onClick'); m", + ) + .unwrap(); + assert_eq!(v, JsValue::String("TypeError".into())); +} + +#[test] +fn an_object_made_to_look_like_an_element_reads_a_long_list_as_empty() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var a = []; a.length = 4000000000; \ + var f = {__vcKind: 'button', __vcListeners: a, __vcKids: a}; b.notify.call(f, 'onClick'); \ + b.findElement.call(f, 'x') === null", + ) + .unwrap(); + assert_eq!(v, JsValue::Bool(true)); +} + +#[test] +fn remove_refuses_an_object_made_to_look_like_a_container_of_a_real_control() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var g = w.add('group'); var b = g.add('button'); var l = g.add('listbox', undefined, ['a']); \ + var f = {__vcKind: 'group', __vcWindow: w, __vcParent: w, __vcKids: [b]}; \ + var fl = {__vcKind: 'listbox', __vcWindow: w, __vcParent: w, __vcItems: l.items}; var m = []; \ + try { w.remove.call(f, 0); m.push('removed'); } catch (e) { m.push(e.name); } \ + try { l.removeAll.call(fl); m.push('removed'); } catch (e) { m.push(e.name); } \ + [m.join(','), b.parent === g, b.window === w].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("TypeError,TypeError|true|true".into())); +} diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 88d53cac21..e72be16209 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -131,50 +131,46 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAc } return DialogAction::None; } - let next = queue.remove(0); - if !queue.is_empty() { - d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); - } - if let Value::Object(mut fields) = next { - // The control the event was given to, found again in the dialog as the handlers that ran - // since left it. - let at = fields.remove(PLACE_KEY).and_then(|p| serde_json::from_value::>(p).ok()).and_then(|p| control_at(&w, &p)); - if let Some(i) = at { - fields.insert("control".into(), json!(i)); + // An event whose control or list items a handler removed since it was given is dropped. + while !queue.is_empty() { + let next = queue.remove(0); + let Some(fields) = for_dialog(&w, next) else { continue }; + if !queue.is_empty() { + d.fields.insert(QUEUE_KEY.into(), Value::Array(queue)); } d.fields.extend(fields); + return DialogAction::Confirm; } - DialogAction::Confirm + DialogAction::None } -/// The field of a queued event that holds where its control sits in the dialog ([`place_of`]). -const PLACE_KEY: &str = "place"; +/// The field of a queued event that holds its control's id ([`UiNode::id`]). +const ID_KEY: &str = "id"; -/// Where control `i` sits in the dialog `w`: its position among its container's controls, after -/// its container's own position, and so on up to the dialog. `add` puts a new control after the -/// others in its container, so a handler that adds controls leaves the place of every other one -/// as it was, while its index in the dialog's list of elements can move. -fn place_of(w: &ScriptUiDialog, mut i: usize) -> Vec { - let mut place = Vec::new(); - while i > 0 { - let Some(n) = w.nodes.get(i) else { return Vec::new() }; - place.push(w.nodes.iter().take(i).skip(1).filter(|m| m.parent == n.parent).count()); - if n.parent >= i { - return Vec::new(); - } - i = n.parent; +/// The field of a queued list change that holds the list's items as the person saw them. +const ITEMS_KEY: &str = "items"; + +/// The queued event `next` as fields for the dialog `w`, with `control` the index its control has +/// in `w` now, which moves when a handler adds or removes controls before it. `None` when `w` no +/// longer has the control, or for a list's change, when the list's items are no longer those the +/// person chose from. +fn for_dialog(w: &ScriptUiDialog, next: Value) -> Option> { + let Value::Object(mut fields) = next else { return None }; + let items = fields.remove(ITEMS_KEY); + let Some(id) = fields.remove(ID_KEY) else { return Some(fields) }; + let i = id.as_u64().and_then(|id| index_of(w, id))?; + if let Some(items) = items + && serde_json::from_value::>(items).ok().as_ref() != Some(&w.nodes[i].items) + { + return None; } - place.reverse(); - place + fields.insert("control".into(), json!(i)); + Some(fields) } -/// The index of the control at `place` ([`place_of`]) in the dialog `w`, if it has one. -fn control_at(w: &ScriptUiDialog, place: &[usize]) -> Option { - let mut at = 0; - for &k in place { - at = w.nodes.iter().enumerate().skip(1).filter(|(_, n)| n.parent == at).nth(k)?.0; - } - (at > 0).then_some(at) +/// The index of the control whose id ([`UiNode::id`]) is `id` in the dialog `w`, if it has one. +fn index_of(w: &ScriptUiDialog, id: u64) -> Option { + w.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0) } /// The field that holds the events the person gave in one frame that the script has not had yet; @@ -240,14 +236,13 @@ fn draft_key(i: usize) -> String { format!("text{i}") } -/// The field that holds, for each text typed in an edit field, where the field sat ([`place_of`]) -/// in the dialog the text was typed in. +/// The field that holds, for each text typed in an edit field, the field's id ([`UiNode::id`]). const DRAFT_PLACES_KEY: &str = "draftPlaces"; -/// Records where the field of each typed text sits in the dialog `w`, for [`move_drafts`]. +/// Records the id of the field of each typed text in the dialog `w`, for [`move_drafts`]. fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { let places: serde_json::Map = - (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(place_of(w, i)))).collect(); + (1..w.nodes.len()).map(|i| (i, draft_key(i))).filter(|(_, k)| d.fields.contains_key(k)).map(|(i, k)| (k, json!(w.nodes[i].id))).collect(); if places.is_empty() { d.fields.remove(DRAFT_PLACES_KEY); } else { @@ -256,14 +251,14 @@ fn note_draft_places(w: &ScriptUiDialog, d: &mut Dialog) { } /// Puts each typed text that [`note_draft_places`] recorded under the index its field has in the -/// dialog `w`, which moves when a handler adds controls before the field. A text whose field the -/// dialog no longer has is dropped. +/// dialog `w`, which moves when a handler adds or removes controls before the field. A text whose +/// field the dialog no longer has is dropped. fn move_drafts(w: &ScriptUiDialog, d: &mut Dialog) { let Some(Value::Object(places)) = d.fields.remove(DRAFT_PLACES_KEY) else { return }; let mut moved = Vec::new(); - for (key, place) in places { + for (key, id) in places { let Some(text) = d.fields.remove(&key) else { continue }; - let at = serde_json::from_value::>(place).ok().and_then(|p| control_at(w, &p)); + let at = id.as_u64().and_then(|id| index_of(w, id)); if let Some(i) = at.filter(|i| w.nodes.get(*i).is_some_and(|n| n.kind == UiKind::EditText)) { moved.push((draft_key(i), text)); } @@ -439,7 +434,8 @@ fn edit(ui: &mut egui::Ui, d: &mut Dialog, rect: egui::Rect, (i, n, prompt): (us } /// `event` in the dialog `w` as the dialog's `event`, `control` and `value` fields, and for a -/// click or a change, the control's place ([`PLACE_KEY`]). +/// click or a change, the control's id ([`ID_KEY`]), and for a list's change, its items +/// ([`ITEMS_KEY`]). fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { let (name, control, value) = match event { UiEvent::Click(i) => ("click", Some(*i), Value::Null), @@ -449,8 +445,11 @@ fn event_fields(w: &ScriptUiDialog, event: &UiEvent) -> Value { UiEvent::Close => ("close", None, Value::Null), }; let mut fields = json!({"event": name, "control": control, "value": value}); - if let Some(i) = control { - fields[PLACE_KEY] = json!(place_of(w, i)); + if let Some(n) = control.and_then(|i| w.nodes.get(i)) { + fields[ID_KEY] = json!(n.id); + if matches!(event, UiEvent::Change(_, UiValue::Index(_))) { + fields[ITEMS_KEY] = json!(n.items); + } } fields } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index ad6533004a..489b2f97fb 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -462,10 +462,11 @@ fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_an ); assert!(until_window(&mut app)); frame(&mut app, Vec::new()); + let ok = app.session.script_window().unwrap().nodes[4].id; give(&mut app, json!({"event": "click", "control": "Grow"})).unwrap(); let d = app.ui.dialog.as_mut().unwrap(); d.fields.insert("text2".into(), json!("typed")); - d.fields.insert("queued".into(), json!([{"event": "click", "control": 4, "value": null, "place": [3]}])); + d.fields.insert("queued".into(), json!([{"event": "click", "control": 4, "value": null, "id": ok}])); frame(&mut app, Vec::new()); for _ in 0..10_000 { if app.ui.dialog.as_ref().is_some_and(|d| d.kind == dialogs::script_run::GROWTH_KIND) { @@ -484,6 +485,61 @@ fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_an assert_eq!(log(&app), json!([[1, "typed"]])); } +#[test] +fn queued_clicks_reach_their_buttons_after_a_handler_removes_a_control_before_them() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group'); var x = g.add('button', undefined, 'x'); var y = g.add('button', undefined, 'y'); \ + var z = g.add('button', undefined, 'z'); var hit = []; x.onClick = function () { hit.push('x'); g.remove(x); }; \ + y.onClick = function () { hit.push('y'); }; z.onClick = function () { hit.push('z'); }; vc.log([w.show(), hit]);", + ); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let (x, y) = (w.nodes[2].id, w.nodes[3].id); + give(&mut app, json!({"event": "click", "control": "x"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert( + "queued".into(), + json!([{"event": "click", "control": 2, "value": null, "id": x}, {"event": "click", "control": 3, "value": null, "id": y}]), + ); + assert!(until_window(&mut app), "the script runs x's handler and waits again"); + assert_eq!(app.session.script_window().unwrap().nodes[2].text, "y", "the handler removed x"); + frame(&mut app, Vec::new()); + assert!(until_window(&mut app), "the script runs y's handler and waits again"); + assert!(!app.ui.dialog.as_ref().unwrap().fields.contains_key("queued"), "nothing is left queued"); + give(&mut app, json!({"event": "close"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, ["x", "y"]]]), "the click on the removed x is dropped and the click on y reaches y"); +} + +#[test] +fn a_queued_list_change_is_dropped_after_a_handler_removes_an_item() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var rm = w.add('button', undefined, 'Remove'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); \ + rm.onClick = function () { l.remove(0); }; vc.log([w.show(), l.selection === null]);", + ); + assert!(until_window(&mut app)); + let w = app.session.script_window().unwrap(); + let list = w.nodes[2].id; + give(&mut app, json!({"event": "click", "control": "Remove"})).unwrap(); + app.ui + .dialog + .as_mut() + .unwrap() + .fields + .insert("queued".into(), json!([{"event": "change", "control": 2, "value": 1, "id": list, "items": ["a", "b", "c"]}])); + assert!(until_window(&mut app), "the script runs the handler and waits again"); + frame(&mut app, Vec::new()); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.fields.contains_key("queued") && !d.fields.contains_key("event"), "the change is dropped"); + assert_eq!(app.session.script_window().unwrap().nodes[2].selection, None); + give(&mut app, json!({"event": "close"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, true]])); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 63813fbe7f..0d51d87d1a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2909,9 +2909,9 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes - `properties` right after `bounds`, or after an empty third argument, and a list may take `properties` right - after `bounds` in place of its items, with the item texts in `properties.items`; a list given items both ways - throws a `TypeError`. The `alignment` in `properties`, + `properties` right after `bounds`, or fourth when the third argument is not an object, and a list may take + `properties` right after `bounds` in place of its items, with the item texts in `properties.items`; a list given + items both ways throws a `TypeError`. The `alignment` in `properties`, and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values (VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an @@ -2927,8 +2927,9 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item - or a control that is not there does nothing. A removed control has no `parent` and its handlers no longer reach - the containers it was in; `add` and `remove` on it, or on a control it holds, throw an `Error`. When a `text` + or a control that is not there does nothing. A removed control has no `parent`, it and the controls it holds have + no `window`, and its events no longer reach the containers it was in, also when a handler removes it while its + event runs; `add`, `remove` and `removeAll` on it, or on a control it holds, throw an `Error`. When a `text` getter changes the list or container while `remove(text)` looks for a match, `remove` throws an `Error` and removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. @@ -2941,8 +2942,8 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `click` listeners. `notify` does not close the dialog, even for the default or cancel button. `notify()` gives a click for a button, a check box and a radio button, and a change for the others. - `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`, - and `removeEventListener` with the same arguments removes it; a function registered twice for the same type and - phase runs once. `show` can be registered only on the dialog, and on a control it throws an `Error`. A window or + and `removeEventListener` with the same arguments removes it, so that it does not run even when the event it was + waiting for is already running; a function registered twice for the same type and phase runs once. `show` can be registered only on the dialog, and on a control it throws an `Error`. A window or control takes at most 256 handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own limit). A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, `cancelable` (always false), `detail` (1 for a click), `stopPropagation()` and `preventDefault()`, which does nothing. The From e5d3c9a7fcae443aa264e33bb892b20ef945af2c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 23 Nov 2026 13:26:13 -0800 Subject: [PATCH 12/29] Scripts: a dialog listener's close(result) decides show() for the default button - When a click on the default or cancel button has no handler of the button's own, a listener on a container that calls close(result) now decides what show() returns; before, the button's result 1 or 2 replaced it. - An event on objects made to look like controls whose parents form a cycle ends with a TypeError once the chain is longer than a dialog's nesting allows, instead of walking the cycle until the run's fuel is gone. - The Run Script params text says that an unknown event type throws, and the progress line says that only the dialog takes a show listener. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/js/src/scriptui.rs | 9 +++++++-- crates/js/src/scriptui_tests.rs | 30 ++++++++++++++++++++++++++---- docs/mcp.md | 5 +++-- docs/target-app-parity.md | 2 +- 5 files changed, 38 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 5d6147b564..7a2676f300 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; other event types throw that they are not available yet), 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, 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", always, run ), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 95a2ea9527..febbcea099 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -933,12 +933,16 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult r } -/// The containers that hold `target`, innermost first. +/// The containers that hold `target`, innermost first. A chain longer than a dialog's nesting +/// allows comes from objects a script made to look like elements, and is a `TypeError`. fn containers_above(i: &mut Interp, target: ObjId) -> JsResult> { let mut above = Vec::new(); let mut at = object_slot(i, target, PARENT)?; while let Some(p) = at { i.use_fuel()?; + if above.len() > MAX_DEPTH { + return Err(i.type_error("the event's target is not a ScriptUI window or control")); + } above.push(p); at = object_slot(i, p, PARENT)?; } @@ -1331,7 +1335,8 @@ fn answered(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { let value = slot(i, ev, "value")?; match event.as_str() { "click" => { - if !click_control(i, c, &kind)? && kind == "button" { + // A listener above the button that closed the dialog gives the result. + if !click_control(i, c, &kind)? && kind == "button" && matches!(slot(i, win, CLOSING)?, Value::Undefined) { let is = |k: usize| matches!(arg(keep, k), Value::Number(n) if n == id as f64); if is(2) { set_slot(i, win, CLOSING, Value::Number(1.0))?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 1fbf739cdb..263ae48f8f 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -425,16 +425,38 @@ fn listeners_run_in_the_capture_target_and_bubbling_phases_until_one_stops() { "a button with a click listener does not close the dialog by itself, and the same listener is added once" ); for (source, want) in [ - ("new Window('dialog').addEventListener('mouseover', function () {})", "addEventListener: the event mouseover is not available yet"), - ("new Window('dialog').addEventListener('wobble', function () {})", "addEventListener: there is no event wobble"), - ("new Window('dialog').addEventListener('click', 'code')", "addEventListener: give the handler as a function"), + ("w.addEventListener('click', function () { w.close(3); })", "3"), + ("w.addEventListener('click', function () { w.close(3); }, true)", "3"), + ("w.addEventListener('click', function () {})", "1"), + ] { + let (mut r, _, _) = realm(vec![click(1)]); + let source = format!("var w = new Window('dialog'); w.add('button', undefined, 'OK'); {source}; String(w.show())"); + assert_eq!(r.run(&source).unwrap(), JsValue::String(want.into()), "a dialog listener's close(result) decides what show() gives: {source}"); + } + for (source, want) in [ + ("new Window('dialog').addEventListener('mouseover', function () {})", "Error addEventListener: the event mouseover is not available yet"), + ("new Window('dialog').addEventListener('wobble', function () {})", "Error addEventListener: there is no event wobble"), + ("new Window('dialog').addEventListener('click', 'code')", "TypeError addEventListener: give the handler as a function"), ] { let (mut r, _, _) = realm(Vec::new()); - let e = r.run(&format!("try {{ {source}; 'added' }} catch (e) {{ e.message }}")).unwrap(); + let e = r.run(&format!("try {{ {source}; 'added' }} catch (e) {{ e.name + ' ' + e.message }}")).unwrap(); assert_eq!(e, JsValue::String(want.into()), "{source}"); } } +#[test] +fn an_event_on_objects_made_to_look_like_controls_ends_with_a_type_error() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var b = new Window('dialog').add('button', undefined, 'Go'); var ran = false; \ + var f = {__vcKind: 'button'}; var g = {__vcKind: 'group'}; f.__vcParent = g; g.__vcParent = f; f.onClick = function () { ran = true; }; \ + try { b.notify.call(f, 'onClick'); 'ran' } catch (e) { e.name + ' ' + ran }", + ) + .unwrap(); + assert_eq!(v, JsValue::String("TypeError false".into()), "a parent cycle ends at once, not when the run's fuel is gone"); +} + #[test] fn lists_find_and_remove_items_and_take_their_items_in_the_creation_properties() { let (mut r, _, _) = realm(Vec::new()); diff --git a/docs/mcp.md b/docs/mcp.md index 0d51d87d1a..1317559a57 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2943,8 +2943,9 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s click for a button, a check box and a radio button, and a change for the others. - `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`, and `removeEventListener` with the same arguments removes it, so that it does not run even when the event it was - waiting for is already running; a function registered twice for the same type and phase runs once. `show` can be registered only on the dialog, and on a control it throws an `Error`. A window or - control takes at most 256 handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own + waiting for is already running; a function registered twice for the same type and phase runs once. `show` can + be registered only on the dialog, and on a control it throws an `Error`. A window or control takes at most 256 + handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own limit). A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, `cancelable` (always false), `detail` (1 for a click), `stopPropagation()` and `preventDefault()`, which does nothing. The containers above the control run their `capture` handlers first, then the control runs its `onClick`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ead7d36125..b47a547b34 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 `addEventListener` for clicks, changes and `show`, `notify`, size objects a script can set one side of, and lists' `find` and `remove`, and `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. 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`. - 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`). From e323636ac87a81f44f8f81cb09a5dff5599e8f02 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 13:24:00 -0800 Subject: [PATCH 13/29] Scripts: the report lists a ScriptUI dialog before the dialogs its handlers open A ScriptUI dialog's record was added when its show() ended, so an alert, confirm or prompt a handler opened came first in the report's dialogs. The record now keeps the place the dialog took when it opened. When the dialogs its handlers opened leave no room for it, the last of them are dropped until it fits, and the list stops before it when it does not fit alone, so the list keeps the first dialogs in the order they opened. --- crates/engine/src/script/dialogs.rs | 56 ++++++++++++++++++++-- crates/engine/src/tests/script_scriptui.rs | 15 ++++++ 2 files changed, 67 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/dialogs.rs b/crates/engine/src/script/dialogs.rs index fa3043b0a7..c635db0585 100644 --- a/crates/engine/src/script/dialogs.rs +++ b/crates/engine/src/script/dialogs.rs @@ -217,6 +217,9 @@ pub(crate) struct Dialogs { truncated: Cell, /// The ScriptUI dialog whose `show()` is running. window: RefCell>, + /// Where that dialog's record is in `records`, kept from when it opened so a dialog a handler + /// opens is listed after it; `None` when the list had stopped at its limit. + window_slot: Cell>, /// That dialog waits for what the person does. window_waiting: Cell, /// The `show()` calls the run has made. @@ -236,6 +239,7 @@ impl Dialogs { count: Cell::new(0), truncated: Cell::new(false), window: RefCell::default(), + window_slot: Cell::new(None), window_waiting: Cell::new(false), shows: Cell::new(0), } @@ -313,10 +317,54 @@ impl Dialogs { } } } + self.window_slot.set(self.reserve_record()); *self.window.borrow_mut() = Some(showing); Ok(()) } + /// Keeps a place in the list for the ScriptUI dialog that opens now, counted; its bytes count + /// once the dialog ends. → the place, or `None` when the list stopped at its limit. + fn reserve_record(&self) -> Option { + self.count.set(self.count.get().saturating_add(1)); + let mut records = self.records.borrow_mut(); + if self.truncated.get() || records.len() >= MAX_RECORDS { + self.truncated.set(true); + return None; + } + records.push(Value::Null); + Some(records.len() - 1) + } + + /// Puts the record of the ScriptUI dialog `showing`, with its `answer`, in the place it took + /// in the list when it opened. When the dialogs a handler opened left no room for it, the list + /// drops the last of them until it fits, or stops before the dialog when it does not fit + /// alone, so it still holds the first dialogs in the order they opened, and is marked as + /// stopped at its limit. + fn end_record(&self, showing: &Showing, answer: Value) { + let Some(i) = self.window_slot.take() else { return }; + let size = |r: &Value| serde_json::to_vec(r).map_or(usize::MAX, |b| b.len()); + let r = showing.record(answer); + let bytes = size(&r); + let mut records = self.records.borrow_mut(); + if i >= records.len() { + return; + } + while self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES && records.len() > i + 1 { + let last = records.pop().map_or(0, |r| size(&r)); + self.record_bytes.set(self.record_bytes.get().saturating_sub(last)); + self.truncated.set(true); + } + if self.record_bytes.get().saturating_add(bytes) > MAX_RECORD_BYTES { + records.truncate(i); + self.truncated.set(true); + return; + } + self.record_bytes.set(self.record_bytes.get() + bytes); + if let Some(slot) = records.get_mut(i) { + *slot = r; + } + } + /// The dialog that is showing waits, as `dialog` now is. A run with nobody to ask takes the /// next step of its answer. pub(crate) fn window_wait(&self, mut dialog: ScriptUiDialog) -> Result { @@ -341,7 +389,7 @@ impl Dialogs { }, }; if let Some(showing) = window.take() { - self.push_record(showing.record(json!("missing"))); + self.end_record(&showing, json!("missing")); } Err(HostError::Abort(failure)) } @@ -355,7 +403,7 @@ impl Dialogs { let steps = if left == 1 { "step" } else { "steps" }; let unused = format!("show: the dialog's answer in `answers` has {left} {steps} the dialog did not use"); if normal && left > 0 { - self.push_record(showing.record(json!("missing"))); + self.end_record(&showing, json!("missing")); return Err(HostError::Abort(unused)); } // A show that a handler's error ended still ends the run when steps are left: the script @@ -371,7 +419,7 @@ impl Dialogs { r if r.fract() == 0.0 && r.abs() < 9.0e15 => json!(r as i64), r => json!(r), }; - self.push_record(showing.record(answer)); + self.end_record(&showing, answer); Ok(()) } @@ -409,7 +457,7 @@ impl Dialogs { } self.window_waiting.set(false); if let Some(showing) = self.window.borrow_mut().take() { - self.push_record(showing.record(json!("stop"))); + self.end_record(&showing, json!("stop")); } } diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index e572d01f64..fdb0fc702c 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -80,6 +80,21 @@ fn a_run_with_nobody_to_ask_takes_the_steps_of_its_window_answer() { assert_eq!(closed["log"], json!([0])); } +#[test] +fn a_dialog_a_handler_opens_is_listed_after_the_window_that_opened_it() { + let mut s = one_doc(); + let source = format!("{FORM} bold.onClick = function () {{ alert('Bolded'); }}; vc.log(w.show());"); + let answers = json!([ + {"kind": "window", "value": [{"control": "Bold", "event": "click"}, {"control": "OK", "event": "click"}]}, + {"kind": "alert", "value": "ok"}, + ]); + let r = headless(&mut s, &source, answers).unwrap(); + assert_eq!(r["log"], json!([1])); + assert_eq!(r["dialogCount"], 2); + assert_eq!(r["dialogs"][0], json!({"kind": "window", "title": "Settings", "controls": 8, "events": 2, "answer": 1}), "{r}"); + assert_eq!((&r["dialogs"][1]["kind"], &r["dialogs"][1]["message"]), (&json!("alert"), &json!("Bolded")), "{r}"); +} + #[test] fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { let mut s = one_doc(); From 13224857bf998f1f5aee5962222197ed5ec1558a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 16:01:35 -0800 Subject: [PATCH 14/29] Scripts: screen readers name every ScriptUI control and read a disabled panel as disabled An edit field, list or slider with no visible prompt and no name from the script had an empty screen-reader name. It is now called "Text" for an edit field and "Value" for the other controls. A panel the script set to enabled = false was reported to screen readers as enabled; it is now reported as disabled. --- crates/ui-egui/src/dialogs/script_window.rs | 33 ++++++++++++++------- crates/ui-egui/src/tests/script_window.rs | 4 +-- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 602a68c4be..7e7c677cdc 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -390,7 +390,7 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n ui.push_id(n.id, |ui| { ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| match n.kind { UiKind::Dialog | UiKind::Group => {} - UiKind::Panel => panel(ui, rect, n), + UiKind::Panel => panel(ui, rect, n, enabled), UiKind::StaticText => { Text::new(n.text.clone()).show(ui); } @@ -460,10 +460,11 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n shown } -/// A panel's frame, with its text over the frame's top edge; screen readers read it as a group. -fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode) { +/// A panel's frame, with its text over the frame's top edge; screen readers read it as a group, +/// disabled when the panel is. +fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) { let frame = rect.shrink(1.0); - let (enabled, name) = (ui.is_enabled(), n.text.clone()); + let (enabled, name) = (enabled && ui.is_enabled(), n.text.clone()); let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); let visuals = ui.visuals(); @@ -475,21 +476,31 @@ fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode) { } /// The name screen readers call a list box or a drop-down list `n` by: the visible static text -/// just before it, or else the name the script gave it. Empty for none. +/// just before it, or else the name the script gave it, or else "Value". fn list_name(n: &UiNode, prompt: &str) -> String { - if prompt.is_empty() { n.name.clone() } else { prompt.to_string() } + match (prompt, n.name.as_str()) { + ("", "") => tl!("Value").to_string(), + ("", name) => name.to_string(), + (prompt, _) => prompt.to_string(), + } } /// The name screen readers call a control with no visible label of its own (an edit field, a /// slider or a progress bar) by: the visible static text just before it in its container, or else -/// the name the script gave it, or else a slider's or progress bar's text. Empty for none. +/// the name the script gave it, or else a slider's or progress bar's text, or else "Text" for an +/// edit field and "Value" for the others. pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { - if !prompt.is_empty() { - prompt.to_string() + let name = if !prompt.is_empty() { + prompt } else if !n.name.is_empty() || n.kind == UiKind::EditText { - n.name.clone() + &n.name } else { - n.text.clone() + &n.text + }; + match name { + "" if n.kind == UiKind::EditText => tl!("Text").to_string(), + "" => tl!("Value").to_string(), + name => name.to_string(), } } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index c936f1762a..16bd6bc28e 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -636,8 +636,8 @@ fn an_unnamed_edit_field_is_called_by_the_static_text_before_it() { let name = |i: usize| script_window::screen_reader_name(&w.nodes[i], script_window::prompt_of(&w, i)); assert_eq!(name(3), "Width:", "the static text before it in its group"); assert_eq!(name(4), "height", "the name the script gave it"); - assert_eq!(name(5), "", "the control before it is no static text"); - assert_eq!(name(7), "", "a hidden static text is no prompt"); + assert_eq!(name(5), "Text", "the control before it is no static text, and the script gave it no name"); + assert_eq!(name(7), "Text", "a hidden static text is no prompt"); assert_eq!(name(9), "Account", "the visible text before it goes before the name the script gave"); app.session.script_request_stop(); assert!(!until_window(&mut app)); From 46478976ce9e1ba277ad76a583d660082dda0718 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:20:38 -0800 Subject: [PATCH 15/29] Scripts: a window answer names a control by its text only when the control has no name A headless window step whose control matched no name fell back to the first control with that text, even when that control had a name of its own, so a step could reach a different control than the one it named. The text now matches only controls without a name. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/scriptui.rs | 6 ++++-- crates/engine/src/tests/script_scriptui.rs | 15 +++++++++++++++ docs/mcp.md | 6 +++--- 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 7a2676f300..64724404ab 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, 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, 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", always, run ), diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index bdc7e993b7..20c11a6239 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -194,10 +194,12 @@ impl ScriptUiDialog { self.nodes.first().map_or((0.0, 0.0), |n| (n.rect.w, n.rect.h)) } - /// The first control whose name, or else whose text, is `control`. + /// The first control whose name is `control`, or else the first control without a name + /// whose text is `control`. pub fn find(&self, control: &str) -> Option { let by = |name: bool| { - self.nodes.iter().enumerate().skip(1).find(|(_, n)| if name { n.name == control } else { n.text == control }).map(|(i, _)| i) + let hit = |n: &UiNode| if name { n.name == control } else { n.name.is_empty() && n.text == control }; + self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i) }; by(true).or_else(|| by(false)) } diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index fdb0fc702c..82d17c6c86 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -118,6 +118,21 @@ fn a_missing_wrong_or_unused_step_ends_the_run_and_rolls_it_back() { } } +#[test] +fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() { + let mut s = one_doc(); + let source = "var w = new Window('dialog'); \ + var named = w.add('button', undefined, 'Apply', {name: 'apply'}); named.onClick = function () { vc.log('named'); }; \ + var plain = w.add('button', undefined, 'Apply'); plain.onClick = function () { vc.log('plain'); }; \ + w.add('button', undefined, 'OK'); w.show();"; + let steps = window(json!([{"control": "Apply", "event": "click"}, {"control": "apply", "event": "click"}, {"control": "OK", "event": "click"}])); + headless(&mut s, source, steps).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["plain", "named"])); + let go = "var w = new Window('dialog'); w.add('button', undefined, 'Go', {name: 'go'}); w.show();"; + let e = headless(&mut s, go, window(json!([{"control": "Go", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named Go"), "{e}"); +} + #[test] fn window_answers_that_do_not_parse_are_refused_before_the_run() { let mut s = one_doc(); diff --git a/docs/mcp.md b/docs/mcp.md index 8d9eaa6a61..eea32290d4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3031,8 +3031,8 @@ asks whether to stop the script, and Cancel shows it again with the events it ha handler takes the run past the growth limit, the question to continue opens over the dialog, and Continue shows the dialog again with those events and the text typed in its fields. An event that waits for the script goes to the control it was given to, and a typed text stays in its field, also after a handler adds controls before that one. -`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name or -its text) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the +`ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name, or +the text of a control without a name) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action` return an error, and Escape shows it in the status bar. Such a text stays in its field when the field loses the @@ -3042,7 +3042,7 @@ open. A run with nobody to ask takes `{kind: "window", value: [step, ...]}` from `answers` for each `show()`. A step is `{control, event: "click"}`, `{control, event: "change", value}` or `{event: "close"}`, where `control` is a -control's `name`, else its text, and `value` is an edit field's text, a slider's number (kept in its range), or a +control's `name`, or the text of a control without a name, and `value` is an edit field's text, a slider's number (kept in its range), or a list's item index (a whole number, such as `2` or `2.0`) or `null`. The dialog takes the next step each time it waits. The run ends with an error that the script cannot catch, and every document goes back, when no step is left, when a step names a control the dialog does not have or that cannot take it, or when the dialog closes, or From aa8c9b8d366e44597cff9f1659762e1521d0951b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 17:29:15 -0800 Subject: [PATCH 16/29] Scripts: ScriptUI builds windows and controls from resource strings new Window() and add() threw that resource specifications were not available yet. They now read a resource specification in place of the type, as https://extendscript.docsforadobe.dev/user-interface-tools/resource-specifications/ describes it: a type, then braces holding `name: value` properties, where `name: Class { ... }` defines a control. - `crates/js/src/scriptui_resource.rs` reads `[name:] Type { ... }`. A value is null, true, false, a quoted string, a number, an inline array or an inline object. The commas between properties may be left out, as in the page's own example. A malformed specification throws a SyntaxError. One longer than 1 MiB or nested more than 64 deep throws a RangeError; these limits are VectorCraft's own. - With a resource specification, new Window() and add() read no other argument. `properties` gives the creation properties. Each control in the braces is added through add(), with its limits of 512 controls nested 16 deep, and set as the container's property of its name. A list's `items` gives its item texts, as add()'s third argument does. Each other value is assigned to the property of its name. Palettes and windows still throw that they are not available yet. - The script.run params text, docs/mcp.md and the Scripts line in docs/target-app-parity.md describe resource specifications. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/tests/script_scriptui.rs | 13 + crates/js/src/lib.rs | 1 + crates/js/src/scriptui.rs | 144 ++++++++- crates/js/src/scriptui_resource.rs | 336 +++++++++++++++++++++ crates/js/src/scriptui_tests.rs | 116 ++++++- docs/mcp.md | 13 +- docs/target-app-parity.md | 2 +- 8 files changed, 614 insertions(+), 13 deletions(-) create mode 100644 crates/js/src/scriptui_resource.rs 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`). From 2782b779e47766e7771066642e62d27d4280cbd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 20:18:02 -0800 Subject: [PATCH 17/29] Scripts: a ScriptUI dialog takes Enter on a slider and caps a list box's rows The dialog opens with the focus on its default button, so Enter clicks it until the person moves into a field; an Enter a slider or check box leaves untaken also clicks it, but not while a question is open over the dialog. A list box shows as many rows as its height holds and scrolls the rest. --- crates/ui-egui/src/dialogs/script_window.rs | 43 +++++++++--- crates/ui-egui/src/tests/script_window.rs | 72 ++++++++++++--------- 2 files changed, 74 insertions(+), 41 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 7e7c677cdc..06d1b94626 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -27,6 +27,8 @@ use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusa use craft::ui::display::{Progress, Text}; use craft::ui::list::{List, ListRow}; use craft::ui::pickers::Select; +use craft::ui::runtime::focus::Initial; +use craft::ui::runtime::keys::take_submit; use craft::ui::sections::{DialogRole, FooterButton}; use craft::ui::text::TextField; use craft::ui::value_drag::Slider; @@ -45,6 +47,18 @@ pub const KIND: &str = "scriptWindow"; /// The most of the dialog's content shown at once; a larger dialog scrolls. const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); +/// The height of a list box row in the engine's layout, and the room the layout adds around the +/// rows. +const LIST_ROW: f32 = 18.0; +const LIST_PAD: f32 = 6.0; + +/// How many rows a list box `height` tall shows; it scrolls the rest, inside the dialog's own +/// scroll. +fn list_rows(height: f32) -> u16 { + let rows = ((height - LIST_PAD) / LIST_ROW).floor(); + if rows.is_finite() { rows.clamp(1.0, f32::from(u16::MAX)) as u16 } else { 1 } +} + /// An event the script has not had yet, with its control by its id ([`UiNode::id`]), which stays /// with the control while a handler adds or removes controls before it. #[derive(Clone, Debug, PartialEq)] @@ -273,17 +287,24 @@ impl StackDialog for ScriptWindow { Some(KIND) } - fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option> { + let top = stack.is_top(self.id()); let heading = match self.window.title() { "" => tl!("Script Alert").to_string(), title => shown_text(title, false), }; let mut events = Vec::new(); let mut typing = false; + let mut submit = false; let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)]; let ScriptWindow { window, waiting, drafts, open, .. } = self; let (window, waiting) = (&*window, *waiting); - let shown = Dialog::new(heading).buttons(buttons).opened(Bind::bound(open)).show(ui, |ui, _| { + // The dialog opens with the focus on its default button, so Enter clicks it until the + // person moves the focus into a field; without one that can be clicked, on its first control. + let focus_default = window.default_element.and_then(|i| window.nodes.get(i)).is_some_and(|n| n.visible && n.enabled); + let initial = if focus_default { Initial::Default } else { Initial::First }; + let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); + let shown = dialog.show(ui, |ui, _| { let (width, height) = window.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { @@ -298,6 +319,9 @@ impl StackDialog for ScriptWindow { events.extend(shown.event); } }); + // An Enter the focused control left untaken (a slider, a check box) is the dialog's, + // unless a question is open over it. + submit = top && !typing && take_submit(ui.ctx()); }); if shown.output.picked == Some(0) { self.stop = true; @@ -312,7 +336,7 @@ impl StackDialog for ScriptWindow { } // Enter in a field belongs to the field; with the focus on any other control, it clicks the // default button. - let enter = ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.is_none()); + let enter = submit || (top && ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.is_none())); if events.is_empty() && self.waiting && !typing && enter { events.extend(self.window.default_element.map(UiEvent::Click)); } @@ -397,7 +421,7 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n UiKind::Button => { let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled); if place.default { - button = button.variant(Variant::PRIMARY); + button = button.variant(Variant::PRIMARY).default_stop(); } if clicked(&button.show(ui)) { shown.event = Some(UiEvent::Click(i)); @@ -432,11 +456,12 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n let selection = n.selection.map(Selection::single).unwrap_or_default(); // Screen readers read the box as a list box, by its name or the static text before // it, with the selected item as its value. - let out = List::::options(list_name(n, prompt)).id_salt(salt).enabled(enabled).selection(Bind::given(selection)).show_items( - ui, - &source, - &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default()), - ); + let out = List::::options(list_name(n, prompt)) + .id_salt(salt) + .enabled(enabled) + .max_rows(list_rows(n.rect.h)) + .selection(Bind::given(selection)) + .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); for event in out.events { if let CollectionEvent::Activate(k) = event && n.selection != Some(k) diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 16bd6bc28e..389cd0e40d 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -5,7 +5,7 @@ use craft::automation::{ControlRequest, Reply}; use craft::ui::dialog::StackDialog as _; use serde_json::{Value, json}; -use vectorcraft_engine::script::{UiEvent, UiValue}; +use vectorcraft_engine::script::{UiEvent, UiKind, UiValue}; use super::script_dialogs::{app, frame, is_open, key, open_id, pump}; use crate::dialogs::script_run::{CLOSE_KIND, CloseQuestion, GROWTH_KIND, GrowthQuestion, ScriptNotice, with_host}; @@ -139,6 +139,9 @@ fn escape_clicks_the_cancel_button_and_closes_a_dialog_without_one() { step(&mut app, Vec::new()); step(&mut app, vec![key(egui::Key::Escape)]); assert!(!until_window(&mut app)); + // The next frame takes down the dialog's window. + step(&mut app, Vec::new()); + assert!(!crate::dialogs::script_run::busy(&app), "the dialog Escape closed leaves nothing open"); assert_eq!(log(&app), json!([2])); start(&mut app, "var w = new Window('dialog'); w.add('statictext', undefined, 'Hi'); vc.log(w.show());"); assert!(until_window(&mut app)); @@ -219,7 +222,7 @@ fn a_dialog_function_after_show_opens_its_own_dialog() { } #[test] -fn an_alert_from_a_handler_opens_over_the_dialog_and_keeps_its_typed_text() { +fn an_alert_from_a_handler_ends_the_run_and_closes_the_dialog() { let mut app = app(); start( &mut app, @@ -227,23 +230,16 @@ fn an_alert_from_a_handler_opens_over_the_dialog_and_keeps_its_typed_text() { b.onClick = function () { alert('told'); }; w.add('button', undefined, 'OK'); vc.log([w.show(), e.text]);", ); assert!(until_window(&mut app)); - give(&mut app, json!({"event": "click", "control": "Tell"})).unwrap(); type_text(&app, 1, "typed"); - for _ in 0..100 { - script_runs::poll(&mut app); - if is_open::(&app) { - break; - } - } - assert!(is_open::(&app) && is_open::(&app), "the alert opens over the dialog"); - super::script_dialogs::confirm(&mut app, crate::dialogs::script_run::NOTICE_KIND); - assert!(until_window(&mut app), "the run waits at its dialog again"); - assert_eq!(typed(&app, 1).as_deref(), Some("typed"), "the text typed in its field stays"); - give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); - assert!(until_window(&mut app), "the script takes the text and waits again"); + give(&mut app, json!({"event": "click", "control": "Tell"})).unwrap(); + assert!(until_window(&mut app), "the script takes the typed text first"); step(&mut app, Vec::new()); - assert!(!until_window(&mut app)); - assert_eq!(log(&app), json!([[1, "typed"]])); + assert!(!until_window(&mut app), "the handler's alert ends the run"); + let report = app.session.script_report().unwrap(); + assert!(report["message"].as_str().is_some_and(|m| m.contains("alert: a dialog cannot open inside a callback")), "{report}"); + assert!(!is_open::(&app) && !is_open::(&app), "no dialog of the run stays open"); + step(&mut app, Vec::new()); + assert!(!crate::dialogs::script_run::busy(&app), "the next frame takes down the dialog's window"); } #[test] @@ -462,18 +458,31 @@ fn continue_on_the_growth_question_shows_the_dialog_again_with_its_queued_click_ with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); until_growth(&mut app); assert!(is_open::(&app), "the question opens over the dialog"); - assert!(super::script_dialogs::confirm(&mut app, GROWTH_KIND)); + assert_eq!(typed(&app, 1).as_deref(), Some("typed"), "the text typed in its field waits under the question"); + // Enter goes to the question over the dialog, whose default is Continue, and clicks nothing + // in the dialog under it. + frame(&app, Vec::new()); + frame(&app, vec![key(egui::Key::Enter)]); + assert!(!is_open::(&app), "Enter answers the question"); + assert_eq!(queued(&app), vec![Queued::Click(4)], "the dialog under it takes no click from Enter"); + pump(&mut app); assert!(is_open::(&app), "Continue shows the dialog again"); - assert_eq!(typed(&app, 1).as_deref(), Some("typed"), "with the text typed in its field"); - assert!(!queued(&app).is_empty(), "and the click still queued"); - assert!(until_window(&mut app), "the script waits at its dialog again"); - step(&mut app, Vec::new()); - assert!(until_window(&mut app), "the script takes the typed text and waits again"); - step(&mut app, Vec::new()); - assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + // The run waits at its dialog again, takes the typed text, then the queued click on OK. + run_to_end(&mut app); assert_eq!(log(&app), json!([[1, "typed"]])); } +/// Takes the run through the events its dialog has queued, one wait at a time, to its end. +fn run_to_end(app: &mut VectorcraftApp) { + for _ in 0..8 { + if !until_window(app) { + return; + } + step(app, Vec::new()); + } + panic!("the run did not end with the events its dialog had queued"); +} + #[test] fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_and_the_run_grows() { let mut app = app(); @@ -493,12 +502,10 @@ fn a_typed_text_stays_with_its_field_after_a_handler_adds_a_control_before_it_an until_growth(&mut app); assert!(super::script_dialogs::confirm(&mut app, GROWTH_KIND)); assert!(until_window(&mut app), "the script waits at its dialog again"); - assert_eq!(app.session.script_window().unwrap().nodes[3].text, "a", "the handler added a control before the edit field"); - assert_eq!(typed(&app, 3).as_deref(), Some("typed"), "the typed text stays with its field"); - step(&mut app, Vec::new()); - assert!(until_window(&mut app), "the script takes the typed text and waits again"); - step(&mut app, Vec::new()); - assert!(!until_window(&mut app), "the queued click on OK closes the dialog"); + let w = app.session.script_window().unwrap(); + assert_eq!(w.nodes[2].text, "Added", "the handler added a control before the edit field"); + assert_eq!((w.nodes[3].kind, w.nodes[3].text.as_str()), (UiKind::EditText, "typed"), "the typed text reached its field, now one place later"); + run_to_end(&mut app); assert_eq!(log(&app), json!([[1, "typed"]])); } @@ -614,7 +621,8 @@ fn ui_dialog_set_with_an_action_gives_the_event() { assert_eq!(r["ok"], false, "the title is read only: {r}"); let r = run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "click", "action": "wave"})); assert_eq!(r["ok"], false, "{r}"); - run(&mut app, "ui.dialog.set", json!({"field": "control", "value": "OK"})); + assert_eq!(with_window(&app, |d| d.json_fields().unwrap()["event"].clone()), Some(Value::Null), "a refused action sets no field"); + run(&mut app, "ui.dialog.set", json!({"fields": [{"field": "event", "value": "click"}, {"field": "control", "value": "OK"}]})); let r = run(&mut app, "ui.dialog.confirm", json!({})); assert_eq!(r["ok"], true, "{r}"); assert!(!until_window(&mut app)); From 99df55dda2e2c11ab021a2323d8794a88e6c93a6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 20:31:53 -0800 Subject: [PATCH 18/29] Scripts: docs say a ScriptUI handler in the app cannot open alert, confirm, prompt or a file dialog --- crates/engine/src/cmd/scripts.rs | 2 +- docs/mcp.md | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 64724404ab..95297f89d3 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, 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, 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, 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 in the app so do alert, confirm, prompt and the file dialogs a handler calls, 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/docs/mcp.md b/docs/mcp.md index 20ea5f194b..e42ae7391a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3011,8 +3011,9 @@ its own and no `capture` handler on a container stopped the click; `click` handl capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside a handler, -or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. A -shown dialog can be shown again after it closes. +or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. In +the app, `alert`, `confirm`, `prompt` and the file dialogs called from a handler also throw an `Error`; in a run with +nobody to ask, `alert`, `confirm` and `prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes. `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws From a28882a78c5f5760357b4664b0b7d611c78b3718 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 24 Nov 2026 23:37:24 -0800 Subject: [PATCH 19/29] Scripts: a hidden ScriptUI control takes no room, and a confirmed event waits behind queued ones A control whose visible is false, and everything in it, no longer adds to its container's size or pushes the next control along. An event sent with ui.dialog.confirm while the dialog still holds events the script has not taken goes after them, so handlers run in the order the events were given. --- crates/engine/src/script/scriptui.rs | 8 +++++++- crates/engine/src/tests/script_scriptui.rs | 15 +++++++++++++++ crates/ui-egui/src/dialogs/script_window.rs | 13 ++++++++++++- crates/ui-egui/src/tests/script_window.rs | 20 +++++++++++++++++++- docs/mcp.md | 6 ++++-- 5 files changed, 57 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 20c11a6239..3cc82001f6 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -566,6 +566,10 @@ fn layout(d: &mut ScriptUiDialog) { let [l, t, r, b] = node.margins; let (mut main, mut cross, mut count, mut reach) = (0.0f32, 0.0f32, 0usize, [0.0f32; 2]); for &k in &kids[i] { + // A hidden control, and everything in it, takes no room. + if !d.nodes[k].visible { + continue; + } if let Some(bounds) = d.nodes[k].bounds { reach = [reach[0].max(bounds.x + bounds.w), reach[1].max(bounds.y + bounds.h)]; continue; @@ -617,7 +621,9 @@ fn layout(d: &mut ScriptUiDialog) { let mut cursor = 0.0f32; for &k in &kids[i] { let kid = &d.nodes[k]; - let rect = if let Some(bounds) = kid.bounds { + let rect = if !kid.visible { + UiRect { x, y, w: 0.0, h: 0.0 } + } else if let Some(bounds) = kid.bounds { UiRect { x: node.rect.x + bounds.x, y: node.rect.y + bounds.y, w: bounds.w, h: bounds.h } } else { let [w, h] = size[k]; diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 82d17c6c86..1d3e333a99 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -346,6 +346,21 @@ fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); } +#[test] +fn a_hidden_control_and_what_it_holds_take_no_room() { + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let a = with(node("button", 0.0), "size", pair(100.0, 20.0)); + let hidden = with(node("group", 0.0), "visible", Data::Bool(false)); + let inside = with(node("button", 2.0), "size", pair(400.0, 300.0)); + let b = with(node("button", 0.0), "size", pair(50.0, 20.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog.clone(), a.clone(), hidden, inside, b.clone()])).unwrap(); + let shown: ScriptUiDialog = scriptui::parse(&description(vec![dialog, a, b])).unwrap(); + assert_eq!(d.size(), shown.size(), "the hidden group and the button in it leave the dialog's size as it is"); + assert_eq!(d.nodes[4].rect.x, shown.nodes[2].rect.x, "the next control takes the hidden group's place"); + assert!(!d.nodes[3].visible, "the button in the hidden group is hidden too"); +} + #[test] fn a_control_s_size_keeps_within_its_minimum_and_maximum() { let dialog = node("dialog", -1.0); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 06d1b94626..cdd273ec1f 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -669,7 +669,18 @@ fn give(app: &mut VectorcraftApp, w: &ScriptUiDialog, event: UiEvent) -> Result< pub(crate) fn confirm(app: &mut VectorcraftApp) -> Result { let Some(w) = app.session.script_window() else { return Err("no script dialog waits".into()) }; let event = with_window(app, |d| event_of(&w, d)).ok_or("no script dialog waits")??; - give(app, &w, event)?; + if with_window(app, |d| d.queue.is_empty()).unwrap_or(true) { + give(app, &w, event)?; + } else { + // Events the script has not had yet come first; this one, and the typed texts before a + // click or a close, go after them. + let mut events = vec![check_event(&w, event)?]; + if matches!(events[0], UiEvent::Click(_) | UiEvent::Close) { + with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; + } + let later: Vec = events.iter().filter_map(|e| queued(&w, e)).collect(); + with_window(app, |d| d.queue.extend(later)); + } with_window(app, |d| (d.event, d.control, d.value) = (None, None, None)); Ok(Value::Null) } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 389cd0e40d..6ad0512c5f 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -277,8 +277,8 @@ fn quitting_while_a_handler_runs_keeps_the_events_still_queued() { let mut app = app(); start(&mut app, &format!("{DRAW} {FORM} name.onChange = function () {{ name.text = name.text + '!'; }}; vc.log([w.show(), name.text]);")); assert!(until_window(&mut app)); - with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); give(&mut app, json!({"event": "change", "control": "name", "value": "Ann"})).unwrap(); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); crate::dialogs::script_run::ask_to_close(&mut app); assert!(is_open::(&app)); script_runs::poll(&mut app); @@ -535,6 +535,24 @@ fn queued_clicks_reach_their_buttons_after_a_handler_removes_a_control_before_th assert_eq!(log(&app), json!([[0, ["x", "y"]]]), "the click on the removed x is dropped and the click on y reaches y"); } +#[test] +fn a_click_from_ui_dialog_confirm_waits_behind_the_events_still_queued() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group'); var x = g.add('button', undefined, 'x'); var y = g.add('button', undefined, 'y'); \ + var hit = []; x.onClick = function () { hit.push('x'); }; y.onClick = function () { hit.push('y'); w.close(); }; \ + vc.log([w.show(), hit]);", + ); + assert!(until_window(&mut app)); + let ids: Vec = app.session.script_window().unwrap().nodes.iter().map(|n| n.id).collect(); + with_window(&app, |d| d.queue(&UiEvent::Click(2))).unwrap(); + give(&mut app, json!({"event": "click", "control": "y"})).unwrap(); + assert_eq!(queued(&app), vec![Queued::Click(ids[2]), Queued::Click(ids[3])], "the confirmed click goes after the queued one"); + run_to_end(&mut app); + assert_eq!(log(&app)[0][1], json!(["x", "y"]), "the handlers ran in the order the clicks were made"); +} + #[test] fn a_queued_list_change_is_dropped_after_a_handler_removes_an_item() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index e42ae7391a..37273ff099 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3021,7 +3021,8 @@ too, and a slider's minimum above its maximum. When a getter changes a list's it reads the dialog again, and throws an `Error` when a list changes again. It lays the controls out from each container's `orientation`, `alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its -container. Sizes and places are kept within 8,192 pixels. These limits are VectorCraft's own. +container. A control whose `visible` is false, and every control in it, takes no room in the layout. Sizes and places +are kept within 8,192 pixels. These limits are VectorCraft's own. In the app, the dialog (kind `scriptWindow`) draws the controls where they were laid out and has a Stop button, which ends the run as `script.stop` does. It stays open while one of its handlers runs and closes when `show()` @@ -3034,7 +3035,8 @@ dialog again with those events and the text typed in its fields. An event that w it was given to, and a typed text stays in its field, also after a handler adds controls before that one. `ui.dialog.set` with `event` (`click`, `change` or `close`), `control` (a control's index in the dialog, its name, or the text of a control without a name) and `value`, then `ui.dialog.confirm`, gives the script that event; a click or a close first gives the -script the text still typed in the dialog's fields. When one of those texts is longer than 16 KiB, the script gets +script the text still typed in the dialog's fields. When the dialog holds events the script has not taken yet, the +confirmed event goes after them. When one of those texts is longer than 16 KiB, the script gets no event and every field keeps its text: `ui.dialog.confirm`, `ui.dialog.cancel` and `ui.dialog.set` with `action` return an error, and Escape shows it in the status bar. Such a text stays in its field when the field loses the focus too, with the error in the status bar. A disabled or hidden control, a value out of a list's range, a From 7d408520de96d92327cd66af4a75fa56b9cdf607 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 04:33:29 -0800 Subject: [PATCH 20/29] Scripts: an arrow key or a typed letter in a ScriptUI list box gives the script the change The list box reports a row picked with the keys as a selection change rather than an activation, so the dialog took only clicks. It now gives the script both. --- crates/ui-egui/src/dialogs/script_window.rs | 12 +++-- crates/ui-egui/src/tests/script_window.rs | 50 +++++++++++++++++++++ 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index cdd273ec1f..dbc048947e 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -18,7 +18,7 @@ use std::collections::{BTreeMap, VecDeque}; -use craft::behavior::{Selection, keyed}; +use craft::behavior::{Selection, SelectionChange, keyed}; use craft::theme::Variant; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; @@ -462,10 +462,14 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n .max_rows(list_rows(n.rect.h)) .selection(Bind::given(selection)) .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); + // A click activates a row; the arrow keys and typed letters select one. for event in out.events { - if let CollectionEvent::Activate(k) = event - && n.selection != Some(k) - { + let picked = match event { + CollectionEvent::Activate(k) => Some(k), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(), + _ => None, + }; + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { shown.event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); } } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 6ad0512c5f..d4022737eb 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -695,6 +695,56 @@ fn a_title_a_handler_changes_and_a_list_box_reach_the_dialog() { assert!(!until_window(&mut app)); } +#[test] +fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['apple', 'pear', 'plum']); l.selection = 0; \ + var picked = []; l.onChange = function () { picked.push(l.selection.index); }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), picked]);", + ); + assert!(until_window(&mut app)); + let mut on_list = false; + for _ in 0..8 { + step(&mut app, vec![key(egui::Key::Tab)]); + let ctx = app.ui_ctx.clone().unwrap(); + ctx.enable_accesskit(); + let dialogs = app.dialogs().unwrap(); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); + out.textures_delta.clear(); + on_list = out.platform_output.accesskit_update.is_some_and(|u| { + u.nodes.iter().any(|(id, n)| *id == u.focus && matches!(n.role(), egui::accesskit::Role::ListBox | egui::accesskit::Role::ListItem)) + }); + if on_list { + break; + } + } + assert!(on_list, "Tab puts the focus on the list box"); + step(&mut app, vec![key(egui::Key::ArrowDown)]); + assert!(until_window(&mut app), "the change handler runs and the dialog waits again"); + step(&mut app, Vec::new()); + access_nodes(&app); + let nodes = access_nodes(&app); + let b = nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == egui::accesskit::Role::ListItem && n.label() == Some("plum")) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no plum row")); + // The top half of the row: the OK button below the list starts in the row's lower half. + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, b.y0 as f32 + 4.0); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + assert!(until_window(&mut app), "the change handler runs again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, [1, 2]]]), "the arrow key picked pear, the click picked plum, and the script was told each time"); +} + #[test] fn enter_with_the_focus_on_a_slider_clicks_the_default_button() { let mut app = app(); From 9dc197b4e4dc3d7b40bfbc3192289a2c371a1f25 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 14:41:28 -0800 Subject: [PATCH 21/29] Scripts: ScriptUI dialogs refuse look-alike containers, noecho fields and stale descriptions - An answer step with an empty control matches only an unnamed control whose text is empty, not the first unnamed control. - add() and add("item") on an object made to look like a container or list throw a TypeError and charge nothing to the dialog's limits. - A new list's initial items are read through ordinary property access, so an index getter gives its value. - findElement() keeps the controls it has still to look at rooted while a name getter runs, and skips a control the element no longer holds. - A close() that onClose calls before it returns false belongs to the close it refuses; the dialog waits for the next event. - show() throws for an edittext with noecho before the dialog opens. - show() reads the dialog again when a getter adds or removes a control after the controls were read, and throws when it changes again. - An edit field takes at most 32,768 characters while it is typed. --- crates/engine/src/script/scriptui.rs | 2 +- crates/engine/src/tests/script_scriptui.rs | 7 ++ crates/js/src/scriptui.rs | 115 +++++++++++++++----- crates/js/src/scriptui_tests.rs | 70 +++++++++++- crates/ui-egui/src/dialogs/script_window.rs | 8 +- crates/ui-egui/src/tests/script_window.rs | 22 ++++ docs/mcp.md | 8 +- 7 files changed, 200 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index 3cc82001f6..b4b4a95ccf 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -198,7 +198,7 @@ impl ScriptUiDialog { /// whose text is `control`. pub fn find(&self, control: &str) -> Option { let by = |name: bool| { - let hit = |n: &UiNode| if name { n.name == control } else { n.name.is_empty() && n.text == control }; + let hit = |n: &UiNode| if name { !control.is_empty() && n.name == control } else { n.name.is_empty() && n.text == control }; self.nodes.iter().enumerate().skip(1).find(|(_, n)| hit(n)).map(|(i, _)| i) }; by(true).or_else(|| by(false)) diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 1d3e333a99..48f4e492b3 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -131,6 +131,13 @@ fn a_step_names_a_control_by_its_text_only_when_it_has_no_name() { let go = "var w = new Window('dialog'); w.add('button', undefined, 'Go', {name: 'go'}); w.show();"; let e = headless(&mut s, go, window(json!([{"control": "Go", "event": "click"}]))).unwrap_err().to_string(); assert!(e.contains("the dialog has no control named Go"), "{e}"); + let help = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; w.show();"; + let e = headless(&mut s, help, window(json!([{"control": "", "event": "click"}]))).unwrap_err().to_string(); + assert!(e.contains("the dialog has no control named"), "an empty step names no control without a name: {e}"); + let blank = "var w = new Window('dialog'); w.add('button', undefined, 'Help').onClick = function () { vc.log('help'); }; \ + w.add('button', undefined, '').onClick = function () { vc.log('blank'); }; w.add('button', undefined, 'OK'); w.show();"; + headless(&mut s, blank, window(json!([{"control": "", "event": "click"}, {"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(s.script_report().unwrap()["log"], json!(["blank"]), "an empty step names the unnamed control whose text is empty"); } #[test] diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index febbcea099..6f45d87c7c 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -8,7 +8,8 @@ //! 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). -//! The other documented control types throw an `Error` that says they are not available yet. A +//! The other documented control types throw an `Error` that says they are not available yet, and +//! `show()` throws one for an `edittext` whose `properties` have `noecho`. A //! group takes its creation properties as the third argument (or the fourth when the third is not //! an object), and a list takes them there in place of its items, with the items in //! `properties.items`. A list's `add("item", text)` adds an item, `find(text)` finds one and @@ -52,8 +53,9 @@ //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] //! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a //! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These and [`MAX_LISTENERS`] are -//! VectorCraft's own limits. A getter that changes a list's items after the list was read makes -//! `show()` read the dialog again, and a list that changes again throws an `Error`. A `text` getter +//! VectorCraft's own limits. A getter that changes a list's items after the list was read, or adds +//! or removes a control after the dialog's controls were read, makes `show()` read the dialog +//! again, and a dialog that changes again throws an `Error`. A `text` getter //! that changes a list or a container while `remove(text)` looks for an item or a control makes //! `remove` throw an `Error`. @@ -557,10 +559,12 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if length > MAX_ITEMS.saturating_sub(number_slot(i, win, ITEM_COUNT)? as usize) { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); } - let values = list_values(i, a)?; - i.temp_roots.extend(values.iter().cloned()); - for item in &values { - let text = text_arg(i, item)?; + // Each item is read as a script reads it, so an index getter gives its value. + for n in 0..length { + let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; + let item = i.get_value(&Value::Object(a), &index_key(n))?; + i.temp_roots.push(item.clone()); + let text = text_arg(i, &item)?; new_item(i, c, text)?; staged += 1; } @@ -569,8 +573,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } } // A getter or a conversion above may have added controls or items itself, or removed the - // container from its dialog. - window_of(i, o, "add")?; + // container from its dialog. An object made to look like a container is not in the dialog, + // so it charges nothing to the dialog's controls. + window_in(i, o, "add")?; let count = number_slot(i, win, COUNT)?; if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); @@ -593,7 +598,7 @@ fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { // The conversion runs first: it may add or remove items itself. let text = text_arg(i, text)?; i.rooted(std::slice::from_ref(&text), |i| { - let win = window_of(i, o, "add")?; + let win = window_in(i, o, "add")?; let count = number_slot(i, win, ITEM_COUNT)?; if count as usize >= MAX_ITEMS { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); @@ -725,17 +730,50 @@ fn kids_of(i: &Interp, o: ObjId) -> JsResult> { fn find_element(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, _) = element(i, &this, "findElement")?; let want = i.to_str(&arg(args, 0))?; - let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); - while let Some(v) = stack.pop() { - i.use_fuel()?; - let Some(c) = v.as_object() else { continue }; - let name = i.get_value(&v, &key("name"))?; - if matches!(&name, Value::String(s) if *s == want) { - return Ok(v); + let mark = i.temp_roots.len(); + let r = (|| { + // The controls still to look at stay rooted while a `name` getter runs, and each one is + // looked at only while the element still holds it. + let mut stack: Vec = kids_of(i, o)?.into_iter().rev().collect(); + i.temp_roots.extend(stack.iter().cloned()); + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(c) = v.as_object() else { continue }; + if !holds(i, o, c)? { + continue; + } + let name = i.get_value(&v, &key("name"))?; + if !holds(i, o, c)? { + continue; + } + if matches!(&name, Value::String(s) if *s == want) { + return Ok(v); + } + let kids = kids_of(i, c)?; + i.temp_roots.extend(kids.iter().cloned()); + stack.extend(kids.into_iter().rev()); } - stack.extend(kids_of(i, c)?.into_iter().rev()); + Ok(Value::Null) + })(); + i.temp_roots.truncate(mark); + r +} + +/// Does the element `top` hold the control `c`: does each container from `c`'s up to `top` hold +/// the one below? +fn holds(i: &Interp, top: ObjId, c: ObjId) -> JsResult { + let mut at = c; + for _ in 0..=MAX_DEPTH { + let Some(p) = object_slot(i, at, PARENT)? else { return Ok(false) }; + if !kids_of(i, p)?.iter().any(|k| same(k, &Value::Object(at))) { + return Ok(false); + } + if p == top { + return Ok(true); + } + at = p; } - Ok(Value::Null) + Ok(false) } /// Calls the element's handler `name` when it has one. → its result, or `None` without one. @@ -1261,9 +1299,14 @@ fn finish(i: &mut Interp, win: ObjId, result: f64) -> JsResult { Ok(Value::Number(result)) } -/// Runs `onClose`. → false when it returned `false`. +/// Runs `onClose`. → false when it returned `false`. A `close()` that `onClose` calls belongs to +/// the close it decides on, so after `false` the dialog waits for the next event. fn may_close(i: &mut Interp, win: ObjId) -> JsResult { - Ok(!matches!(handler(i, win, "onClose")?, Some(Value::Bool(false)))) + let closes = !matches!(handler(i, win, "onClose")?, Some(Value::Bool(false))); + if !closes { + set_slot(i, win, CLOSING, Value::Undefined)?; + } + Ok(closes) } /// Closes the dialog when a handler asked to, or asks the host's `wait` what happens next. @@ -1480,8 +1523,9 @@ fn margins(i: &mut Interp, v: &Value) -> JsResult { /// The dialog's description: its elements in order, each after the container that holds it, as /// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of /// its default and cancel elements (-1 for none), and each element's array of list items as it -/// was described (`undefined` for an element that is not a list). When a getter changes a list -/// after it was read, the dialog is read again once; a list that changes again throws an `Error`. +/// was described (`undefined` for an element that is not a list). When a getter changes a list, +/// or adds or removes a control, after it was read, the dialog is read again once; a dialog that +/// changes again throws an `Error`. fn describe(i: &mut Interp, win: ObjId) -> JsResult { for _ in 0..2 { let mark = i.temp_roots.len(); @@ -1491,7 +1535,7 @@ fn describe(i: &mut Interp, win: ObjId) -> JsResult { return Ok(d); } } - Err(error(i, "show: a list's items changed while the dialog was read")) + Err(error(i, "show: a list's items or a container's controls changed while the dialog was read")) } /// A description, the elements in its order, the default and cancel elements, and the lists' items. @@ -1507,8 +1551,20 @@ fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value Ok(true) } +/// Has each element in `order` the array of controls it had when the dialog was read? +fn tree_unchanged(i: &Interp, order: &[(ObjId, String, f64)], tree: &[Value]) -> JsResult { + for ((o, ..), kept) in order.iter().zip(tree) { + let now = slot(i, *o, KIDS)?; + if !(same(&now, kept) || matches!((&now, kept), (Value::Undefined, Value::Undefined))) { + return Ok(false); + } + } + Ok(true) +} + fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let mut order: Vec<(ObjId, String, f64)> = Vec::new(); + let mut tree = Vec::new(); let mut seen = std::collections::HashSet::new(); let mut stack: Vec<(Value, f64, usize)> = vec![(Value::Object(win), -1.0, 0)]; while let Some((v, parent, depth)) = stack.pop() { @@ -1525,6 +1581,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { } let index = order.len() as f64; order.push((o, kind, parent)); + // Each container's array of controls as it is read; a change to it means a later getter + // added or removed a control. + let held = slot(i, o, KIDS)?; + i.temp_roots.push(held.clone()); + tree.push(held); for kid in kids_of(i, o)?.into_iter().rev() { stack.push((kid, index, depth + 1)); } @@ -1595,6 +1656,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { Value::Object(_) => (i.get_value(&props, &key("multiline"))?.truthy(), i.get_value(&props, &key("readonly"))?.truthy()), _ => (false, false), }; + // The dialog cannot hide what is typed, so a field meant to hide it is refused before it shows. + if props.as_object().is_some() && i.get_value(&props, &key("noecho"))?.truthy() { + return Err(error(i, "show: an edit field that hides its text (noecho) is not available yet")); + } d.push(("multiline".into(), Data::Bool(multiline))); d.push(("readonly".into(), Data::Bool(readonly))); } @@ -1634,7 +1699,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { }; let def = target(i, "defaultElement", "ok")?; let cancel = target(i, "cancelElement", "cancel")?; - if !lists_unchanged(i, &order, &snapshot)? { + if !lists_unchanged(i, &order, &snapshot)? || !tree_unchanged(i, &order, &tree)? { return Ok(None); } let desc = Data::Object(vec![ diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 263ae48f8f..eb80e515ab 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -340,7 +340,75 @@ fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() { let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ Object.defineProperty(b, 'text', {get: function () { l.removeAll(); l.add('item', 'B'); return 'OK'; }}); \ try { w.show(); } catch (e) { e.message }"; - assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items changed while the dialog was read".into())); + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_control_a_later_getter_removes_is_not_in_the_description() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var ok = w.add('button', undefined, 'OK'); var b = w.add('button', undefined, 'Go'); \ + var gone = false; Object.defineProperty(b, 'text', {get: function () { if (!gone) { gone = true; w.remove(ok); } return 'Go'; }}); \ + var went = 0; b.onClick = function () { went++; w.close(5); }; ok.onClick = function () { went = -1; }; [w.show(), went].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("5,1".into()), "the click at index 1 reaches Go, which the dialog still holds"); + let seen = seen.borrow(); + let first = nodes(&seen.descriptions[0]); + assert_eq!(first.len(), 2, "the removed OK button is not described"); + assert_eq!(field(&first[1], "text"), &Data::String("Go".into())); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); \ + Object.defineProperty(b, 'text', {get: function () { w.add('statictext', undefined, 'more'); return 'Go'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + +#[test] +fn a_list_s_initial_items_are_read_through_their_getters() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var a = ['x']; Object.defineProperty(a, 0, {get: function () { return 'A'; }}); \ + var w = new Window('dialog'); w.add('listbox', undefined, a); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + assert_eq!(field(&nodes(&seen.descriptions[0])[1], "items"), &Data::Array(vec![Data::String("A".into())])); +} + +#[test] +fn an_object_made_to_look_like_a_container_charges_nothing_to_the_dialog() { + let (mut r, _, _) = realm(Vec::new()); + let source = format!( + "var w = new Window('dialog'); var fake = {{__vcKind: 'group', __vcWindow: w, __vcDepth: 0, __vcKids: []}}; \ + fake.add = w.add; var e = ''; try {{ fake.add('button'); }} catch (x) {{ e = x.name; }} \ + var l = w.add('listbox'); var fl = {{__vcKind: 'listbox', __vcWindow: w, __vcItems: []}}; fl.add = l.add; \ + var f = ''; try {{ fl.add('item', 'A'); }} catch (x) {{ f = x.name; }} \ + for (var n = 1; n < {}; n++) w.add('statictext'); [e, f, w.children.length].join()", + scriptui::MAX_CONTROLS + ); + assert_eq!(r.run(&source).unwrap(), JsValue::String(format!("TypeError,TypeError,{}", scriptui::MAX_CONTROLS))); +} + +#[test] +fn find_element_skips_a_control_a_name_getter_removes() { + let (mut r, _, _) = realm(Vec::new()); + let source = "function heavy() { var junk = []; for (var k = 0; k < 50000; k++) junk.push({}); } \ + var w = new Window('dialog'); var a = w.add('button'); var b = w.add('button', undefined, 'B', {name: 'b'}); \ + Object.defineProperty(a, 'name', {get: function () { w.remove(b); b = null; heavy(); return 'a'; }}); \ + String(w.findElement('b'))"; + assert_eq!(r.run(source).unwrap(), JsValue::String("null".into())); +} + +#[test] +fn a_close_that_on_close_asks_for_is_part_of_the_close_it_refuses() { + let (mut r, _, _) = realm(vec![close(), click(1)]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var asked = 0; \ + w.onClose = function () { asked++; if (asked == 1) { w.close(7); return false; } }; [w.show(), asked].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("1,2".into()), "the refused close waits for the click on OK"); +} + +#[test] +fn an_edit_field_that_hides_its_text_is_refused_when_shown() { + let (mut r, seen, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); w.add('edittext', undefined, 'secret', {noecho: true}); try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: an edit field that hides its text (noecho) is not available yet".into())); + assert!(seen.borrow().descriptions.is_empty(), "the dialog never opens"); } #[test] diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index dbc048947e..3c12181935 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -35,7 +35,7 @@ use craft::ui::value_drag::Slider; use egui::Ui; use serde_json::{Value, json}; use vectorcraft_engine::script::dialogs::{cut_to, shown_text}; -use vectorcraft_engine::script::scriptui::{UiNode, check_event, list_index}; +use vectorcraft_engine::script::scriptui::{MAX_TEXT_BYTES, UiNode, check_event, list_index}; use vectorcraft_engine::script::{ScriptUiDialog, UiEvent, UiKind, UiValue}; use super::script_run::with_host; @@ -533,12 +533,16 @@ pub(crate) fn screen_reader_name(n: &UiNode, prompt: &str) -> String { } } +/// The most characters an edit field takes while it is typed: twice the longest text a script +/// accepts, so that a text that is too long can still be typed, refused and shortened. +pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; + /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. fn edit(ui: &mut Ui, drafts: &mut BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) - .limit(None) + .limit(DRAFT_CHARS) .id_salt((KIND, n.id)) .enabled(enabled) .read_only(n.readonly); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index d4022737eb..91c99a475a 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -413,6 +413,28 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t assert!(!until_window(&mut app)); } +#[test] +fn an_edit_field_takes_at_most_its_draft_limit_while_it_is_typed() { + let mut app = app(); + start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, ''); w.add('button', undefined, 'OK'); vc.log(w.show());"); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&app); + let nodes = access_nodes(&app); + let b = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput).and_then(egui::accesskit::Node::bounds); + let b = b.unwrap_or_else(|| panic!("no edit field")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + step(&mut app, vec![egui::Event::Paste("x".repeat(script_window::DRAFT_CHARS + 100))]); + let typed_now = typed(&app, 1).expect("the pasted text is kept while the field has the focus"); + assert_eq!(typed_now.chars().count(), script_window::DRAFT_CHARS, "the draft stops at its limit"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn a_queued_click_reaches_its_button_after_a_handler_adds_a_control_before_it() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 7a052cca10..33049dfe14 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3000,7 +3000,8 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values (VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an - unknown type throws too. + unknown type throws too. An `edittext` with `noecho` in its `properties` makes `show()` throw that a field that + hides its text is not available yet, before the dialog opens. - A list's `add("item", text)` adds an item, `find(text)` gives the first item with that text or `null`, `remove(what)` removes the item given by its index, the item itself or its text, `removeAll()` removes them all, `items` lists them and `selection` is the selected item or `null`; setting it to an item or an index selects it. @@ -3058,8 +3059,9 @@ nobody to ask, `alert`, `confirm` and `prompt` in a handler take their answers f `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws -too, and a slider's minimum above its maximum. When a getter changes a list's items after the list was read, it -reads the dialog again, and throws an `Error` when a list changes again. It lays the controls out from each container's `orientation`, +too, and a slider's minimum above its maximum. When a getter changes a list's items after the list was read, or +adds or removes a control after the controls were read, it reads the dialog again, and throws an `Error` when the +dialog changes again. It lays the controls out from each container's `orientation`, `alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its container. A control whose `visible` is false, and every control in it, takes no room in the layout. Sizes and places From 6aae27aa2e65ddb8d282e01e0f7c9d8f0b9d929d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:23:12 -0800 Subject: [PATCH 22/29] Scripts: screen readers read a ScriptUI group and the controls inside it A group is a node with the group role, named by the name the script gave it, and each control in a group or a panel is that container's child in the accessibility tree. --- crates/ui-egui/src/dialogs/script_window.rs | 49 ++++++++++++++++----- crates/ui-egui/src/tests/script_window.rs | 30 +++++++++++++ 2 files changed, 68 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 3c12181935..376dc5b338 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -309,12 +309,18 @@ impl StackDialog for ScriptWindow { let size = egui::vec2(width.max(1.0), height.max(1.0)); egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); + // Each container comes before the controls it holds. + let mut containers: Vec> = vec![None; window.nodes.len()]; for (i, n) in window.nodes.iter().enumerate().skip(1) { if !n.visible { continue; } - let place = Place { origin: area.min, enabled: waiting && n.enabled, default: window.default_element == Some(i) }; + let parent = containers.get(n.parent).copied().flatten(); + let place = Place { origin: area.min, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent }; let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i))); + if let Some(slot) = containers.get_mut(i) { + *slot = shown.container; + } typing |= shown.typing; events.extend(shown.event); } @@ -379,19 +385,22 @@ impl StackDialog for ScriptWindow { } } -/// Where a control is drawn: from `origin`, enabled or not, and whether it is the default button. +/// Where a control is drawn: from `origin`, enabled or not, whether it is the default button, and +/// the accessibility node of the group or panel that holds it. struct Place { origin: egui::Pos2, enabled: bool, default: bool, + parent: Option, } -/// What drawing a control gave: the event it gives, and whether an edit field has the keyboard -/// focus. +/// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, +/// and a group's or a panel's accessibility node. #[derive(Default)] struct Shown { event: Option, typing: bool, + container: Option, } /// The text of the visible static text just before control `i` in its container: the visible @@ -411,10 +420,17 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n let mut shown = Shown::default(); let enabled = place.enabled; let salt = (KIND, n.id); + // A control in a group or a panel is that container's child in the accessibility tree. + let builder = egui::UiBuilder::new().max_rect(rect); + let builder = match place.parent { + Some(parent) => builder.accessibility_parent(parent), + None => builder, + }; ui.push_id(n.id, |ui| { - ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| match n.kind { - UiKind::Dialog | UiKind::Group => {} - UiKind::Panel => panel(ui, rect, n, enabled), + ui.scope_builder(builder, |ui| match n.kind { + UiKind::Dialog => {} + UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)), + UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)), UiKind::StaticText => { Text::new(n.text.clone()).show(ui); } @@ -490,8 +506,8 @@ fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n } /// A panel's frame, with its text over the frame's top edge; screen readers read it as a group, -/// disabled when the panel is. -fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) { +/// disabled when the panel is. → the id of its node in the accessibility tree. +fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id { let frame = rect.shrink(1.0); let (enabled, name) = (enabled && ui.is_enabled(), n.text.clone()); let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); @@ -502,6 +518,17 @@ fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) { let color = visuals.text_color(); ui.painter().text(frame.min + egui::vec2(8.0, -6.0), egui::Align2::LEFT_TOP, &n.text, egui::FontId::proportional(11.0), color); } + r.id +} + +/// A group, which draws nothing; screen readers read it as a group called by the name the script +/// gave it, disabled when the group is. +/// → the id of its node in the accessibility tree. +fn group(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id { + let (enabled, name) = (enabled && ui.is_enabled(), n.name.clone()); + let r = ui.interact(rect, ui.scope_id().with("group"), egui::Sense::hover()); + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); + r.id } /// The name screen readers call a list box or a drop-down list `n` by: the visible static text @@ -557,13 +584,13 @@ fn edit(ui: &mut Ui, drafts: &mut BTreeMap, enabled: bool, (i, n, p let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); if committed && text != n.text && !n.readonly { drafts.remove(&n.id); - return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true }; + return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None }; } // A text the script refused stays in the field until the person changes it. if !focused && text == n.text { drafts.remove(&n.id); } - Shown { event: None, typing: focused || committed } + Shown { event: None, typing: focused || committed, container: None } } /// The event in the dialog's fields, for the dialog `w`. diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 91c99a475a..27e2f861f8 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -413,6 +413,36 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t assert!(!until_window(&mut app)); } +#[test] +fn screen_readers_read_a_group_by_its_name() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var g = w.add('group', undefined, {name: 'opts'}); g.add('checkbox', undefined, 'Bold'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&app); + let nodes = access_nodes(&app); + let group = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Group && n.label() == Some("opts")); + let (group, _) = group.unwrap_or_else(|| panic!("the group is in the accessibility tree")); + let bold = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::CheckBox && n.label() == Some("Bold")); + let (bold, _) = bold.unwrap_or_else(|| panic!("no Bold check box")); + let parent_of = |id: egui::accesskit::NodeId| nodes.iter().find(|(_, n)| n.children().contains(&id)).map(|(p, _)| *p); + let mut at = Some(*bold); + let mut inside = false; + for _ in 0..16 { + at = at.and_then(parent_of); + if at == Some(*group) { + inside = true; + break; + } + } + assert!(inside, "the check box is inside the group in the accessibility tree"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn an_edit_field_takes_at_most_its_draft_limit_while_it_is_typed() { let mut app = app(); From 5473a2217bb1ac0e50ad591f586eaea12fde14b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 15:44:37 -0800 Subject: [PATCH 23/29] Scripts: a ScriptUI dialog's OK and Cancel found by name or text skip buttons that cannot be clicked Without defaultElement or cancelElement, the dialog's default and cancel buttons are the first enabled and visible buttons named or titled OK and Cancel, so Enter and Escape click a button the dialog takes a click on. --- crates/js/src/scriptui.rs | 6 ++++-- crates/js/src/scriptui_tests.rs | 9 +++++++++ docs/mcp.md | 3 ++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 6f45d87c7c..52440bcdce 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -1611,9 +1611,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { ("name".into(), Data::String(name.clone())), ("text".into(), Data::String(text.clone())), ]; - names.push((kind.clone(), name, text)); let enabled = get(i, o, "enabled")?.truthy(); let visible = get(i, o, "visible")?.truthy(); + // Enter and Escape click a button found by its name or text only when it can be clicked. + let clickable = kind == "button" && enabled && visible; + names.push((clickable, name, text)); d.push(("enabled".into(), Data::Bool(enabled))); d.push(("visible".into(), Data::Bool(visible))); // A value a getter gives is kept from collection while its own properties are read. @@ -1694,7 +1696,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { if !matches!(given, Value::Undefined | Value::Null) { return Ok(-1.0); } - let button = |by_name: bool| names.iter().position(|(k, n, t)| k == "button" && (if by_name { n } else { t }).to_lowercase() == word); + let button = |by_name: bool| names.iter().position(|(c, n, t)| *c && (if by_name { n } else { t }).to_lowercase() == word); Ok(button(true).or_else(|| button(false)).map_or(-1.0, |n| n as f64)) }; let def = target(i, "defaultElement", "ok")?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index eb80e515ab..78b491b021 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -403,6 +403,15 @@ fn a_close_that_on_close_asks_for_is_part_of_the_close_it_refuses() { assert_eq!(r.run(source).unwrap(), JsValue::String("1,2".into()), "the refused close waits for the click on OK"); } +#[test] +fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK').enabled = false; w.add('button', undefined, 'OK').visible = false; \ + w.add('button', undefined, 'OK'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default"); +} + #[test] fn an_edit_field_that_hides_its_text_is_refused_when_shown() { let (mut r, seen, _) = realm(Vec::new()); diff --git a/docs/mcp.md b/docs/mcp.md index 33049dfe14..10be342154 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3052,7 +3052,8 @@ close box. The default or cancel button closes the dialog only when it has no `o its own and no `capture` handler on a container stopped the click; `click` handlers on the containers that do not capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the -cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside a handler, +cancel button is `cancelElement`, else a button named or titled Cancel, in any case; a button found by its name or +title counts only while it is enabled and visible. A `show()` inside a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. In the app, `alert`, `confirm`, `prompt` and the file dialogs called from a handler also throw an `Error`; in a run with nobody to ask, `alert`, `confirm` and `prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes. From 541c361e8c546d94a4e1a4016dd826f93559208a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:31:31 -0800 Subject: [PATCH 24/29] Scripts: ScriptUI dialogs draw with craft containers, and remove() changes nothing when it fails - The dialog's body only reports its events, typed texts and whether a field has the focus; the dialog applies the last run's report after the container, and Enter outside a field comes from take_submit after it. - The controls scroll in a craft Stack, and a panel is a GroupBox. - remove() on a container walks the removed control's subtree and checks the heap before its first change, so a run that ends in it leaves the container, the dialog's counts and the control as they were. - The dialog's accessibility tests draw through part_frame. --- crates/js/src/scriptui.rs | 84 ++++--- crates/js/src/scriptui_tests.rs | 29 +++ crates/ui-egui/src/dialogs/script_window.rs | 254 ++++++++++---------- crates/ui-egui/src/tests/script_window.rs | 55 ++--- 4 files changed, 239 insertions(+), 183 deletions(-) diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 52440bcdce..2ecc51a0b5 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -61,7 +61,7 @@ use crate::HostItem; 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::heap::{Class, ENUMERABLE, HIDDEN, NativeKind, OBJECT_BYTES, OPEN, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; use crate::host::Data; use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; use crate::value::{Value, index_key}; @@ -1104,14 +1104,15 @@ fn own_kids(i: &Interp, o: ObjId) -> JsResult> { Ok(own) } -/// The controls in `c` and in the containers it holds, `c` included, and their list items. -fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { - let (mut controls, mut items) = (0.0, 0.0); +/// The controls in `c` and in the containers it holds, `c` included, and the number of their list +/// items. +fn subtree(i: &mut Interp, c: &Value) -> JsResult<(Vec, f64)> { + let (mut controls, mut items) = (Vec::new(), 0.0); let mut stack = vec![c.clone()]; while let Some(v) = stack.pop() { i.use_fuel()?; let Some(o) = v.as_object() else { continue }; - controls += 1.0; + controls.push(o); items += items_of(i, o)?.len() as f64; stack.extend(own_kids(i, o)?); } @@ -1164,38 +1165,57 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult<()> { - let Some(root) = c.as_object() else { return Ok(()) }; - let mut stack = vec![c.clone()]; - while let Some(v) = stack.pop() { - i.use_fuel()?; - let Some(o) = v.as_object() else { continue }; - stack.extend(own_kids(i, o)?); - set_slot(i, o, WINDOW, Value::Null)?; - set_open(i, o, "window", Value::Null)?; +/// The writes that take the control `root`, removed from its container, out of the dialog: it has +/// no container, and neither it nor `controls`, the controls it holds, belong to the dialog any +/// longer, so their `window` is `null`. +fn detached(root: ObjId, controls: &[ObjId]) -> Vec<(ObjId, &'static str, Value, u8)> { + let mut writes = Vec::with_capacity(2 * controls.len() + 2); + for &o in controls { + writes.push((o, WINDOW, Value::Null, 0)); + writes.push((o, "window", Value::Null, OPEN)); } - set_slot(i, root, PARENT, Value::Null)?; - set_open(i, root, "parent", Value::Null) + writes.push((root, PARENT, Value::Null, 0)); + writes.push((root, "parent", Value::Null, OPEN)); + writes } fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 78b491b021..613775a975 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -665,6 +665,35 @@ fn a_removed_control_leaves_its_dialog() { ); } +#[test] +fn a_remove_that_runs_out_of_fuel_leaves_the_dialog_as_it_was() { + let (mut r, _, _) = realm(Vec::new()); + r.run("var w = new Window('dialog'); var g = w.add('group'); for (var n = 0; n < 300; n++) g.add('button');").unwrap(); + let mut failed = 0; + for fuel in 1..20_000 { + r.set_limits(Limits { fuel, ..Limits::default() }); + if r.run("w.remove(g);").is_ok() { + break; + } + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let state = r.run("[w.children.length, g.parent === w, g.window === w, g.children[299].window === w].join()").unwrap(); + // The run may end after remove returned, with the group already removed. + if state == JsValue::String("0,false,false,false".into()) { + break; + } + failed += 1; + assert_eq!(state, JsValue::String("1,true,true,true".into()), "a remove that ended at fuel {fuel} changed the dialog"); + } + assert!(failed > 300, "the runs ended inside remove's walk of the group ({failed})"); + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + let v = r + .run( + "var added = 0; try { while (true) { w.add('button'); added++; } } catch (e) {} [w.children.length, g.parent, g.window, added].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("512|||512".into()), "the removed group's controls are counted off the dialog once"); +} + #[test] fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 376dc5b338..36117c2a96 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -22,14 +22,15 @@ use craft::behavior::{Selection, SelectionChange, keyed}; use craft::theme::Variant; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::display::{Progress, Text}; +use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow}; use craft::ui::pickers::Select; use craft::ui::runtime::focus::Initial; use craft::ui::runtime::keys::take_submit; -use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::sections::{DialogRole, FooterButton, GroupBox}; use craft::ui::text::TextField; use craft::ui::value_drag::Slider; use egui::Ui; @@ -293,42 +294,56 @@ impl StackDialog for ScriptWindow { "" => tl!("Script Alert").to_string(), title => shown_text(title, false), }; - let mut events = Vec::new(); - let mut typing = false; - let mut submit = false; let buttons = [FooterButton::new(tl!("Stop"), DialogRole::Other).stays_open(true)]; let ScriptWindow { window, waiting, drafts, open, .. } = self; - let (window, waiting) = (&*window, *waiting); + let (window, waiting, drafts) = (&*window, *waiting, &*drafts); // The dialog opens with the focus on its default button, so Enter clicks it until the // person moves the focus into a field; without one that can be clicked, on its first control. let focus_default = window.default_element.and_then(|i| window.nodes.get(i)).is_some_and(|n| n.visible && n.enabled); let initial = if focus_default { Initial::Default } else { Initial::First }; let dialog = Dialog::new(heading).buttons(buttons).initial_focus(initial).opened(Bind::bound(open)); + // The body can run twice in a pass (measure, then paint), so it only reports what the + // person did; the dialog applies the last run's report after the container. let shown = dialog.show(ui, |ui, _| { let (width, height) = window.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); - egui::ScrollArea::both().max_width(MAX_SHOWN.x).max_height(MAX_SHOWN.y).auto_shrink([true, true]).show(ui, |ui| { - let (area, _) = ui.allocate_exact_size(size, egui::Sense::hover()); - // Each container comes before the controls it holds. - let mut containers: Vec> = vec![None; window.nodes.len()]; - for (i, n) in window.nodes.iter().enumerate().skip(1) { - if !n.visible { - continue; + let mut pass = Pass::default(); + ui.scope(|ui| { + ui.set_max_size(MAX_SHOWN); + Stack::new().scroll(Scroll::both()).show(ui, |ui, _| { + let origin = ui.cursor().min; + ui.set_min_size(size); + // Each container comes before the controls it holds. + let mut containers: Vec> = vec![None; window.nodes.len()]; + for (i, n) in window.nodes.iter().enumerate().skip(1) { + if !n.visible { + continue; + } + let parent = containers.get(n.parent).copied().flatten(); + let place = Place { origin, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent }; + let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i))); + if let Some(slot) = containers.get_mut(i) { + *slot = shown.container; + } + pass.typing |= shown.typing; + pass.events.extend(shown.event); + pass.drafts.extend(shown.draft.map(|d| (n.id, d))); } - let parent = containers.get(n.parent).copied().flatten(); - let place = Place { origin: area.min, enabled: waiting && n.enabled, default: window.default_element == Some(i), parent }; - let shown = control(ui, drafts, &place, (i, n, prompt_of(window, i))); - if let Some(slot) = containers.get_mut(i) { - *slot = shown.container; - } - typing |= shown.typing; - events.extend(shown.event); - } + }); }); - // An Enter the focused control left untaken (a slider, a check box) is the dialog's, - // unless a question is open over it. - submit = top && !typing && take_submit(ui.ctx()); + pass }); + let pass = shown.inner.unwrap_or_default(); + for (id, draft) in pass.drafts { + match draft { + Some(text) => self.drafts.insert(id, text), + None => self.drafts.remove(&id), + }; + } + let (mut events, typing) = (pass.events, pass.typing); + // An Enter the focused control left untaken (a slider, a check box, a button) is the + // dialog's, unless a question is open over it or a field has the focus. + let submit = top && !typing && take_submit(ui.ctx()); if shown.output.picked == Some(0) { self.stop = true; return None; @@ -342,8 +357,7 @@ impl StackDialog for ScriptWindow { } // Enter in a field belongs to the field; with the focus on any other control, it clicks the // default button. - let enter = submit || (top && ui.input(|i| i.key_pressed(egui::Key::Enter) && i.modifiers.is_none())); - if events.is_empty() && self.waiting && !typing && enter { + if events.is_empty() && self.waiting && submit { events.extend(self.window.default_element.map(UiEvent::Click)); } if !events.is_empty() { @@ -395,12 +409,23 @@ struct Place { } /// What drawing a control gave: the event it gives, whether an edit field has the keyboard focus, -/// and a group's or a panel's accessibility node. +/// a group's or a panel's accessibility node, and an edit field's typed text to keep (`Some`) or +/// forget (`None`). #[derive(Default)] struct Shown { event: Option, typing: bool, container: Option, + draft: Option>, +} + +/// What one run of the dialog's body gave: the events, whether an edit field has the keyboard +/// focus, and the typed texts to keep or forget, by field id. +#[derive(Default)] +struct Pass { + events: Vec, + typing: bool, + drafts: Vec<(u64, Option)>, } /// The text of the visible static text just before control `i` in its container: the visible @@ -415,110 +440,98 @@ pub(crate) fn prompt_of(w: &ScriptUiDialog, i: usize) -> &str { } /// Draws control `i` (`n`, with the prompt [`prompt_of`] gives) at its place. -fn control(ui: &mut Ui, drafts: &mut BTreeMap, place: &Place, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let rect = egui::Rect::from_min_size(place.origin + egui::vec2(n.rect.x, n.rect.y), egui::vec2(n.rect.w, n.rect.h)); let mut shown = Shown::default(); let enabled = place.enabled; let salt = (KIND, n.id); // A control in a group or a panel is that container's child in the accessibility tree. - let builder = egui::UiBuilder::new().max_rect(rect); + let builder = egui::UiBuilder::new().id_salt(n.id).max_rect(rect); let builder = match place.parent { Some(parent) => builder.accessibility_parent(parent), None => builder, }; - ui.push_id(n.id, |ui| { - ui.scope_builder(builder, |ui| match n.kind { - UiKind::Dialog => {} - UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)), - UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)), - UiKind::StaticText => { - Text::new(n.text.clone()).show(ui); + ui.scope_builder(builder, |ui| match n.kind { + UiKind::Dialog => {} + UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)), + UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)), + UiKind::StaticText => { + Text::new(n.text.clone()).show(ui); + } + UiKind::Button => { + let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled); + if place.default { + button = button.variant(Variant::PRIMARY).default_stop(); } - UiKind::Button => { - let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled); - if place.default { - button = button.variant(Variant::PRIMARY).default_stop(); - } - if clicked(&button.show(ui)) { - shown.event = Some(UiEvent::Click(i)); + if clicked(&button.show(ui)) { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::CheckBox => { + let out = Checkbox::new(Bind::given(n.checked)).label(n.text.clone()).id_salt(salt).enabled(enabled).show(ui); + if out.events.committed().is_some() { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::RadioButton => { + let mut picked = false; + let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show(ui, |ui, _| { + picked = clicked(&Radio::new(true).label(n.text.clone()).enabled(enabled).show(ui)); + }); + if picked || out.events.committed().is_some() { + shown.event = Some(UiEvent::Click(i)); + } + } + UiKind::EditText => shown = edit(ui, drafts, enabled, (i, n, prompt)), + UiKind::DropDownList => { + let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); + let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show(ui); + if let Some(k) = out.events.committed().copied().filter(|k| *k != n.selection) { + shown.event = Some(UiEvent::Change(i, UiValue::Index(k))); + } + } + UiKind::ListBox => { + let keys: Vec = (0..n.items.len()).collect(); + let source = keyed(&keys, |k: &usize| *k); + let selection = n.selection.map(Selection::single).unwrap_or_default(); + // Screen readers read the box as a list box, by its name or the static text before + // it, with the selected item as its value. + let out = List::::options(list_name(n, prompt)) + .id_salt(salt) + .enabled(enabled) + .max_rows(list_rows(n.rect.h)) + .selection(Bind::given(selection)) + .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); + // A click activates a row; the arrow keys and typed letters select one. + for event in out.events { + let picked = match event { + CollectionEvent::Activate(k) => Some(k), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(), + _ => None, + }; + if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { + shown.event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); } } - UiKind::CheckBox => { - let out = Checkbox::new(Bind::given(n.checked)).label(n.text.clone()).id_salt(salt).enabled(enabled).show(ui); - if out.events.committed().is_some() { - shown.event = Some(UiEvent::Click(i)); - } + } + UiKind::Slider => { + let out = Slider::new(Bind::given(n.value), n.min..=n.max).label(screen_reader_name(n, prompt)).id_salt(salt).enabled(enabled).show(ui); + if let Some(v) = out.events.committed().copied().filter(|v| *v != n.value) { + shown.event = Some(UiEvent::Change(i, UiValue::Number(v))); } - UiKind::RadioButton => { - let mut picked = false; - let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show(ui, |ui, _| { - picked = clicked(&Radio::new(true).label(n.text.clone()).enabled(enabled).show(ui)); - }); - if picked || out.events.committed().is_some() { - shown.event = Some(UiEvent::Click(i)); - } - } - UiKind::EditText => shown = edit(ui, drafts, enabled, (i, n, prompt)), - UiKind::DropDownList => { - let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); - let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show(ui); - if let Some(k) = out.events.committed().copied().filter(|k| *k != n.selection) { - shown.event = Some(UiEvent::Change(i, UiValue::Index(k))); - } - } - UiKind::ListBox => { - let keys: Vec = (0..n.items.len()).collect(); - let source = keyed(&keys, |k: &usize| *k); - let selection = n.selection.map(Selection::single).unwrap_or_default(); - // Screen readers read the box as a list box, by its name or the static text before - // it, with the selected item as its value. - let out = List::::options(list_name(n, prompt)) - .id_salt(salt) - .enabled(enabled) - .max_rows(list_rows(n.rect.h)) - .selection(Bind::given(selection)) - .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); - // A click activates a row; the arrow keys and typed letters select one. - for event in out.events { - let picked = match event { - CollectionEvent::Activate(k) => Some(k), - CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(), - _ => None, - }; - if let Some(k) = picked.filter(|k| n.selection != Some(*k)) { - shown.event = Some(UiEvent::Change(i, UiValue::Index(Some(k)))); - } - } - } - UiKind::Slider => { - let out = - Slider::new(Bind::given(n.value), n.min..=n.max).label(screen_reader_name(n, prompt)).id_salt(salt).enabled(enabled).show(ui); - if let Some(v) = out.events.committed().copied().filter(|v| *v != n.value) { - shown.event = Some(UiEvent::Change(i, UiValue::Number(v))); - } - } - UiKind::ProgressBar => { - Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show(ui); - } - }); + } + UiKind::ProgressBar => { + Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show(ui); + } }); shown } -/// A panel's frame, with its text over the frame's top edge; screen readers read it as a group, -/// disabled when the panel is. → the id of its node in the accessibility tree. +/// A panel: a group box titled by its text over the panel's place; screen readers read it as a +/// group, disabled when the panel is. → the id of its node in the accessibility tree. fn panel(ui: &mut Ui, rect: egui::Rect, n: &UiNode, enabled: bool) -> egui::Id { - let frame = rect.shrink(1.0); - let (enabled, name) = (enabled && ui.is_enabled(), n.text.clone()); - let r = ui.interact(rect, ui.scope_id().with("panel"), egui::Sense::hover()); - r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Group, enabled, &name)); - let visuals = ui.visuals(); - ui.painter().rect_stroke(frame, 4.0, visuals.widgets.noninteractive.bg_stroke, egui::StrokeKind::Inside); - if !n.text.is_empty() { - let color = visuals.text_color(); - ui.painter().text(frame.min + egui::vec2(8.0, -6.0), egui::Align2::LEFT_TOP, &n.text, egui::FontId::proportional(11.0), color); - } - r.id + let shown = GroupBox::new(n.text.clone(), None).id_salt((KIND, n.id)).enabled(enabled).show_at(ui, rect, |_, _| ()); + shown.output.response.id } /// A group, which draws nothing; screen readers read it as a group called by the name the script @@ -566,7 +579,7 @@ pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut Ui, drafts: &mut BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn edit(ui: &mut Ui, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) .limit(DRAFT_CHARS) @@ -578,19 +591,16 @@ fn edit(ui: &mut Ui, drafts: &mut BTreeMap, enabled: bool, (i, n, p } let out = field.show(ui); let focused = out.response.has_focus(); - if out.events.value().is_some() || text != n.text { - drafts.insert(n.id, text.clone()); - } + let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); if committed && text != n.text && !n.readonly { - drafts.remove(&n.id); - return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None }; + return Shown { event: Some(UiEvent::Change(i, UiValue::Text(text))), typing: true, container: None, draft: Some(None) }; } // A text the script refused stays in the field until the person changes it. if !focused && text == n.text { - drafts.remove(&n.id); + draft = Some(None); } - Shown { event: None, typing: focused || committed, container: None } + Shown { event: None, typing: focused || committed, container: None, draft } } /// The event in the dialog's fields, for the dialog `w`. diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 27e2f861f8..d61ec36cc2 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -365,15 +365,22 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_after_it_loses_the_focus() assert!(!until_window(&mut app)); } -/// One pass of the dialog host with accessibility on. → the nodes it reports. -fn access_nodes(app: &VectorcraftApp) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { +/// One pass of the dialog host with accessibility on, drawn as part of the window. → what the pass +/// gave. +fn access_frame(app: &mut VectorcraftApp) -> egui::FullOutput { let ctx = app.ui_ctx.clone().unwrap(); ctx.enable_accesskit(); - let dialogs = app.dialogs().unwrap(); let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); - out.platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() + crate::testing::part_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() }, |app, ui| { + if let Some(dialogs) = app.dialogs() { + dialogs.with(|host| host.run(ui)); + } + }) +} + +/// One pass of the dialog host with accessibility on. → the nodes it reports. +fn access_nodes(app: &mut VectorcraftApp) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + access_frame(app).platform_output.accesskit_update.map(|u| u.nodes).unwrap_or_default() } #[test] @@ -382,8 +389,8 @@ fn a_typed_text_the_script_refuses_stays_in_its_field_when_a_click_on_a_button_t start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, 'a'); w.add('button', undefined, 'OK'); vc.log(w.show());"); assert!(until_window(&mut app)); step(&mut app, Vec::new()); - access_nodes(&app); - let nodes = access_nodes(&app); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); let center = |found: Option<&egui::accesskit::Node>, what: &str| { let b = found.and_then(egui::accesskit::Node::bounds).unwrap_or_else(|| panic!("no {what}")); egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5) @@ -422,8 +429,8 @@ fn screen_readers_read_a_group_by_its_name() { ); assert!(until_window(&mut app)); step(&mut app, Vec::new()); - access_nodes(&app); - let nodes = access_nodes(&app); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); let group = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::Group && n.label() == Some("opts")); let (group, _) = group.unwrap_or_else(|| panic!("the group is in the accessibility tree")); let bold = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::CheckBox && n.label() == Some("Bold")); @@ -449,8 +456,8 @@ fn an_edit_field_takes_at_most_its_draft_limit_while_it_is_typed() { start(&mut app, "var w = new Window('dialog'); w.add('edittext', undefined, ''); w.add('button', undefined, 'OK'); vc.log(w.show());"); assert!(until_window(&mut app)); step(&mut app, Vec::new()); - access_nodes(&app); - let nodes = access_nodes(&app); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); let b = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::TextInput).and_then(egui::accesskit::Node::bounds); let b = b.unwrap_or_else(|| panic!("no edit field")); let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); @@ -735,8 +742,8 @@ fn a_title_a_handler_changes_and_a_list_box_reach_the_dialog() { give(&mut app, json!({"event": "click", "control": "Rename"})).unwrap(); assert!(until_window(&mut app)); assert_eq!(title(&app), "Renamed", "the heading follows the handler's title"); - access_nodes(&app); - let nodes = access_nodes(&app); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); let list = nodes.iter().any(|(_, n)| n.role() == egui::accesskit::Role::ListBox && n.label() == Some("Fruit:")); assert!(list, "screen readers read the list box by its prompt"); let pear = nodes.iter().any(|(_, n)| n.label() == Some("pear") && n.is_selected() == Some(true)); @@ -760,12 +767,7 @@ fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { let mut on_list = false; for _ in 0..8 { step(&mut app, vec![key(egui::Key::Tab)]); - let ctx = app.ui_ctx.clone().unwrap(); - ctx.enable_accesskit(); - let dialogs = app.dialogs().unwrap(); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); + let out = access_frame(&mut app); on_list = out.platform_output.accesskit_update.is_some_and(|u| { u.nodes.iter().any(|(id, n)| *id == u.focus && matches!(n.role(), egui::accesskit::Role::ListBox | egui::accesskit::Role::ListItem)) }); @@ -777,8 +779,8 @@ fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { step(&mut app, vec![key(egui::Key::ArrowDown)]); assert!(until_window(&mut app), "the change handler runs and the dialog waits again"); step(&mut app, Vec::new()); - access_nodes(&app); - let nodes = access_nodes(&app); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); let b = nodes .iter() .map(|(_, n)| n) @@ -805,12 +807,7 @@ fn enter_with_the_focus_on_a_slider_clicks_the_default_button() { let mut on_slider = false; for _ in 0..8 { step(&mut app, vec![key(egui::Key::Tab)]); - let ctx = app.ui_ctx.clone().unwrap(); - ctx.enable_accesskit(); - let dialogs = app.dialogs().unwrap(); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 800.0))); - let mut out = ctx.run_ui(egui::RawInput { screen_rect, ..Default::default() }, |ui| dialogs.with(|host| host.run(ui))); - out.textures_delta.clear(); + let out = access_frame(&mut app); on_slider = out .platform_output .accesskit_update @@ -846,7 +843,7 @@ fn stop_ends_the_run() { start(&mut app, &format!("{DRAW} {FORM} w.show();")); assert!(until_window(&mut app)); step(&mut app, Vec::new()); - let nodes = access_nodes(&app); + let nodes = access_nodes(&mut app); let stop = nodes.iter().map(|(_, n)| n).find(|n| n.role() == egui::accesskit::Role::Button && n.label() == Some("Stop")); let b = stop.and_then(egui::accesskit::Node::bounds).expect("a Stop button"); let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); From 5654c06c6d8105336734ed6dd31bd82c231d44e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:18:53 -0800 Subject: [PATCH 25/29] Scripts: ScriptUI review fixes for resource strings, list choices, listeners and the dialog's cancel and close A resource string's characters size edit fields and static text, a list's items must be an array, a listener added again runs in a later dispatch only, a close asked for while the dialog is described closes it, a list selection a getter changes is read again, and Escape during a handler cancels the dialog the run waits at next. The thrown error of a failed host call stays kept while the failure callback runs. --- crates/engine/src/script/scriptui.rs | 14 ++- crates/engine/src/tests/script_scriptui.rs | 16 +++ crates/js/src/interp.rs | 6 +- crates/js/src/scriptui.rs | 130 ++++++++++++++++---- crates/js/src/scriptui_resource.rs | 15 ++- crates/js/src/scriptui_tests.rs | 57 +++++++++ crates/ui-egui/src/dialogs/script_window.rs | 42 +++++-- crates/ui-egui/src/tests/script_window.rs | 55 +++++++++ docs/target-app-parity.md | 2 +- 9 files changed, 296 insertions(+), 41 deletions(-) diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index b4b4a95ccf..b578bdb0b7 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -152,6 +152,8 @@ pub struct UiNode { min_size: [Option; 2], max_size: [Option; 2], bounds: Option, + /// The characters an edit field or static text reserves room for in its width. + characters: Option, } impl UiNode { @@ -522,6 +524,8 @@ pub fn parse(d: &Data) -> Result { min_size, max_size, bounds, + // At most as many characters as the longest text holds. + characters: number(field(f, "characters")).filter(|c| *c > 0.0).map(|c| (c as f32).min(MAX_TEXT_BYTES as f32)), }); } let target = |name: &str| number(field(top, name)).map(|k| k as usize).filter(|k| nodes.get(*k).is_some_and(|n| n.kind == UiKind::Button)); @@ -537,12 +541,16 @@ fn own_size(n: &UiNode) -> [f32; 2] { let widest = |lines: &mut dyn Iterator| lines.map(chars).fold(0.0, f32::max); let lines = |s: &str| s.lines().count().max(1) as f32; let longest_item = n.items.iter().map(|t| chars(t)).fold(0.0, f32::max); + // `characters` reserves room for that many characters, however long the text is now. + let reserved = n.characters.unwrap_or(0.0); match n.kind { - UiKind::StaticText => [widest(&mut n.text.lines()) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], + UiKind::StaticText => [widest(&mut n.text.lines()).max(reserved) * CHAR + 4.0, lines(&n.text) * LINE + 4.0], UiKind::Button => [(chars(&n.text) * CHAR + 24.0).max(80.0), 24.0], UiKind::CheckBox | UiKind::RadioButton => [chars(&n.text) * CHAR + 24.0, 20.0], - UiKind::EditText if n.multiline => [(widest(&mut n.text.lines()) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0], - UiKind::EditText => [(chars(&n.text) * CHAR + 12.0).max(80.0), 24.0], + UiKind::EditText if n.multiline => { + [(widest(&mut n.text.lines()).max(reserved) * CHAR + 12.0).max(160.0), lines(&n.text).max(3.0) * LINE + 10.0] + } + UiKind::EditText => [(chars(&n.text).max(reserved) * CHAR + 12.0).max(80.0), 24.0], UiKind::DropDownList => [(longest_item * CHAR + 40.0).max(100.0), 24.0], UiKind::ListBox => [(longest_item * CHAR + 24.0).max(120.0), (n.items.len() as f32).clamp(3.0, 10.0) * 18.0 + 6.0], UiKind::Slider => [160.0, 20.0], diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 82cfff63d8..01cef50a55 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -366,6 +366,22 @@ fn sizes_and_places_are_clamped_and_the_layout_follows_the_containers() { assert!(w <= MAX_EXTENT && h <= MAX_EXTENT); } +#[test] +fn characters_reserve_the_width_of_an_edit_field_or_a_static_text() { + let pair = |w: f64, h: f64| Data::Array(vec![Data::Number(w), Data::Number(h)]); + let text = |kind: &str, t: &str| with(node(kind, 0.0), "text", Data::String(t.into())); + let field = with(text("edittext", "Sample"), "characters", Data::Number(35.0)); + let plain = text("edittext", "Sample"); + let label = with(text("statictext", "Hi"), "characters", Data::Number(10.0)); + let sized = with(with(text("edittext", "Sample"), "characters", Data::Number(35.0)), "size", pair(100.0, 20.0)); + let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); + let d: ScriptUiDialog = scriptui::parse(&description(vec![dialog, field, plain, label, sized])).unwrap(); + assert_eq!(d.nodes[1].rect.w, 35.0 * 7.0 + 12.0, "35 characters of room"); + assert_eq!(d.nodes[2].rect.w, 80.0, "without characters, the text's own width and the 80 minimum"); + assert_eq!(d.nodes[3].rect.w, 10.0 * 7.0 + 4.0); + assert_eq!(d.nodes[4].rect.w, 100.0, "a size set takes the place of the characters' width"); +} + #[test] fn a_hidden_control_and_what_it_holds_take_no_room() { let dialog = with(node("dialog", -1.0), "orientation", Data::String("row".into())); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 30ee64ef4c..4b9a34e3df 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -3228,9 +3228,13 @@ impl Interp { Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &Value::Undefined, &args, &read), _ => self.call(&host, &Value::Undefined, &args), }; - if answer.is_err() + if let Err(e) = &answer && let Some(failed) = failed { + // The thrown value stays kept from collection while `failed` runs. + if let Abrupt::Throw(v) = e { + self.temp_roots.push(v.clone()); + } failed(self, &keep); } self.temp_roots.truncate(mark); diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 9c45aa6f13..7ad0e41c20 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -107,12 +107,14 @@ const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; const ID: &str = "__vcId"; +/// The number of listeners an element has had registered, which numbers each registration. +const REGISTERED: &str = "__vcRegistered"; /// The longest array an element keeps in a slot: a list's items, a container's controls, its -/// listeners (three values each), and the elements of a description. +/// listeners (four values each), and the elements of a description. const LIST_CAP: u32 = { let most = if MAX_ITEMS > MAX_CONTROLS + 1 { MAX_ITEMS } else { MAX_CONTROLS + 1 }; - let most = if most > 3 * MAX_LISTENERS { most } else { 3 * MAX_LISTENERS }; + let most = if most > 4 * MAX_LISTENERS { most } else { 4 * MAX_LISTENERS }; most as u32 }; @@ -527,6 +529,11 @@ fn add_resource(i: &mut Interp, parent: ObjId, spec: &Spec) -> JsResult { // 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") { + // Only an array is item texts; `add` would read an object third as creation properties. + Some((_, Res::Null)) if list_kind => Value::Undefined, + Some((_, v)) if list_kind && !matches!(v, Res::Array(_)) => { + return Err(i.type_error("items: give a list's items as an array")); + } Some((_, v)) if list_kind => { let v = resource_value(i, v)?; i.temp_roots.push(v.clone()); @@ -688,14 +695,16 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); } // Each item is read as a script reads it, so an index getter gives its value. + let mut texts = Vec::with_capacity(length); for n in 0..length { let n = u32::try_from(n).map_err(|_| Abrupt::Internal("a list is too long".into()))?; let item = i.get_value(&Value::Object(a), &index_key(n))?; i.temp_roots.push(item.clone()); let text = text_arg(i, &item)?; - new_item(i, c, text)?; - staged += 1; + i.temp_roots.push(text.clone()); + texts.push(text); } + staged = new_items(i, c, &texts)?; } _ => return Err(i.type_error("add: give a list's items as an array")), } @@ -752,6 +761,32 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { }) } +/// Gives the new list `o`, which has no items yet, an item for each of `texts`, building its +/// arrays of items once, without counting them in the dialog's items. → how many were added. +fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { + let proto = classes(i)?.item_proto; + let mark = i.temp_roots.len(); + let r = (|| { + let mut items = Vec::with_capacity(texts.len()); + for text in texts { + i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; + let item = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + i.temp_roots.push(Value::Object(item)); + set_slot(i, item, LIST, Value::Object(o))?; + set_open(i, item, "text", text.clone())?; + items.push(Value::Object(item)); + } + let kept = list(i, &items, false)?; + i.temp_roots.push(Value::Object(kept)); + set_slot(i, o, ITEMS, Value::Object(kept))?; + let copy = list(i, &items, true)?; + set_open(i, o, "items", Value::Object(copy))?; + Ok(items.len()) + })(); + i.temp_roots.truncate(mark); + r +} + fn list_of(i: &mut Interp, this: &Value, what: &str) -> JsResult { match kind_of(i, this)? { Some((o, kind)) if kind == "dropdownlist" || kind == "listbox" => Ok(o), @@ -957,17 +992,26 @@ fn radio_set(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult> { +/// A listener registered on an element: its event type, handler, capture flag and registration +/// number. +type Listener = (Value, Value, bool, f64); + +/// The listeners registered on `o`, in the order they were added. +fn listeners_of(i: &Interp, o: ObjId) -> JsResult> { let flat = match object_slot(i, o, LISTENERS)? { Some(a) => list_values(i, a)?, None => Vec::new(), }; - Ok(flat.as_chunks::<3>().0.iter().map(|[t, f, c]| (t.clone(), f.clone(), c.truthy())).collect()) + Ok(flat + .as_chunks::<4>() + .0 + .iter() + .map(|[t, f, c, n]| (t.clone(), f.clone(), c.truthy(), if let Value::Number(n) = n { *n } else { 0.0 })) + .collect()) } -fn set_listeners(i: &mut Interp, o: ObjId, all: &[(Value, Value, bool)]) -> JsResult<()> { - let flat: Vec = all.iter().flat_map(|(t, f, c)| [t.clone(), f.clone(), Value::Bool(*c)]).collect(); +fn set_listeners(i: &mut Interp, o: ObjId, all: &[Listener]) -> JsResult<()> { + let flat: Vec = all.iter().flat_map(|(t, f, c, n)| [t.clone(), f.clone(), Value::Bool(*c), Value::Number(*n)]).collect(); i.rooted(&flat.clone(), |i| { let kept = list(i, &flat, false)?; set_slot(i, o, LISTENERS, Value::Object(kept)) @@ -1004,11 +1048,15 @@ fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J } let capture = arg(args, 2).truthy(); let mut all = listeners_of(i, o)?; - if !all.iter().any(|(t, g, c)| is_type(t, ty) && same(g, &f) && *c == capture) { + if !all.iter().any(|(t, g, c, _)| is_type(t, ty) && same(g, &f) && *c == capture) { if all.len() >= MAX_LISTENERS { return Err(range(i, &format!("addEventListener: a window or control takes at most {MAX_LISTENERS} listeners"))); } - all.push((Value::str(ty), f, capture)); + // A listener removed and added again is a new registration, which an event already + // running does not reach. + let n = number_slot(i, o, REGISTERED)? + 1.0; + set_slot(i, o, REGISTERED, Value::Number(n))?; + all.push((Value::str(ty), f, capture, n)); set_listeners(i, o, &all)?; } Ok(Value::Undefined) @@ -1022,7 +1070,7 @@ fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) - let capture = arg(args, 2).truthy(); let mut all = listeners_of(i, o)?; let before = all.len(); - all.retain(|(t, g, c)| !(is_type(t, ty) && same(g, &f) && *c == capture)); + all.retain(|(t, g, c, _)| !(is_type(t, ty) && same(g, &f) && *c == capture)); if all.len() != before { set_listeners(i, o, &all)?; } @@ -1041,13 +1089,14 @@ fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult, event: ObjId, phase: f64) -> JsResult { - let wanted = |i: &Interp| -> JsResult> { + let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() - .filter(|(t, _, c)| is_type(t, ty) && capture.is_none_or(|want| *c == want)) - .map(|(_, f, c)| (f, c)) + .filter(|(t, _, c, _)| is_type(t, ty) && capture.is_none_or(|want| *c == want)) + .map(|(_, f, _, n)| (f, n)) .collect()) }; let first = wanted(i)?; @@ -1058,8 +1107,8 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve i.rooted(&functions, |i| { set_open(i, event, "currentTarget", Value::Object(at))?; set_open(i, event, "eventPhase", Value::Number(phase))?; - for (f, c) in &first { - if !wanted(i)?.iter().any(|(g, d)| same(g, f) && d == c) { + for (f, n) in &first { + if !wanted(i)?.iter().any(|(_, m)| m == n) { continue; } i.call(f, &Value::Object(at), &[Value::Object(event)])?; @@ -1416,7 +1465,13 @@ fn show(i: &mut Interp, this: Value, _: &[Value]) -> JsResult { return Err(e); } }; - let open = host_fn(i, "open")?; + let open = match host_fn(i, "open") { + Ok(open) => open, + Err(e) => { + set_showing(i, None); + return Err(e); + } + }; Ok(Pause { host: open, args: vec![desc], @@ -1469,6 +1524,10 @@ fn next(i: &mut Interp, win: ObjId) -> JsResult { continue; } let (desc, nodes, def, cancel, lists) = describe(i, win)?; + // A getter that `describe` ran may have closed the dialog. + if matches!(slot(i, win, CLOSING)?, Value::Number(_)) { + continue; + } let wait = host_fn(i, "wait")?; i.again = Some(Pause { host: wait, @@ -1484,8 +1543,16 @@ fn next(i: &mut Interp, win: ObjId) -> JsResult { /// Runs `r`; when it fails, the dialog is no longer showing. fn guarded(i: &mut Interp, keep: &[Value], r: impl FnOnce(&mut Interp) -> JsResult) -> JsResult { let v = r(i); - if v.is_err() { + if let Err(e) = &v { + // The thrown value stays kept from collection while `failed` runs. + let thrown = match e { + Abrupt::Throw(t) => vec![t.clone()], + _ => Vec::new(), + }; + let mark = i.temp_roots.len(); + i.temp_roots.extend(thrown); failed(i, keep); + i.temp_roots.truncate(mark); } v } @@ -1689,10 +1756,10 @@ fn describe(i: &mut Interp, win: ObjId) -> JsResult { /// A description, the elements in its order, the default and cancel elements, and the lists' items. type Described = (Value, ObjId, f64, f64, ObjId); -/// Has each list in `order` the array of items it had when it was described? -fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value]) -> JsResult { - for ((o, ..), kept) in order.iter().zip(snapshot) { - if !matches!(kept, Value::Undefined) && !same(&slot(i, *o, ITEMS)?, kept) { +/// Has each list in `order` the array of items and the selection it had when it was described? +fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value], selections: &[f64]) -> JsResult { + for (((o, ..), kept), sel) in order.iter().zip(snapshot).zip(selections) { + if !matches!(kept, Value::Undefined) && (!same(&slot(i, *o, ITEMS)?, kept) || number_slot(i, *o, SELECTION)? != *sel) { return Ok(false); } } @@ -1745,9 +1812,12 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let mut items_total = 0usize; // Each list's array of items as it is read; a change to it means a later getter changed the list. let mut snapshot = Vec::with_capacity(order.len()); + // Each list's selection as it is read; a later getter may change it. + let mut selections = Vec::with_capacity(order.len()); for (o, kind, parent) in &order { let o = *o; let mut listed = Value::Undefined; + let mut selected = -1.0; let name_v = get(i, o, "name")?; let name = text_of(i, &name_v, "a control's name")?; let text_v = get(i, o, "text")?; @@ -1781,6 +1851,13 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { } let a = get_kept(i, o, "alignment")?; d.push(("alignment".into(), alignment(i, &a)?)); + // The characters a text field or static text reserves room for in its width. + if matches!(kind.as_str(), "edittext" | "statictext") { + let n = get(i, o, "characters")?; + if !matches!(n, Value::Undefined | Value::Null) { + d.push(("characters".into(), Data::Number(number_arg(i, &n, "show: a control's characters")?))); + } + } if matches!(kind.as_str(), "dialog" | "group" | "panel") { let orientation = get(i, o, "orientation")?; d.push(("orientation".into(), Data::String(text_of(i, &orientation, "an orientation")?.to_lowercase()))); @@ -1828,6 +1905,8 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { texts.push(Data::String(text_of(i, &t, "a list item's text")?)); } d.push(("items".into(), Data::Array(texts))); + // The item texts' getters ran above, so the selection is read after them. + selected = number_slot(i, o, SELECTION)?; let sel = selection_index(i, o)?.filter(|n| *n < items.len()); d.push(("selection".into(), sel.map_or(Data::Null, |n| Data::Number(n as f64)))); } @@ -1835,6 +1914,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { } nodes.push(Data::Object(d)); snapshot.push(listed); + selections.push(selected); } let target = |i: &mut Interp, name: &str, word: &str| -> JsResult { let given = get(i, win, name)?; @@ -1849,7 +1929,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { }; let def = target(i, "defaultElement", "ok")?; let cancel = target(i, "cancelElement", "cancel")?; - if !lists_unchanged(i, &order, &snapshot)? || !tree_unchanged(i, &order, &tree)? { + if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? { return Ok(None); } let desc = Data::Object(vec![ diff --git a/crates/js/src/scriptui_resource.rs b/crates/js/src/scriptui_resource.rs index 8789777518..118d4c74ad 100644 --- a/crates/js/src/scriptui_resource.rs +++ b/crates/js/src/scriptui_resource.rs @@ -101,7 +101,7 @@ impl Reader { 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")), + None => Fault::Syntax(format!("expected {what} at character {}, the end of the resource specification", self.at + 1)), } } @@ -251,7 +251,9 @@ impl Reader { '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) { + // `from_str_radix` also takes a sign, which an escape does not have. + let valid = hex.len() == digits && hex.chars().all(|c| c.is_ascii_hexdigit()); + match u32::from_str_radix(&hex, 16).ok().filter(|_| valid).and_then(char::from_u32) { Some(c) => { s.push(c); self.at += digits; @@ -318,10 +320,19 @@ mod tests { "dialog { a: [Button {}] }", "dialog { v: orange }", "dialog { t: '\\u12' }", + "dialog { t: '\\x+A' }", + "dialog { t: '\\u+00A' }", "{ }", ] { assert!(matches!(parse(text), Err(Fault::Syntax(_))), "{text}: {:?}", parse(text)); } + assert_eq!(parse("dialog { t: '\\x0A\\u0041' }"), Ok(spec("dialog", vec![("t", Res::String("\nA".into()))]))); + } + + #[test] + fn a_resource_specification_that_ends_early_says_at_which_character() { + assert_eq!(parse("dialog {"), Err(Fault::Syntax("expected a name at character 9, the end of the resource specification".into()))); + assert_eq!(parse("dialog"), Err(Fault::Syntax("expected { after the type at character 7, the end of the resource specification".into()))); } #[test] diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 0a7779b280..98bab84b8b 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -306,6 +306,23 @@ fn a_resource_list_s_items_are_the_items_the_dialog_shows() { 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"); + let object = r + .run("try { new Window(\"dialog { l: ListBox { items: {}, properties: {name: 'choices'} } }\"); 'made' } catch (e) { e.name + ': ' + e.message }") + .unwrap(); + assert_eq!(object, JsValue::String("TypeError: items: give a list's items as an array".into()), "an object is not item texts"); + let none = r + .run("var n = new Window(\"dialog { l: ListBox { items: null, properties: {name: 'choices'} } }\"); [n.l.items.length, n.l.name].join()") + .unwrap(); + assert_eq!(none, JsValue::String("0,choices".into())); +} + +#[test] +fn an_edit_field_s_and_a_static_text_s_characters_reach_the_description() { + let (mut r, seen, _) = realm(vec![close()]); + r.run("var w = new Window(\"dialog { e: EditText { text: 'Sample', characters: 35 }, s: StaticText { text: 'Hi' } }\"); w.show()").unwrap(); + let first = nodes(&seen.borrow().descriptions[0]); + assert_eq!(field(&first[1], "characters"), &Data::Number(35.0)); + assert_eq!(field(&first[2], "characters"), &Data::Undefined, "a control without characters gives none"); } #[test] @@ -352,6 +369,9 @@ fn a_resource_specification_keeps_to_the_dialog_limits() { )) .unwrap(); assert_eq!(added, JsValue::String(format!("RangeError,{}", scriptui::MAX_CONTROLS - 1)), "the group took a place before its second button"); + let kept = + r.run("var g = w.children[w.children.length - 1]; [g.type, g.children.length, g.a === g.children[0], g.b === undefined].join()").unwrap(); + assert_eq!(kept, JsValue::String("group,1,true,true".into()), "the first button stays in the group"); let nested = |depth: usize| { format!( "var s = ''; for (var d = 0; d < {depth}; d++) s += 'g: Group {{ '; for (d = 0; d < {depth}; d++) s += '}} '; \ @@ -848,6 +868,43 @@ fn a_listener_removed_by_an_earlier_one_in_the_same_event_does_not_run() { assert_eq!(v, JsValue::String("1".into())); } +#[test] +fn a_listener_removed_and_added_again_in_the_same_event_does_not_run_in_it() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var ran = []; var once = true; function second() { ran.push(2); } \ + b.addEventListener('click', function () { ran.push(1); if (once) { once = false; b.removeEventListener('click', second); b.addEventListener('click', second); } }); \ + b.addEventListener('click', second); b.notify('onClick'); b.notify('onClick'); ran.join(',')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,1,2".into()), "the second registration runs from the next event on"); +} + +#[test] +fn a_close_a_getter_asks_for_while_the_dialog_is_read_again_ends_show() { + let (mut r, seen, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); var b = w.add('button', undefined, 'Go'); var armed = false; \ + b.onClick = function () { armed = true; }; \ + Object.defineProperty(b, 'text', {get: function () { if (armed) { armed = false; w.close(7); } return 'Go'; }}); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(7.0)); + assert_eq!(seen.borrow().ends, vec![(7.0, true)]); +} + +#[test] +fn a_selection_a_later_getter_changes_is_described_as_it_is() { + let (mut r, seen, _) = realm(vec![click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A', 'B']); var b = w.add('button', undefined, 'OK'); \ + var moved = false; Object.defineProperty(b, 'text', {get: function () { if (!moved) { moved = true; l.selection = 1; } return 'OK'; }}); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(1.0)); + assert_eq!(field(&nodes(&seen.borrow().descriptions[0])[1], "selection"), &Data::Number(1.0), "the description shows the selection as it is"); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A', 'B']); var b = w.add('button', undefined, 'OK'); \ + var reads = 0; Object.defineProperty(b, 'text', {get: function () { reads++; l.selection = reads % 2; return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + #[test] fn a_script_cannot_put_its_own_listener_list_on_a_control() { let (mut r, _, _) = realm(Vec::new()); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 36117c2a96..6ae7961174 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -68,6 +68,9 @@ pub(crate) enum Queued { /// A change, and for a list's, the list's items as the person saw them. Change(u64, UiValue, Option>), Close, + /// Escape or `ui.dialog.cancel` while a handler ran: the click on the cancel button of the + /// dialog the run waits at next, or its close box. + Cancel, } /// The ScriptUI dialog on the window's dialog host; at most one is open. @@ -269,9 +272,16 @@ fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { Some(UiEvent::Change(i, v)) } Queued::Close => Some(UiEvent::Close), + Queued::Cancel => Some(cancel_event(w)), } } +/// The dialog `w`'s cancel: a click on its cancel button, or its close box when it has none or the +/// button cannot be clicked. +fn cancel_event(w: &ScriptUiDialog) -> UiEvent { + w.cancel_element.map(UiEvent::Click).filter(|e| check_event(w, e.clone()).is_ok()).unwrap_or(UiEvent::Close) +} + /// The index of the control whose id ([`UiNode::id`]) is `id` in the dialog `w`, if it has one. fn index_of(w: &ScriptUiDialog, id: u64) -> Option { w.nodes.iter().position(|n| n.id == id).filter(|i| *i > 0) @@ -605,6 +615,10 @@ fn edit(ui: &mut Ui, drafts: &BTreeMap, enabled: bool, (i, n, promp /// The event in the dialog's fields, for the dialog `w`. fn event_of(w: &ScriptUiDialog, d: &ScriptWindow) -> Result { + // A close names no control, so a `control` left from an earlier event does not stop it. + if d.event.as_deref() == Some("close") { + return Ok(UiEvent::Close); + } let control = match &d.control { Some(Value::Number(n)) => n.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`control` must be a control's index, name or text")?, Some(Value::String(s)) => w.find(s).ok_or_else(|| format!("the dialog has no control named {}", cut_to(s, 64)))?, @@ -612,7 +626,6 @@ fn event_of(w: &ScriptUiDialog, d: &ScriptWindow) -> Result { }; let list = w.nodes.get(control).is_some_and(|n| matches!(n.kind, UiKind::DropDownList | UiKind::ListBox)); match (d.event.as_deref(), &d.value) { - (Some("close"), _) => Ok(UiEvent::Close), (Some("click"), _) => Ok(UiEvent::Click(control)), (Some("change"), Some(Value::String(t))) => Ok(UiEvent::Change(control, UiValue::Text(t.clone()))), (Some("change"), Some(Value::Number(v))) if list => match list_index(v) { @@ -681,10 +694,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp) { if with_window(app, |d| d.shown()) != Some(w.shown) { return; } - if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() - && let Err(e) = give(app, &w, event) - { - app.status(e); + if let Some(event) = with_window(app, |d| d.next_event(&w)).flatten() { + // A typed text the script refuses (an earlier handler disabled its field, say) goes back + // in its field, so the person does not have to type it again. + let typed = match &event { + UiEvent::Change(i, UiValue::Text(t)) => w.nodes.get(*i).map(|n| (n.id, t.clone())), + _ => None, + }; + if let Err(e) = give(app, &w, event) { + if let Some((id, text)) = typed { + with_window(app, |d| d.drafts.insert(id, text)); + } + app.status(e); + } } } @@ -733,11 +755,13 @@ pub(crate) fn confirm(app: &mut VectorcraftApp) -> Result { /// Escape or `ui.dialog.cancel`: a click on the cancel button, or the close box when the dialog /// has none or it cannot be clicked, after the text still typed in its fields. Events the script /// has not had yet go after the ones before them. A typed text the script would refuse is an -/// error, and the dialog is left as it was. +/// error, and the dialog is left as it was. While a handler runs, the cancel waits for the dialog +/// the run waits at next. pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { - let Some(w) = app.session.script_window() else { return Ok(()) }; - let click = w.cancel_element.map(UiEvent::Click).filter(|e| check_event(&w, e.clone()).is_ok()); - let mut events = vec![click.unwrap_or(UiEvent::Close)]; + let Some(w) = app.session.script_window() else { + return with_window(app, |d| d.queue.push_back(Queued::Cancel)).ok_or_else(|| "no script dialog waits".to_string()); + }; + let mut events = vec![cancel_event(&w)]; with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true); let mut events = events.into_iter(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index d61ec36cc2..627822f738 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -872,3 +872,58 @@ fn a_large_dialog_draws_in_a_small_window() { assert!(!until_window(&mut app)); assert_eq!(log(&app), json!([1])); } + +#[test] +fn a_close_closes_the_dialog_after_a_click_on_a_control_it_lacks() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log(w.show());")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(give(&mut app, json!({"event": "click", "control": "missing"})).is_err()); + // Only `event` changes; `control` still names the missing control. + let id = open_id(&app, KIND); + with_host(&app, |host, ctx| host.set_json_field(ctx, id, "event", json!("close"))).unwrap().unwrap(); + script_window::confirm(&mut app).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([0])); +} + +#[test] +fn a_cancel_while_a_handler_runs_reaches_the_dialog_s_next_wait() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + give(&mut app, json!({"event": "click", "control": "Bold"})).unwrap(); + assert!(app.session.script_window().is_none(), "the click's handler has not run yet"); + script_window::cancel(&mut app).unwrap(); + assert_eq!(queued(&app), vec![Queued::Cancel]); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued cancel clicks Cancel"); + assert_eq!(log(&app), json!([[2, "clicked"]])); +} + +#[test] +fn a_queued_text_the_script_refuses_goes_back_in_its_field() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var name = w.add('edittext', undefined, 'first', {name: 'name'}); \ + var lock = w.add('checkbox', undefined, 'Lock'); lock.onClick = function () { name.enabled = false; }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), name.text]);", + ); + assert!(until_window(&mut app)); + with_window(&app, |d| { + d.queue(&UiEvent::Click(2)); + d.queue(&UiEvent::Change(1, UiValue::Text("Ann".into()))); + }) + .unwrap(); + step(&mut app, Vec::new()); + assert!(until_window(&mut app), "the click's handler disabled the field"); + step(&mut app, Vec::new()); + assert_eq!(typed(&app, 1).as_deref(), Some("Ann"), "the refused text stays in its field"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, "first"]])); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 433c4fe924..8ad72fc70b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1083,7 +1083,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. `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`. + - 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` and `onChange` handlers and the dialog's `onShow` and `onClose` callbacks, and returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener. 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`). From f6aef4fc8af2afa360c7a842caa856b561cf4831 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:18:53 -0800 Subject: [PATCH 26/29] Scripts: a queued list choice is dropped when a handler replaced the item, and the new items stay kept while counted A list counts how many times a script replaced its items, so a choice queued against an item a handler removed and added again with the same text is not replayed against the new item. The items array stays kept from collection while the count's slot reserves room. --- crates/engine/src/script/scriptui.rs | 4 ++++ crates/js/src/scriptui.rs | 20 ++++++++++++++++---- crates/js/src/scriptui_tests.rs | 13 +++++++++++++ crates/ui-egui/src/dialogs/script_window.rs | 9 +++++---- crates/ui-egui/src/tests/script_window.rs | 20 ++++++++++++++++++++ docs/target-app-parity.md | 2 +- 6 files changed, 59 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index b578bdb0b7..4226196239 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -139,6 +139,9 @@ pub struct UiNode { pub min: f64, pub max: f64, pub items: Vec, + /// How many times the script replaced a list's items (removed or added some), which tells a + /// list from one that holds the same texts again. + pub items_revision: u64, pub selection: Option, pub multiline: bool, pub readonly: bool, @@ -511,6 +514,7 @@ pub fn parse(d: &Data) -> Result { min, max, items, + items_revision: number(field(f, "itemsRevision")).map_or(0, |n| n as u64), selection, multiline: flag("multiline"), readonly: flag("readonly"), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 7ad0e41c20..d1a79939c7 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -101,6 +101,9 @@ const COUNT: &str = "__vcCount"; const ITEM_COUNT: &str = "__vcItemCount"; const CLOSING: &str = "__vcClosing"; const ITEMS: &str = "__vcItems"; +/// How many times a list's items have been replaced, which tells a list from one whose items were +/// removed and added again with the same texts. +const ITEMS_REV: &str = "__vcItemsRev"; const SELECTION: &str = "__vcSelection"; const LIST: &str = "__vcList"; const VALUE: &str = "__vcValue"; @@ -220,6 +223,14 @@ fn set_slot(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> i.define(o, key(name), Prop::Data { value, flags: 0 }) } +/// Gives the list `o` the array `kept` as its items and counts the replacement ([`ITEMS_REV`]). +fn set_items(i: &mut Interp, o: ObjId, kept: ObjId) -> JsResult<()> { + let rev = number_slot(i, o, ITEMS_REV)? + 1.0; + // The array stays kept from collection while the revision's slot reserves room. + i.rooted(&[Value::Object(kept)], |i| set_slot(i, o, ITEMS_REV, Value::Number(rev)))?; + set_slot(i, o, ITEMS, Value::Object(kept)) +} + /// Sets the property `name` of `o` that a script can change. fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; @@ -672,7 +683,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult } "dropdownlist" | "listbox" => { let kept = list(i, &[], false)?; - set_slot(i, c, ITEMS, Value::Object(kept))?; + set_items(i, c, kept)?; set_slot(i, c, SELECTION, Value::Number(-1.0))?; let items = list(i, &[], true)?; set_open(i, c, "items", Value::Object(items))?; @@ -778,7 +789,7 @@ fn new_items(i: &mut Interp, o: ObjId, texts: &[Value]) -> JsResult { } let kept = list(i, &items, false)?; i.temp_roots.push(Value::Object(kept)); - set_slot(i, o, ITEMS, Value::Object(kept))?; + set_items(i, o, kept)?; let copy = list(i, &items, true)?; set_open(i, o, "items", Value::Object(copy))?; Ok(items.len()) @@ -875,7 +886,7 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult JsResult> { texts.push(Data::String(text_of(i, &t, "a list item's text")?)); } d.push(("items".into(), Data::Array(texts))); + d.push(("itemsRevision".into(), Data::Number(number_slot(i, o, ITEMS_REV)?))); // The item texts' getters ran above, so the selection is read after them. selected = number_slot(i, o, SELECTION)?; let sel = selection_index(i, o)?.filter(|n| *n < items.len()); diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 98bab84b8b..e739efe5b0 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -891,6 +891,19 @@ fn a_close_a_getter_asks_for_while_the_dialog_is_read_again_ends_show() { assert_eq!(seen.borrow().ends, vec![(7.0, true)]); } +#[test] +fn a_list_replaced_with_the_same_texts_is_described_with_a_new_revision() { + let (mut r, seen, _) = realm(vec![click(2), close()]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b']); var go = w.add('button', undefined, 'Go'); \ + go.onClick = function () { l.remove(1); l.add('item', 'b'); }; w.show()"; + r.run(source).unwrap(); + let seen = seen.borrow(); + let revision = |at: usize| field(&nodes(&seen.descriptions[at])[1], "itemsRevision").clone(); + // `open` and the first `wait` see the dialog as the person does; the second `wait` sees it after the handler. + assert_eq!(field(&nodes(&seen.descriptions[2])[1], "items"), field(&nodes(&seen.descriptions[1])[1], "items"), "the same texts"); + assert_ne!(revision(1), revision(2), "a replacement item is not the one the person saw"); +} + #[test] fn a_selection_a_later_getter_changes_is_described_as_it_is() { let (mut r, seen, _) = realm(vec![click(2)]); diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 6ae7961174..b4963ae08f 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -65,8 +65,9 @@ fn list_rows(height: f32) -> u16 { #[derive(Clone, Debug, PartialEq)] pub(crate) enum Queued { Click(u64), - /// A change, and for a list's, the list's items as the person saw them. - Change(u64, UiValue, Option>), + /// A change, and for a list's, the list's items as the person saw them and how many times the + /// script had replaced them. + Change(u64, UiValue, Option<(Vec, u64)>), Close, /// Escape or `ui.dialog.cancel` while a handler ran: the click on the cancel button of the /// dialog the run waits at next, or its close box. @@ -251,7 +252,7 @@ fn queued(w: &ScriptUiDialog, event: &UiEvent) -> Option { Some(match event { UiEvent::Click(i) => Queued::Click(id(*i)?), UiEvent::Change(i, v) => { - let items = matches!(v, UiValue::Index(_)).then(|| w.nodes.get(*i).map(|n| n.items.clone())).flatten(); + let items = matches!(v, UiValue::Index(_)).then(|| w.nodes.get(*i).map(|n| (n.items.clone(), n.items_revision))).flatten(); Queued::Change(id(*i)?, v.clone(), items) } UiEvent::Close => Queued::Close, @@ -266,7 +267,7 @@ fn resolved(w: &ScriptUiDialog, q: Queued) -> Option { Queued::Click(id) => Some(UiEvent::Click(index_of(w, id)?)), Queued::Change(id, v, items) => { let i = index_of(w, id)?; - if items.is_some_and(|items| items != w.nodes[i].items) { + if items.is_some_and(|(items, revision)| items != w.nodes[i].items || revision != w.nodes[i].items_revision) { return None; } Some(UiEvent::Change(i, v)) diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index 627822f738..e79e3d16eb 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -632,6 +632,26 @@ fn a_queued_list_change_is_dropped_after_a_handler_removes_an_item() { assert_eq!(log(&app), json!([[0, true]])); } +#[test] +fn a_queued_list_change_is_dropped_after_a_handler_replaces_the_item_with_one_of_the_same_text() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var rm = w.add('button', undefined, 'Replace'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); \ + rm.onClick = function () { l.remove(2); l.add('item', 'c'); }; vc.log([w.show(), l.selection === null]);", + ); + assert!(until_window(&mut app)); + give(&mut app, json!({"event": "click", "control": "Replace"})).unwrap(); + with_window(&app, |d| d.queue(&UiEvent::Change(2, UiValue::Index(Some(2))))).unwrap(); + assert!(until_window(&mut app), "the script runs the handler and waits again"); + step(&mut app, Vec::new()); + assert!(queued(&app).is_empty(), "the change chose the item that was replaced, so it is dropped"); + assert_eq!(app.session.script_window().unwrap().nodes[2].selection, None); + give(&mut app, json!({"event": "close"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, true]])); +} + #[test] fn cancel_on_the_quit_question_does_not_show_a_dialog_whose_show_ended() { let mut app = app(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8ad72fc70b..71de04cbae 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1083,7 +1083,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` and `onChange` handlers and the dialog's `onShow` and `onClose` callbacks, and returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener. 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`. + - 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 and runs the controls' `onClick`, `onChanging` and `onChange` handlers. The window's own callbacks are `onShow`, which runs when `show()` starts, and `onClose`, which runs before the dialog closes and keeps it open when it returns false. `show()` returns the result of `close(result)`, or 1 for the default button and 2 for the cancel button when the button has no `onClick` or click listener and no handler closed the dialog with another result. 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`). From 1d3e835927f8c3e4ae8ada76c1d2e42792168f2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 02:43:06 -0800 Subject: [PATCH 27/29] Scripts: ScriptUI review fixes for heap-limit adds and removes, listeners, list texts, Enter, the run's questions and automation requests - Adding a control or an item, and removing items, builds both arrays before the first write, so a run that ends at the heap limit leaves the lists and the dialog's counts as they were. - A listener registered after an event started does not hear it in a later phase, a capturing container's re-registration included. - show() reads the dialog again when a getter changes a list item's text after the item was read. - Enter and Escape skip an OK or Cancel button inside a hidden or disabled container. - A resource string of a name and a type without braces throws a SyntaxError, and a \u escape pair of surrogates reads as one character. - In the app, queued events wait while another dialog is open over the script's dialog, and the run's own questions wait while a popup, such as an open drop-down list, is over it. ui.dialog.confirm and ui.dialog.cancel take only the dialog, ui.dialog.set needs a field or an action and answers with the dialog it set, and OK is refused while a dialog open over it waits. A cancel after typed text clicks the cancel button the dialog has when its turn comes, and an immediate cancel the run refuses is an error. - A click on a list box row gives the list the keyboard focus. - The vc hint test names BridgeTalk, since Window now exists; the params text and docs/mcp.md say that a show() in a handler notify runs throws only in the app, and define_script_ui says when end is not called. --- crates/engine/src/cmd/scripts.rs | 2 +- crates/engine/src/script/mod.rs | 2 +- crates/engine/src/tests/script_run.rs | 4 +- crates/engine/src/tests/script_scriptui.rs | 17 ++ crates/js/src/realm.rs | 5 +- crates/js/src/scriptui.rs | 180 ++++++++++++++------ crates/js/src/scriptui_resource.rs | 36 +++- crates/js/src/scriptui_tests.rs | 108 ++++++++++++ crates/ui-egui/src/dialogs/script_run.rs | 4 +- crates/ui-egui/src/dialogs/script_window.rs | 62 ++++++- crates/ui-egui/src/tests/script_window.rs | 144 +++++++++++++++- docs/mcp.md | 15 +- 12 files changed, 499 insertions(+), 80 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index b1635c23f2..d895c3969f 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, and in the app so do alert, confirm, prompt and the file dialogs a handler calls, 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), 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", always, run ), diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 65f9a279e1..f141f4befc 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -1625,7 +1625,7 @@ fn kind_id(kind: &RunErrorKind) -> &'static str { /// `e`'s message, with what to do about a failure that comes from a script written for another /// program. A message the script supplied itself ([`RunError::authored`]) is given as it is. fn explained(e: &RunError) -> String { - const HOST_OBJECTS: &[&str] = &["Window", "BridgeTalk"]; + const HOST_OBJECTS: &[&str] = &["BridgeTalk"]; let message = &e.message; let first = message.strip_prefix("ReferenceError: ").and_then(|m| m.split_whitespace().next()); let names_host_object = first.is_some_and(|f| HOST_OBJECTS.contains(&f)); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 9489921682..2bccfca19c 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -165,7 +165,7 @@ fn an_error_names_the_script_its_place_and_kind() { assert_eq!(e, "t.js: line 2, column 3: TypeError: no (thrown)"); let e = run(&mut s, "var = 1;").unwrap_err().to_string(); assert!(e.starts_with("t.js: line 1,") && e.ends_with("(syntax)"), "{e}"); - assert!(run(&mut s, "new Window('dialog');").unwrap_err().to_string().contains("`vc`")); + assert!(run(&mut s, "new BridgeTalk();").unwrap_err().to_string().contains("`vc`")); // The application's members need no `app.`, so naming one alone is not an error. assert_eq!(run(&mut s, "activeDocument;").unwrap()["ok"], true); assert!(run(&mut s, "#targetengine 9x\n1").unwrap_err().to_string().contains("#targetengine needs a name of letters, digits and _")); @@ -206,7 +206,7 @@ fn failed_script_report_keeps_message_and_adds_origin() { assert_eq!(error, Some(json!(format!("t.js:{line}:{column}: {message}"))), "{source}"); } // The app's own reference error names the `vc` object; the same text a script threw does not. - run(&mut s, "new Window('dialog');").unwrap_err(); + run(&mut s, "new BridgeTalk();").unwrap_err(); assert!(s.script_report().unwrap()["message"].as_str().unwrap().contains("`vc`")); assert_eq!(s.script_report().unwrap()["messageOrigin"], "built-in"); // An error in code `eval` compiled keeps where its message came from. diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 01cef50a55..23937fb683 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -287,6 +287,23 @@ fn a_show_in_a_callback_throws_in_the_app() { assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); } +/// A handler that `notify` runs while no dialog is showing may show one in a run with nobody to +/// ask, which takes a window answer for it; in the app the same `show()` throws. +#[test] +fn a_show_in_a_handler_notify_runs_takes_a_window_answer_with_nobody_to_ask() { + let source = "var b = new Window('dialog').add('button', undefined, 'Go'); var r = ''; \ + b.onClick = function () { var d = new Window('dialog'); d.add('button', undefined, 'OK'); r = d.show(); }; \ + try { b.notify(); } catch (x) { r = x.message; } vc.log(r);"; + let mut s = one_doc(); + let r = headless(&mut s, source, window(json!([{"control": "OK", "event": "click"}]))).unwrap(); + assert_eq!(r["log"], json!([1]), "{r}"); + let mut s = one_doc(); + s.script_frames = true; + assert_eq!(s.execute("script.run", &json!({"source": source, "name": "w.js"})).unwrap()["running"], true); + let r = pump(&mut s).expect("show does not wait in a handler notify runs").unwrap(); + assert!(r["log"][0].as_str().unwrap().contains("cannot open inside a callback"), "{r}"); +} + fn node(kind: &str, parent: f64) -> Data { Data::Object(vec![ ("kind".into(), Data::String(kind.into())), diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 4688816795..ecdcc23b84 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -607,7 +607,10 @@ impl Realm { /// Adds ScriptUI's global constructor `Window` ([`crate::scriptui`]), whose dialogs the host /// functions in `items` show: `open` and `wait`, each given the dialog's description, and - /// `end`, given the result of `show()` and whether `show()` ended normally. + /// `end`, given the result of `show()` and whether `show()` ended normally. A run that ends + /// while `show()` waits for `wait`'s answer, because it is stopped or the host does not resume + /// it, ends without a call to `end`: the host releases what it holds for the dialog when the run + /// ends, and does not wait for `end`. pub fn define_script_ui(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::scriptui::install(&mut self.interp, items) { Ok(()) => Ok(()), diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index d1a79939c7..47d8aeaffb 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -60,9 +60,9 @@ //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] //! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a //! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These and [`MAX_LISTENERS`] are -//! VectorCraft's own limits. A getter that changes a list's items after the list was read, or adds -//! or removes a control after the dialog's controls were read, makes `show()` read the dialog -//! again, and a dialog that changes again throws an `Error`. A `text` getter +//! VectorCraft's own limits. A getter that changes a list's items or an item's text after the list +//! was read, or adds or removes a control after the dialog's controls were read, makes `show()` +//! read the dialog again, and a dialog that changes again throws an `Error`. A `text` getter //! that changes a list or a container while `remove(text)` looks for an item or a control makes //! `remove` throw an `Error`. @@ -231,6 +231,13 @@ fn set_items(i: &mut Interp, o: ObjId, kept: ObjId) -> JsResult<()> { set_slot(i, o, ITEMS, Value::Object(kept)) } +/// The writes that give the list `o` the array `kept` as its items and `copy` as the array a script +/// can change, counting the replacement ([`ITEMS_REV`]), for [`write_all`]. +fn item_writes(i: &Interp, o: ObjId, kept: Value, copy: Value) -> JsResult<[Write<'static>; 3]> { + let rev = number_slot(i, o, ITEMS_REV)? + 1.0; + Ok([(o, ITEMS_REV, Value::Number(rev), 0), (o, ITEMS, kept, 0), (o, "items", copy, OPEN)]) +} + /// Sets the property `name` of `o` that a script can change. fn set_open(i: &mut Interp, o: ObjId, name: &str, value: Value) -> JsResult<()> { i.rooted(std::slice::from_ref(&value), |i| i.reserve_heap(PROP_BYTES))?; @@ -332,19 +339,46 @@ fn list(i: &mut Interp, items: &[Value], open: bool) -> JsResult { Ok(a) } -/// Adds `v` to the end of the list in `o`'s slot `name`, and puts a copy a script can change in -/// its property `public`. -fn append(i: &mut Interp, o: ObjId, name: &str, public: &str, v: Value) -> JsResult<()> { +/// A write of `value` to the property of an object with a name and flags, made by [`write_all`]. +type Write<'a> = (ObjId, &'a str, Value, u8); + +/// Makes `writes` in order, after checking once that the heap has room for the properties they +/// add, so a run that ends here (out of memory) makes none of them. +fn write_all(i: &mut Interp, writes: Vec>) -> JsResult<()> { + let values: Vec = writes.iter().map(|(_, _, v, _)| v.clone()).collect(); + i.rooted(&values, |i| { + // The heap grows only by the properties a write adds. + let mut growth = 0; + for (at, name, _, _) in &writes { + if !i.object(*at)?.props.contains(&key(name)) { + growth += PROP_BYTES + string_bytes(name.len()); + } + } + i.reserve_heap(growth)?; + for (at, name, value, flags) in writes { + i.define(at, key(name), Prop::Data { value, flags })?; + } + Ok(()) + }) +} + +/// Adds `v` to the end of the list in `o`'s slot `name`, puts a copy a script can change in its +/// property `public`, and makes the writes in `more` with them. Both arrays are made before the +/// first write, so a run that ends here leaves the lists and `more`'s properties as they were. +fn append<'a>(i: &mut Interp, o: ObjId, name: &'a str, public: &'a str, v: Value, more: Vec>) -> JsResult<()> { let mut items = match object_slot(i, o, name)? { Some(a) => list_values(i, a)?, None => Vec::new(), }; items.push(v); i.rooted(&items.clone(), |i| { - let kept = list(i, &items, false)?; - set_slot(i, o, name, Value::Object(kept))?; - let copy = list(i, &items, true)?; - set_open(i, o, public, Value::Object(copy)) + let kept = Value::Object(list(i, &items, false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let copy = Value::Object(list(i, &items, true)?); + let mut writes = vec![(o, name, kept.clone(), 0), (o, public, copy, OPEN)]; + writes.extend(more); + write_all(i, writes) + }) }) } @@ -445,7 +479,7 @@ 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(); - let spec = if kind.contains('{') { Some(resource(i, &kind, "Window")?) } else { None }; + let spec = if is_resource(&kind) { 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"))); @@ -475,6 +509,12 @@ fn window_ctor(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult bool { + text.contains('{') || text.contains(':') +} + /// The resource specification `text` given to `what`, or a `SyntaxError` or `RangeError` naming /// `what`. fn resource(i: &mut Interp, text: &str, what: &str) -> JsResult { @@ -610,7 +650,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if !matches!(kind.as_str(), "dialog" | "group" | "panel") { return Err(error(i, &format!("add: a {kind} holds no controls"))); } - if ty.contains('{') { + if is_resource(&ty) { let spec = resource(i, &ty, "add")?; let mark = i.temp_roots.len(); let r = add_resource(i, o, &spec); @@ -732,9 +772,8 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if items as usize + staged > MAX_ITEMS { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); } - append(i, o, KIDS, "children", Value::Object(c))?; - set_slot(i, win, COUNT, Value::Number(count + 1.0))?; - set_slot(i, win, ITEM_COUNT, Value::Number(items + staged as f64))?; + let counts = vec![(win, COUNT, Value::Number(count + 1.0), 0), (win, ITEM_COUNT, Value::Number(items + staged as f64), 0)]; + append(i, o, KIDS, "children", Value::Object(c), counts)?; Ok(Value::Object(c)) })(); i.temp_roots.truncate(mark); @@ -751,14 +790,12 @@ fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { if count as usize >= MAX_ITEMS { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); } - let item = new_item(i, o, text.clone())?; - i.rooted(std::slice::from_ref(&item), |i| set_slot(i, win, ITEM_COUNT, Value::Number(count + 1.0)))?; - Ok(item) + new_item(i, o, text.clone(), vec![(win, ITEM_COUNT, Value::Number(count + 1.0), 0)]) }) } -/// Adds an item with `text` to the end of the list `o`, without counting it in the dialog's items. -fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { +/// Adds an item with `text` to the end of the list `o`, making the writes in `more` with it. +fn new_item(i: &mut Interp, o: ObjId, text: Value, more: Vec>) -> JsResult { let proto = classes(i)?.item_proto; i.rooted(std::slice::from_ref(&text), |i| { i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(4)))?; @@ -766,7 +803,7 @@ fn new_item(i: &mut Interp, o: ObjId, text: Value) -> JsResult { i.rooted(&[Value::Object(item)], |i| { set_slot(i, item, LIST, Value::Object(o))?; set_open(i, item, "text", text.clone())?; - append(i, o, ITEMS, "items", Value::Object(item))?; + append(i, o, ITEMS, "items", Value::Object(item), more)?; Ok(Value::Object(item)) }) }) @@ -884,12 +921,16 @@ fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult, event: ObjId, phase: f64) -> JsResult { +/// it was added again, and neither does one registered after `cutoff`, the last registration on +/// `at` when the event started. +fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, event: ObjId, phase: f64, cutoff: f64) -> JsResult { let wanted = |i: &Interp| -> JsResult> { Ok(listeners_of(i, at)? .into_iter() - .filter(|(t, _, c, _)| is_type(t, ty) && capture.is_none_or(|want| *c == want)) + .filter(|(t, _, c, n)| is_type(t, ty) && capture.is_none_or(|want| *c == want) && *n <= cutoff) .map(|(_, f, _, n)| (f, n)) .collect()) }; @@ -1185,23 +1227,27 @@ fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: & set_open(i, event, "cancelable", Value::Bool(false))?; set_open(i, event, "detail", Value::Number(if ty == "click" { 1.0 } else { 0.0 }))?; let stopped = |i: &Interp| -> JsResult { Ok(slot(i, event, STOPPED)?.truthy()) }; - for p in above.iter().rev() { + // A listener registered once the event started does not hear it, in any phase. + let cutoff = |i: &Interp, o: ObjId| number_slot(i, o, REGISTERED); + let target_cutoff = cutoff(i, target)?; + let cutoffs = above.iter().map(|p| cutoff(i, *p)).collect::>>()?; + for (p, n) in above.iter().zip(&cutoffs).rev() { if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(true), event, 1.0)?; + run_listeners(i, *p, ty, Some(true), event, 1.0, *n)?; if stopped(i)? { return Ok(true); } } let had = handler(i, target, callback)?.is_some(); - let heard = run_listeners(i, target, ty, None, event, 2.0)?; + let heard = run_listeners(i, target, ty, None, event, 2.0, target_cutoff)?; if bubbles && !stopped(i)? { - for p in above { + for (p, n) in above.iter().zip(&cutoffs) { if !containers_above(i, target)?.contains(p) { continue; } - run_listeners(i, *p, ty, Some(false), event, 3.0)?; + run_listeners(i, *p, ty, Some(false), event, 3.0, *n)?; if stopped(i)? { break; } @@ -1323,19 +1369,24 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult set_slot(i, o, SELECTION, Value::Number(-1.0))?, - Some(n) if n > at => set_slot(i, o, SELECTION, Value::Number((n - 1) as f64))?, - _ => {} - } + let selection = match selection_index(i, o)? { + Some(n) if n == at => Some(-1.0), + Some(n) if n > at => Some((n - 1) as f64), + _ => None, + }; + // Both arrays are made before the first write, so a run that ends here leaves the list, + // its selection and the dialog's count of items as they were. + i.rooted(&items.clone(), |i| { + let kept = Value::Object(list(i, &items, false)?); + i.rooted(std::slice::from_ref(&kept), |i| { + let copy = Value::Object(list(i, &items, true)?); + let mut writes = item_writes(i, o, kept.clone(), copy)?.to_vec(); + writes.push((win, ITEM_COUNT, Value::Number((count - 1.0).max(0.0)), 0)); + writes.extend(selection.map(|n| (o, SELECTION, Value::Number(n), 0))); + write_all(i, writes) + }) + })?; return Ok(Value::Undefined); } if !matches!(kind.as_str(), "dialog" | "group" | "panel") { @@ -1749,9 +1800,9 @@ fn margins(i: &mut Interp, v: &Value) -> JsResult { /// The dialog's description: its elements in order, each after the container that holds it, as /// [`Data`] for the host's `open` and `wait`, with the elements in that order, and the indices of /// its default and cancel elements (-1 for none), and each element's array of list items as it -/// was described (`undefined` for an element that is not a list). When a getter changes a list, -/// or adds or removes a control, after it was read, the dialog is read again once; a dialog that -/// changes again throws an `Error`. +/// was described (`undefined` for an element that is not a list). When a getter changes a list or +/// a list item's text, or adds or removes a control, after it was read, the dialog is read again +/// once; a dialog that changes again throws an `Error`. fn describe(i: &mut Interp, win: ObjId) -> JsResult { for _ in 0..2 { let mark = i.temp_roots.len(); @@ -1777,6 +1828,17 @@ fn lists_unchanged(i: &Interp, order: &[(ObjId, String, f64)], snapshot: &[Value Ok(true) } +/// Has each list item in `texts` the text it had when it was read? +fn texts_unchanged(i: &Interp, texts: &[(ObjId, Value)]) -> JsResult { + for (item, read) in texts { + match i.get_own_property(*item, &key("text"))? { + Some(Prop::Data { value, .. }) if crate::interp::same_value(&value, read) => {} + _ => return Ok(false), + } + } + Ok(true) +} + /// Has each element in `order` the array of controls it had when the dialog was read? fn tree_unchanged(i: &Interp, order: &[(ObjId, String, f64)], tree: &[Value]) -> JsResult { for ((o, ..), kept) in order.iter().zip(tree) { @@ -1825,6 +1887,10 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let mut snapshot = Vec::with_capacity(order.len()); // Each list's selection as it is read; a later getter may change it. let mut selections = Vec::with_capacity(order.len()); + // Whether each element, in `order`, is enabled and visible with the containers above it. + let mut live: Vec<(bool, bool)> = Vec::with_capacity(order.len()); + // Each list item's own text as it was read. + let mut item_texts: Vec<(ObjId, Value)> = Vec::new(); for (o, kind, parent) in &order { let o = *o; let mut listed = Value::Undefined; @@ -1842,8 +1908,11 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { ]; let enabled = get(i, o, "enabled")?.truthy(); let visible = get(i, o, "visible")?.truthy(); + // A control is enabled and visible only while every container above it is. + let (above_enabled, above_visible) = if *parent >= 0.0 { live.get(*parent as usize).copied().unwrap_or((true, true)) } else { (true, true) }; + live.push((enabled && above_enabled, visible && above_visible)); // Enter and Escape click a button found by its name or text only when it can be clicked. - let clickable = kind == "button" && enabled && visible; + let clickable = kind == "button" && enabled && visible && above_enabled && above_visible; names.push((clickable, name, text)); d.push(("enabled".into(), Data::Bool(enabled))); d.push(("visible".into(), Data::Bool(visible))); @@ -1913,6 +1982,13 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { let mut texts = Vec::with_capacity(items.len()); for item in &items { let t = i.get_value(item, &key("text"))?; + // The text as the item holds it; a later getter that changes it changes the list. + if let Some(at) = item.as_object() + && let Some(Prop::Data { value, .. }) = i.get_own_property(at, &key("text"))? + { + i.temp_roots.push(value.clone()); + item_texts.push((at, value)); + } texts.push(Data::String(text_of(i, &t, "a list item's text")?)); } d.push(("items".into(), Data::Array(texts))); @@ -1941,7 +2017,7 @@ fn describe_rooted(i: &mut Interp, win: ObjId) -> JsResult> { }; let def = target(i, "defaultElement", "ok")?; let cancel = target(i, "cancelElement", "cancel")?; - if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? { + if !lists_unchanged(i, &order, &snapshot, &selections)? || !tree_unchanged(i, &order, &tree)? || !texts_unchanged(i, &item_texts)? { return Ok(None); } let desc = Data::Object(vec![ diff --git a/crates/js/src/scriptui_resource.rs b/crates/js/src/scriptui_resource.rs index 118d4c74ad..6d27cce47b 100644 --- a/crates/js/src/scriptui_resource.rs +++ b/crates/js/src/scriptui_resource.rs @@ -219,6 +219,14 @@ impl Reader { } } + /// The number that the `digits` hex digits at `at` write; `None` when they are not all there. + fn hex(&self, at: usize, digits: usize) -> Option { + let hex: String = self.chars.iter().skip(at).take(digits).collect(); + // `from_str_radix` also takes a sign, which an escape does not have. + let valid = hex.len() == digits && hex.chars().all(|c| c.is_ascii_hexdigit()); + u32::from_str_radix(&hex, 16).ok().filter(|_| valid) + } + fn string(&mut self) -> Result { let Some(quote) = self.peek() else { return Err(self.expected("a string")) }; let start = self.at; @@ -249,16 +257,24 @@ impl Reader { '0' => s.push('\0'), '\n' => {} 'u' | 'x' => { + let escape = self.at - 1; let digits = if e == 'u' { 4 } else { 2 }; - let hex: String = self.chars.iter().skip(self.at).take(digits).collect(); - // `from_str_radix` also takes a sign, which an escape does not have. - let valid = hex.len() == digits && hex.chars().all(|c| c.is_ascii_hexdigit()); - match u32::from_str_radix(&hex, 16).ok().filter(|_| valid).and_then(char::from_u32) { + let code = self.hex(self.at, digits); + // A high surrogate and the `\u` escape of a low one after it are one character. + let low = code.filter(|c| (0xD800..0xDC00).contains(c)).and_then(|_| { + let next = self.chars.get(self.at + digits..self.at + digits + 2)?; + (next == ['\\', 'u']).then(|| self.hex(self.at + digits + 2, 4)).flatten().filter(|c| (0xDC00..0xE000).contains(c)) + }); + let (code, len) = match (code, low) { + (Some(high), Some(low)) => (Some(0x10000 + ((high - 0xD800) << 10) + (low - 0xDC00)), digits + 6), + (code, _) => (code, digits), + }; + match code.and_then(char::from_u32) { Some(c) => { s.push(c); - self.at += digits; + self.at += len; } - None => return Err(Fault::Syntax(format!("the escape at character {} is not valid", self.at - 1))), + None => return Err(Fault::Syntax(format!("the escape at character {escape} is not valid"))), } } e => s.push(e), @@ -329,6 +345,14 @@ mod tests { assert_eq!(parse("dialog { t: '\\x0A\\u0041' }"), Ok(spec("dialog", vec![("t", Res::String("\nA".into()))]))); } + #[test] + fn a_surrogate_pair_of_escapes_is_one_character_and_a_lone_surrogate_is_a_syntax_fault() { + assert_eq!(parse("dialog { t: '\\uD83D\\uDE00!' }"), Ok(spec("dialog", vec![("t", Res::String("\u{1F600}!".into()))]))); + for text in ["dialog { t: '\\uD83D' }", "dialog { t: '\\uD83Dx' }", "dialog { t: '\\uD83D\\u0041' }", "dialog { t: '\\uDE00' }"] { + assert_eq!(parse(text), Err(Fault::Syntax("the escape at character 14 is not valid".into())), "{text}"); + } + } + #[test] fn a_resource_specification_that_ends_early_says_at_which_character() { assert_eq!(parse("dialog {"), Err(Fault::Syntax("expected a name at character 9, the end of the resource specification".into()))); diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index e739efe5b0..95719bf965 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -333,6 +333,8 @@ fn a_malformed_resource_specification_throws_a_syntax_error() { "new Window('dialog {} trailing')", "new Window('dialog').add('g: Group { v: orange }')", "new Window('dialog').add('g: Group { o: { b: Button {} } }')", + "new Window('dialog').add('g: Group')", + "new Window('main: Dialog')", ] { let (mut r, _, _) = realm(Vec::new()); let e = r.run(&format!("try {{ {source}; 'made' }} catch (e) {{ e.name }}")).unwrap(); @@ -477,6 +479,26 @@ fn a_list_a_later_getter_changes_is_described_as_the_person_picks_from_it() { assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); } +#[test] +fn a_list_item_text_a_later_getter_changes_is_described_as_the_person_picks_from_it() { + let (mut r, seen, _) = realm(vec![change(1, Data::Number(0.0)), click(2)]); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); \ + var swapped = false; Object.defineProperty(b, 'text', {get: function () { if (!swapped) { swapped = true; l.items[0].text = 'B'; } return 'OK'; }}); \ + var picked = ''; l.onChange = function () { picked = l.selection.text; }; w.show(); picked"; + assert_eq!(r.run(source).unwrap(), JsValue::String("B".into())); + let seen = seen.borrow(); + assert_eq!( + field(&nodes(&seen.descriptions[0])[1], "items"), + &Data::Array(vec![Data::String("B".into())]), + "the description shows the text the item has" + ); + let (mut r, _, _) = realm(Vec::new()); + let source = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['A']); var b = w.add('button', undefined, 'OK'); var n = 0; \ + Object.defineProperty(b, 'text', {get: function () { l.items[0].text = 'T' + n++; return 'OK'; }}); \ + try { w.show(); } catch (e) { e.message }"; + assert_eq!(r.run(source).unwrap(), JsValue::String("show: a list's items or a container's controls changed while the dialog was read".into())); +} + #[test] fn a_control_a_later_getter_removes_is_not_in_the_description() { let (mut r, seen, _) = realm(vec![click(1)]); @@ -546,6 +568,18 @@ fn a_hidden_or_disabled_ok_button_is_not_the_default_found_by_its_text() { assert_eq!(field(&seen.borrow().descriptions[0], "defaultElement"), &Data::Number(3.0), "the OK button that can be clicked is the default"); } +#[test] +fn an_ok_or_cancel_button_in_a_hidden_or_disabled_group_is_not_found_by_its_text() { + let (mut r, seen, _) = realm(vec![close()]); + let source = "var w = new Window('dialog'); var g = w.add('group'); g.add('button', undefined, 'OK'); g.add('button', undefined, 'Cancel'); \ + g.visible = false; var h = w.add('panel'); h.add('group').add('button', undefined, 'OK'); h.enabled = false; \ + w.add('button', undefined, 'OK'); w.add('button', undefined, 'Cancel'); w.show()"; + assert_eq!(r.run(source).unwrap(), JsValue::Number(0.0)); + let seen = seen.borrow(); + assert_eq!(field(&seen.descriptions[0], "defaultElement"), &Data::Number(7.0), "the OK button outside the groups is the default"); + assert_eq!(field(&seen.descriptions[0], "cancelElement"), &Data::Number(8.0), "the Cancel button outside the group is the cancel button"); +} + #[test] fn an_edit_field_that_hides_its_text_is_refused_when_shown() { let (mut r, seen, _) = realm(Vec::new()); @@ -828,6 +862,67 @@ fn a_remove_that_runs_out_of_fuel_leaves_the_dialog_as_it_was() { assert_eq!(v, JsValue::String("512|||512".into()), "the removed group's controls are counted off the dialog once"); } +/// Runs `op` after `setup` with each heap limit from the bytes `setup` left up to past what `op` +/// adds, and after each run that ended at the limit, gives `check` the realm without a limit and +/// what its host was given. +fn at_each_heap_limit(setup: &str, op: &str, check: impl Fn(&mut Realm, &RefCell, u64)) { + let ready = || { + let (mut r, seen, _) = realm(vec![close(); 4]); + r.run(setup).unwrap(); + r.collect_garbage(); + (r, seen) + }; + let (mut r, _) = ready(); + let before = r.interp().heap.bytes; + r.run(op).unwrap(); + let added = r.interp().heap.bytes.saturating_sub(before) as u64; + let mut ended = 0; + for extra in 0..added + 64 { + let (mut r, seen) = ready(); + let limit = r.interp().heap.bytes + extra as usize; + r.set_limits(Limits { fuel: 10_000_000, heap_bytes: limit, ..Limits::default() }); + let e = match r.run(op) { + Ok(_) => break, + Err(e) => e, + }; + assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{op} at {extra}: {e:?}"); + ended += 1; + r.set_limits(Limits { fuel: 10_000_000, ..Limits::default() }); + check(&mut r, &seen, extra); + } + assert!(ended > 0, "{op} ended at the heap limit"); +} + +#[test] +fn an_add_or_a_remove_that_ends_at_the_heap_limit_leaves_the_dialog_as_it_was() { + let list = "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); l.selection = 2;"; + for op in ["w.add('button')", "l.add('item', 'd')", "l.remove(0)", "l.removeAll()"] { + let check = |r: &mut Realm, seen: &RefCell, extra: u64| { + // What the script reads, and what `show()` describes from the dialog's own arrays. + let read = r.run("var d = []; for (var k = 0; k < l.items.length; k++) d.push(l.items[k].text); [w.children.length, d.join(' '), l.selection.index].join()"); + assert_eq!(read, Ok(JsValue::String("1,a b c,2".into())), "{op} ended at {extra} bytes and changed what the script reads"); + let at = seen.borrow().descriptions.len(); + r.run("w.show()").unwrap(); + let shown = nodes(&seen.borrow().descriptions[at]); + let items = Data::Array(["a", "b", "c"].iter().map(|t| Data::String((*t).into())).collect()); + assert_eq!( + (shown.len(), field(&shown[1], "items"), field(&shown[1], "selection")), + (2, &items, &Data::Number(2.0)), + "{op} ended at {extra} bytes and changed the dialog" + ); + }; + at_each_heap_limit(list, op, check); + } + // A removeAll that ends at the limit leaves the dialog's count of items as it was, so a full + // dialog takes no more items. + let full = + format!("var w = new Window('dialog'); var l = w.add('listbox', undefined, new Array({}).join('x,').split(','));", scriptui::MAX_ITEMS); + at_each_heap_limit(&full, "l.removeAll()", |r, _, extra| { + let more = r.run("try { l.add('item', 'y'); 'added' } catch (e) { e.name }"); + assert_eq!(more, Ok(JsValue::String("RangeError".into())), "removeAll ended at {extra} bytes and miscounted the items"); + }); +} + #[test] fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw() { let (mut r, _, _) = realm(Vec::new()); @@ -881,6 +976,19 @@ fn a_listener_removed_and_added_again_in_the_same_event_does_not_run_in_it() { assert_eq!(v, JsValue::String("1,1,2".into()), "the second registration runs from the next event on"); } +#[test] +fn a_listener_a_capturing_container_registers_again_does_not_run_in_the_same_event() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); var ran = []; var once = true; function own() { ran.push(2); } \ + w.addEventListener('click', function () { ran.push(1); if (once) { once = false; b.removeEventListener('click', own); b.addEventListener('click', own); } }, true); \ + b.addEventListener('click', own); b.notify('onClick'); b.notify('onClick'); ran.join(',')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("1,1,2".into()), "the new registration runs from the next event on"); +} + #[test] fn a_close_a_getter_asks_for_while_the_dialog_is_read_again_ends_show() { let (mut r, seen, _) = realm(vec![click(1)]); diff --git a/crates/ui-egui/src/dialogs/script_run.rs b/crates/ui-egui/src/dialogs/script_run.rs index c6a7fc12ee..131fb25611 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -438,9 +438,9 @@ pub(crate) fn busy(app: &VectorcraftApp) -> bool { } /// Whether the run's question can open now: over nothing, or over the script's ScriptUI dialog -/// while nothing is open over it. +/// while nothing, neither a dialog nor a popup, is open over it. pub(crate) fn can_ask(app: &VectorcraftApp) -> bool { - !busy(app) || script_window::is_top(app) + !busy(app) || script_window::uncovered(app) } /// Opens `dialog` over the script's ScriptUI dialog when that is the top dialog, so the ScriptUI diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index b4963ae08f..b9c0d7a996 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -18,6 +18,7 @@ use std::collections::{BTreeMap, VecDeque}; +use craft::automation::protocol::Params; use craft::behavior::{Selection, SelectionChange, keyed}; use craft::theme::Variant; use craft::ui::buttons::Button; @@ -30,6 +31,7 @@ use craft::ui::list::{List, ListRow}; use craft::ui::pickers::Select; use craft::ui::runtime::focus::Initial; use craft::ui::runtime::keys::take_submit; +use craft::ui::runtime::overlay; use craft::ui::sections::{DialogRole, FooterButton, GroupBox}; use craft::ui::text::TextField; use craft::ui::value_drag::Slider; @@ -96,6 +98,8 @@ pub(crate) struct ScriptWindow { cancel: bool, /// An error for the status bar. status: Option, + /// The overlay layer the dialog's body was last drawn in. + layer: Option, } impl ScriptWindow { @@ -112,6 +116,7 @@ impl ScriptWindow { stop: false, cancel: false, status: None, + layer: None, } } @@ -318,7 +323,7 @@ impl StackDialog for ScriptWindow { let shown = dialog.show(ui, |ui, _| { let (width, height) = window.size(); let size = egui::vec2(width.max(1.0), height.max(1.0)); - let mut pass = Pass::default(); + let mut pass = Pass { layer: overlay::drawing_parent(ui.ctx()), ..Pass::default() }; ui.scope(|ui| { ui.set_max_size(MAX_SHOWN); Stack::new().scroll(Scroll::both()).show(ui, |ui, _| { @@ -345,6 +350,9 @@ impl StackDialog for ScriptWindow { pass }); let pass = shown.inner.unwrap_or_default(); + if pass.layer.is_some() { + self.layer = pass.layer; + } for (id, draft) in pass.drafts { match draft { Some(text) => self.drafts.insert(id, text), @@ -431,12 +439,13 @@ struct Shown { } /// What one run of the dialog's body gave: the events, whether an edit field has the keyboard -/// focus, and the typed texts to keep or forget, by field id. +/// focus, the typed texts to keep or forget, by field id, and the overlay layer it was drawn in. #[derive(Default)] struct Pass { events: Vec, typing: bool, drafts: Vec<(u64, Option)>, + layer: Option, } /// The text of the visible static text just before control `i` in its container: the visible @@ -506,8 +515,10 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr let source = keyed(&keys, |k: &usize| *k); let selection = n.selection.map(Selection::single).unwrap_or_default(); // Screen readers read the box as a list box, by its name or the static text before - // it, with the selected item as its value. + // it, with the selected item as its value. The box has no opener to keep the keyboard + // focus, so a press on a row gives it the focus and the arrow keys go on from that row. let out = List::::options(list_name(n, prompt)) + .focus_on_press(true) .id_salt(salt) .enabled(enabled) .max_rows(list_rows(n.rect.h)) @@ -650,6 +661,14 @@ pub(crate) fn is_top(app: &VectorcraftApp) -> bool { with_host(app, |host, _| host.get::().is_some_and(|d| host.stack().is_top(d.id()))).unwrap_or(false) } +/// Whether the ScriptUI dialog is the top dialog and no popup or modal layer, its own drop-down +/// lists' included, is open over it. +pub(crate) fn uncovered(app: &VectorcraftApp) -> bool { + let Some(layer) = with_window(app, |d| d.layer) else { return false }; + let top = app.ui_ctx.as_ref().and_then(overlay::top); + is_top(app) && top.is_none_or(|top| Some(top) == layer) +} + /// Opens, keeps or closes the ScriptUI dialog as the run's `show()` stands: it opens when a /// `show()` waits, follows the dialog while the run waits at it (its heading follows a title a /// handler changed), stays open while one of its handlers runs and closes when `show()` ends. A @@ -691,6 +710,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp) { if cancel_asked && let Err(e) = cancel(app) { app.status(e); } + // Events wait in the queue while another dialog, such as the quit question, is open over it. + if !is_top(app) { + return; + } let Some(w) = app.session.script_window() else { return }; if with_window(app, |d| d.shown()) != Some(w.shown) { return; @@ -765,11 +788,20 @@ pub(crate) fn cancel(app: &mut VectorcraftApp) -> Result<(), String> { let mut events = vec![cancel_event(&w)]; with_window(app, |d| d.commit_drafts(&w, &mut events)).unwrap_or(Ok(()))?; let empty = with_window(app, |d| d.queue.is_empty()).unwrap_or(true); + // A cancel after other events goes last, and is a click on the cancel button of the dialog the + // run waits at when its turn comes, or its close box. + let deferred = !empty || events.len() > 1; + if deferred { + events.pop(); + } let mut events = events.into_iter(); if empty && let Some(first) = events.next() { - let _ = app.session.script_window_answer(first); + app.session.script_window_answer(first)?; + } + let mut later: Vec = events.filter_map(|e| queued(&w, &e)).collect(); + if deferred { + later.push(Queued::Cancel); } - let later: Vec = events.filter_map(|e| queued(&w, &e)).collect(); with_window(app, |d| d.queue.extend(later)); Ok(()) } @@ -782,6 +814,11 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Val if !ours { return None; } + // The parameters each method takes, checked before anything is set or given. + let keys: &[&str] = if method == "ui.dialog.set" { &["dialog", "field", "value", "fields", "action"] } else { &["dialog"] }; + if let Err(e) = Params(params).only(None, keys) { + return Some(Err(e)); + } let mut params = params.clone(); let action = if method == "ui.dialog.set" { params.as_object_mut().and_then(|o| o.remove("action")) } else { None }; let answer = match (method, action.as_ref().map(Value::as_str)) { @@ -790,7 +827,12 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Val (_, None) => None, (_, Some(_)) => return Some(Err("`action` must be confirm or cancel".into())), }; - if method == "ui.dialog.set" && params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog")) { + // A dialog open over it, such as the quit question, takes its answer first. + if answer == Some(true) && with_host(app, |host, _| host.stack().has_child(dialog_id(KIND))).unwrap_or(false) { + return Some(Err("the dialog refuses OK while a dialog open over it waits for its answer".into())); + } + // A set without an action sets a field, which the host's setter asks for when none is given. + if method == "ui.dialog.set" && (answer.is_none() || params.as_object().is_some_and(|o| o.keys().any(|k| k != "dialog"))) { let set = with_host(app, |host, ctx| craft::automation::dialogs::dialog_method(host, ctx, method, ¶ms)).flatten(); if let Some(Err(e)) = set { return Some(Err(e)); @@ -799,6 +841,12 @@ pub(crate) fn dialog_method(app: &mut VectorcraftApp, method: &str, params: &Val Some(match answer { Some(true) => confirm(app), Some(false) => cancel(app).map(|()| Value::Null), - None => Ok(Value::Null), + // A set answers with the dialog it set, `{id, parent, key, fields}`, as the other dialogs' sets do. + None => Ok(with_host(app, |host, _| { + let id = dialog_id(KIND).value().to_string(); + craft::automation::dialogs::inspect(host).as_array().and_then(|open| open.iter().find(|d| d["id"] == id.as_str()).cloned()) + }) + .flatten() + .unwrap_or(Value::Null)), }) } diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index e79e3d16eb..b63c35acfc 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -158,7 +158,7 @@ fn escape_keeps_the_dialog_open_until_the_script_closes_it() { type_text(&app, 1, "typed"); script_window::cancel(&mut app).unwrap(); assert!(is_open::(&app), "the dialog stays open"); - assert_eq!(queued(&app), vec![Queued::Close], "with the close after the typed text"); + assert_eq!(queued(&app), vec![Queued::Cancel], "with the cancel, which has no button to click and closes, after the typed text"); assert!(until_window(&mut app), "the script takes the text and waits again"); assert_eq!(app.session.script_window().unwrap().nodes[1].text, "typed"); step(&mut app, Vec::new()); @@ -819,6 +819,148 @@ fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { assert_eq!(log(&app), json!([[1, [1, 2]]]), "the arrow key picked pear, the click picked plum, and the script was told each time"); } +#[test] +fn a_click_on_a_list_box_row_gives_the_list_the_keyboard_focus() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['apple', 'pear', 'plum']); l.selection = 0; \ + var picked = []; l.onChange = function () { picked.push(l.selection.index); }; \ + w.add('button', undefined, 'OK'); vc.log([w.show(), picked]);", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let b = nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == egui::accesskit::Role::ListItem && n.label() == Some("pear")) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no pear row")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + assert!(until_window(&mut app), "the change handler runs"); + step(&mut app, vec![key(egui::Key::ArrowDown)]); + assert!(until_window(&mut app), "the change handler runs again"); + give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[1, [1, 2]]]), "the click picked pear, and the arrow key went on from it to plum"); +} + +#[test] +fn the_run_asks_its_question_over_the_dialog_only_while_no_popup_is_open_over_it() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('statictext', undefined, 'Size:'); w.add('dropdownlist', undefined, ['small', 'large']); \ + w.add('button', undefined, 'OK'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + assert!(crate::dialogs::script_run::can_ask(&app), "the question can open over the dialog alone"); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let b = nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == egui::accesskit::Role::ComboBox && n.label() == Some("Size:")) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no drop-down list")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(&mut app, vec![egui::Event::PointerMoved(at)]); + step(&mut app, vec![button(true)]); + step(&mut app, vec![button(false)]); + step(&mut app, Vec::new()); + assert!(script_window::is_top(&app), "no dialog is open over it"); + assert!(!crate::dialogs::script_run::can_ask(&app), "the drop-down list's popup is open over the dialog"); + step(&mut app, vec![key(egui::Key::Escape)]); + step(&mut app, Vec::new()); + assert!(crate::dialogs::script_run::can_ask(&app), "the popup closed"); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + +#[test] +fn queued_events_wait_while_the_quit_question_is_open_over_the_dialog() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + with_window(&app, |d| d.queue(&UiEvent::Click(3))).unwrap(); + crate::dialogs::script_run::ask_to_close(&mut app); + assert!(is_open::(&app)); + for _ in 0..4 { + step(&mut app, Vec::new()); + script_runs::poll(&mut app); + } + assert!(app.session.script_running(), "the run waits while the question is open"); + assert_eq!(queued(&app).len(), 1, "the click stays queued"); + cancel_close_question(&mut app); + step(&mut app, Vec::new()); + assert!(!until_window(&mut app), "the queued click on OK closes the dialog once the question is answered"); + assert_eq!(log(&app), json!([[1, "first"]])); +} + +#[test] +fn ui_dialog_requests_on_the_script_dialog_are_checked_as_on_other_dialogs() { + let mut app = app(); + start(&mut app, &format!("{FORM} vc.log([w.show(), name.text]);")); + assert!(until_window(&mut app)); + let ctx = app.ui_ctx.clone().unwrap(); + let run = |app: &mut VectorcraftApp, method: &str, params: Value| { + let (req, _) = ControlRequest::new(method, params); + let Reply::Done(r) = crate::control::handle(app, &ctx, &req) else { panic!("{method}: not done") }; + r + }; + run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "close"})); + // Confirm and cancel take only the dialog, and give nothing when asked with more. + let r = run(&mut app, "ui.dialog.confirm", json!({"field": "event", "value": "click"})); + assert_eq!(r["ok"], false, "{r}"); + let r = run(&mut app, "ui.dialog.cancel", json!({"value": 1})); + assert_eq!(r["ok"], false, "{r}"); + // A set names a field, or an action. + let r = run(&mut app, "ui.dialog.set", json!({})); + assert_eq!(r["ok"], false, "{r}"); + assert!(app.session.script_window().is_some(), "the refused requests gave the script nothing"); + // A set answers with the dialog it set. + let r = run(&mut app, "ui.dialog.set", json!({"field": "event", "value": "close"})); + assert_eq!(r["result"]["key"], KIND, "{r}"); + assert_eq!(r["result"]["fields"]["event"], "close", "{r}"); + // A dialog open over it takes its answer first. + crate::dialogs::script_run::ask_to_close(&mut app); + let id = open_id(&app, KIND).value().to_string(); + let r = run(&mut app, "ui.dialog.confirm", json!({"dialog": id})); + assert_eq!(r["ok"], false, "{r}"); + let r = run(&mut app, "ui.dialog.set", json!({"dialog": id, "action": "confirm"})); + assert_eq!(r["ok"], false, "{r}"); + assert!(app.session.script_window().is_some(), "the script still waits at its dialog"); + cancel_close_question(&mut app); + let r = run(&mut app, "ui.dialog.confirm", json!({})); + assert_eq!(r["ok"], true, "{r}"); + assert!(!until_window(&mut app)); + assert_eq!(log(&app), json!([[0, "first"]])); +} + +#[test] +fn a_cancel_after_a_typed_text_clicks_the_cancel_button_the_dialog_has_when_its_turn_comes() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); var e = w.add('edittext', undefined, 'a'); var c = w.add('button', undefined, 'Cancel'); \ + e.onChange = function () { c.enabled = false; }; vc.log([w.show(), e.text]);", + ); + assert!(until_window(&mut app)); + type_text(&app, 1, "typed"); + script_window::cancel(&mut app).unwrap(); + assert_eq!(queued(&app), vec![Queued::Cancel], "the cancel waits for the typed text"); + run_to_end(&mut app); + assert_eq!(log(&app), json!([[0, "typed"]]), "the disabled Cancel button is passed over for the close box"); +} + #[test] fn enter_with_the_focus_on_a_slider_clicks_the_default_button() { let mut app = app(); diff --git a/docs/mcp.md b/docs/mcp.md index c5e3117c1f..2ed41bda3b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3315,16 +3315,17 @@ its own and no `capture` handler on a container stopped the click; `click` handl capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case; a button found by its name or -title counts only while it is enabled and visible. A `show()` inside a handler, -or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. In -the app, `alert`, `confirm`, `prompt` and the file dialogs called from a handler also throw an `Error`; in a run with -nobody to ask, `alert`, `confirm` and `prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes. +title counts only while it is enabled and visible. A `show()` inside a handler while a dialog is showing, or of a +dialog that is showing, throws an `Error`. In the app, a `show()` inside a callback of a built-in function, a handler +that `notify` runs included, also throws an `Error`, and so do `alert`, `confirm`, `prompt` and the file dialogs called +from a handler; in a run with nobody to ask, such a `show()` takes a `window` answer, and `alert`, `confirm` and +`prompt` in a handler take their answers from `answers`. A shown dialog can be shown again after it closes. `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws -too, and a slider's minimum above its maximum. When a getter changes a list's items after the list was read, or -adds or removes a control after the controls were read, it reads the dialog again, and throws an `Error` when the -dialog changes again. It lays the controls out from each container's `orientation`, +too, and a slider's minimum above its maximum. When a getter changes a list's items or an item's text after the +list was read, or adds or removes a control after the controls were read, it reads the dialog again, and throws an +`Error` when the dialog changes again. It lays the controls out from each container's `orientation`, `alignChildren`, `spacing` and `margins` and each control's `alignment`, `preferredSize` (each side of `size` that is above 0 takes the place of `preferredSize`'s), `minimumSize`, `maximumSize` and `bounds`, which places it in its container. A control whose `visible` is false, and every control in it, takes no room in the layout. Sizes and places From c1d4192ae325d2a6d4ccc8ccf483d7acdf965ec3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 03:05:03 -0800 Subject: [PATCH 28/29] Scripts: a ScriptUI list box shows only the rows that fit its height at the height it draws them The list box counted its rows at 18 pixels each, while the list draws each row at the theme's control height, so a list box ran past its place and over the control below it, which then took clicks meant for the list's last row. --- crates/ui-egui/src/dialogs/script_window.rs | 20 ++++++++++--------- crates/ui-egui/src/tests/script_window.rs | 22 ++++++++++++--------- 2 files changed, 24 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index b9c0d7a996..122a9c3461 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -23,16 +23,18 @@ use craft::behavior::{Selection, SelectionChange, keyed}; use craft::theme::Variant; use craft::ui::buttons::Button; use craft::ui::choice::{Checkbox, Radio, RadioGroup}; -use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _, clicked}; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, RowHeight, Scroll, Show as _, ShowCollection as _, ShowContainer as _, clicked}; use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft::ui::display::{Progress, Text}; use craft::ui::layout_components::Stack; use craft::ui::list::{List, ListRow}; use craft::ui::pickers::Select; +use craft::ui::runtime::env::Env; use craft::ui::runtime::focus::Initial; use craft::ui::runtime::keys::take_submit; use craft::ui::runtime::overlay; use craft::ui::sections::{DialogRole, FooterButton, GroupBox}; +use craft::ui::style::StyleCx; use craft::ui::text::TextField; use craft::ui::value_drag::Slider; use egui::Ui; @@ -50,15 +52,13 @@ pub const KIND: &str = "scriptWindow"; /// The most of the dialog's content shown at once; a larger dialog scrolls. const MAX_SHOWN: egui::Vec2 = egui::vec2(960.0, 640.0); -/// The height of a list box row in the engine's layout, and the room the layout adds around the -/// rows. -const LIST_ROW: f32 = 18.0; +/// The room the engine's layout adds around a list box's rows. const LIST_PAD: f32 = 6.0; -/// How many rows a list box `height` tall shows; it scrolls the rest, inside the dialog's own -/// scroll. -fn list_rows(height: f32) -> u16 { - let rows = ((height - LIST_PAD) / LIST_ROW).floor(); +/// How many rows `row` tall a list box `height` tall shows; it scrolls the rest, inside the +/// dialog's own scroll. +fn list_rows(height: f32, row: f32) -> u16 { + let rows = ((height - LIST_PAD) / row).floor(); if rows.is_finite() { rows.clamp(1.0, f32::from(u16::MAX)) as u16 } else { 1 } } @@ -517,11 +517,13 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr // Screen readers read the box as a list box, by its name or the static text before // it, with the selected item as its value. The box has no opener to keep the keyboard // focus, so a press on a row gives it the focus and the arrow keys go on from that row. + // The rows it shows are as many as fit in its height at the height the list draws them. + let row = RowHeight::Control.of(&StyleCx::of_env(ui.ctx(), &Env::of(ui))); let out = List::::options(list_name(n, prompt)) .focus_on_press(true) .id_salt(salt) .enabled(enabled) - .max_rows(list_rows(n.rect.h)) + .max_rows(list_rows(n.rect.h, row)) .selection(Bind::given(selection)) .show_items(ui, &source, &mut |k, _| ListRow::new(n.items.get(*k).cloned().unwrap_or_default())); // A click activates a row; the arrow keys and typed letters select one. diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index b63c35acfc..ce2d29c999 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -801,14 +801,18 @@ fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { step(&mut app, Vec::new()); access_nodes(&mut app); let nodes = access_nodes(&mut app); - let b = nodes - .iter() - .map(|(_, n)| n) - .find(|n| n.role() == egui::accesskit::Role::ListItem && n.label() == Some("plum")) - .and_then(egui::accesskit::Node::bounds) - .unwrap_or_else(|| panic!("no plum row")); - // The top half of the row: the OK button below the list starts in the row's lower half. - let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, b.y0 as f32 + 4.0); + let bounds = |role: egui::accesskit::Role, label: Option<&str>| { + nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == role && (label.is_none() || n.label() == label)) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let (list, ok) = (bounds(egui::accesskit::Role::ListBox, None), bounds(egui::accesskit::Role::Button, Some("OK"))); + assert!(list.y1 <= ok.y0, "the list box ends above the OK button below it: {list:?} {ok:?}"); + let b = bounds(egui::accesskit::Role::ListItem, Some("apple")); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, ((b.y0 + b.y1) * 0.5) as f32); let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; step(&mut app, vec![egui::Event::PointerMoved(at)]); step(&mut app, vec![button(true)]); @@ -816,7 +820,7 @@ fn an_arrow_key_and_a_click_in_a_list_box_give_the_script_the_change() { assert!(until_window(&mut app), "the change handler runs again"); give(&mut app, json!({"event": "click", "control": "OK"})).unwrap(); assert!(!until_window(&mut app)); - assert_eq!(log(&app), json!([[1, [1, 2]]]), "the arrow key picked pear, the click picked plum, and the script was told each time"); + assert_eq!(log(&app), json!([[1, [1, 0]]]), "the arrow key picked pear, the click picked apple, and the script was told each time"); } #[test] From dbc31253dc649c37c2592376708be45699874c2b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 04:23:23 -0800 Subject: [PATCH 29/29] Scripts: ScriptUI controls are drawn at the place and size the dialog's layout gives them Buttons, static texts, edit fields, drop-down lists, sliders, progress bars and radio buttons were drawn at their own size inside their place, so a button given a larger preferredSize or bounds stayed small, and a control larger than its place ran over the next one. They are now drawn at their place. A check box is still shown in the flow of its place, which draws its text after the box. --- crates/ui-egui/src/dialogs/script_window.rs | 23 ++++++++----- crates/ui-egui/src/tests/script_window.rs | 38 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/dialogs/script_window.rs b/crates/ui-egui/src/dialogs/script_window.rs index 122a9c3461..a2ca70446d 100644 --- a/crates/ui-egui/src/dialogs/script_window.rs +++ b/crates/ui-egui/src/dialogs/script_window.rs @@ -476,18 +476,19 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr UiKind::Group => shown.container = Some(group(ui, rect, n, enabled)), UiKind::Panel => shown.container = Some(panel(ui, rect, n, enabled)), UiKind::StaticText => { - Text::new(n.text.clone()).show(ui); + Text::new(n.text.clone()).show_at(ui, rect); } UiKind::Button => { let mut button = Button::new(n.text.clone()).id_salt(salt).enabled(enabled); if place.default { button = button.variant(Variant::PRIMARY).default_stop(); } - if clicked(&button.show(ui)) { + if clicked(&button.show_at(ui, rect)) { shown.event = Some(UiEvent::Click(i)); } } UiKind::CheckBox => { + // A check box is shown in the flow of its place, which draws its text after the box. let out = Checkbox::new(Bind::given(n.checked)).label(n.text.clone()).id_salt(salt).enabled(enabled).show(ui); if out.events.committed().is_some() { shown.event = Some(UiEvent::Click(i)); @@ -495,17 +496,17 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr } UiKind::RadioButton => { let mut picked = false; - let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show(ui, |ui, _| { + let out = RadioGroup::new(n.text.clone(), Bind::given(n.checked)).id_salt(salt).enabled(enabled).show_at(ui, rect, |ui, _| { picked = clicked(&Radio::new(true).label(n.text.clone()).enabled(enabled).show(ui)); }); if picked || out.events.committed().is_some() { shown.event = Some(UiEvent::Click(i)); } } - UiKind::EditText => shown = edit(ui, drafts, enabled, (i, n, prompt)), + UiKind::EditText => shown = edit(ui, rect, drafts, enabled, (i, n, prompt)), UiKind::DropDownList => { let entries: Vec>> = n.items.iter().enumerate().map(|(k, item)| Entry::new(Some(k), item.clone())).collect(); - let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show(ui); + let out = Select::new(list_name(n, prompt), Bind::given(n.selection), &entries).id_salt(salt).enabled(enabled).show_at(ui, rect); if let Some(k) = out.events.committed().copied().filter(|k| *k != n.selection) { shown.event = Some(UiEvent::Change(i, UiValue::Index(k))); } @@ -539,13 +540,17 @@ fn control(ui: &mut Ui, drafts: &BTreeMap, place: &Place, (i, n, pr } } UiKind::Slider => { - let out = Slider::new(Bind::given(n.value), n.min..=n.max).label(screen_reader_name(n, prompt)).id_salt(salt).enabled(enabled).show(ui); + let out = Slider::new(Bind::given(n.value), n.min..=n.max) + .label(screen_reader_name(n, prompt)) + .id_salt(salt) + .enabled(enabled) + .show_at(ui, rect); if let Some(v) = out.events.committed().copied().filter(|v| *v != n.value) { shown.event = Some(UiEvent::Change(i, UiValue::Number(v))); } } UiKind::ProgressBar => { - Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show(ui); + Progress::new(n.fraction()).label(screen_reader_name(n, prompt)).id_salt(salt).show_at(ui, rect); } }); shown @@ -603,7 +608,7 @@ pub(crate) const DRAFT_CHARS: usize = 2 * MAX_TEXT_BYTES; /// An edit field: its text is kept in the dialog while it is typed and given to the script when /// the field loses the focus, or at Enter in a one-line field. -fn edit(ui: &mut Ui, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { +fn edit(ui: &mut Ui, rect: egui::Rect, drafts: &BTreeMap, enabled: bool, (i, n, prompt): (usize, &UiNode, &str)) -> Shown { let mut text = drafts.get(&n.id).cloned().unwrap_or_else(|| n.text.clone()); let mut field = TextField::new(screen_reader_name(n, prompt), Bind::bound(&mut text)) .limit(DRAFT_CHARS) @@ -613,7 +618,7 @@ fn edit(ui: &mut Ui, drafts: &BTreeMap, enabled: bool, (i, n, promp if n.multiline { field = field.lines(3); } - let out = field.show(ui); + let out = field.show_at(ui, rect); let focused = out.response.has_focus(); let mut draft = (out.events.value().is_some() || text != n.text).then(|| Some(text.clone())); let committed = out.submitted || out.events.committed().is_some() || out.response.lost_focus(); diff --git a/crates/ui-egui/src/tests/script_window.rs b/crates/ui-egui/src/tests/script_window.rs index ce2d29c999..b605447733 100644 --- a/crates/ui-egui/src/tests/script_window.rs +++ b/crates/ui-egui/src/tests/script_window.rs @@ -855,6 +855,44 @@ fn a_click_on_a_list_box_row_gives_the_list_the_keyboard_focus() { assert_eq!(log(&app), json!([[1, [1, 2]]]), "the click picked pear, and the arrow key went on from it to plum"); } +#[test] +fn controls_are_drawn_at_the_size_the_script_gave_them() { + let mut app = app(); + start( + &mut app, + "var w = new Window('dialog'); w.add('button', undefined, 'Wide').preferredSize = [240, 60]; var e = w.add('edittext', undefined, 'a'); \ + e.preferredSize = [200, -1]; w.add('checkbox', undefined, 'Remember the size'); w.add('button', undefined, 'OK'); vc.log(w.show());", + ); + assert!(until_window(&mut app)); + step(&mut app, Vec::new()); + access_nodes(&mut app); + let nodes = access_nodes(&mut app); + let bounds = |role: egui::accesskit::Role, label: Option<&str>| { + nodes + .iter() + .map(|(_, n)| n) + .find(|n| n.role() == role && (label.is_none() || n.label() == label)) + .and_then(egui::accesskit::Node::bounds) + .unwrap_or_else(|| panic!("no {role:?} {label:?}")) + }; + let w = app.session.script_window().unwrap(); + let (wide, ok, field) = ( + bounds(egui::accesskit::Role::Button, Some("Wide")), + bounds(egui::accesskit::Role::Button, Some("OK")), + bounds(egui::accesskit::Role::TextInput, None), + ); + assert!(wide.width() > ok.width() && wide.height() > ok.height(), "the wide button is larger than OK: {wide:?} {ok:?}"); + assert!((wide.width() - f64::from(w.nodes[1].rect.w)).abs() < 1.0, "the wide button is as wide as its preferred size: {wide:?}"); + assert!((field.width() - f64::from(w.nodes[2].rect.w)).abs() < 1.0, "the field is as wide as its preferred size: {field:?}"); + let (check, caption) = (bounds(egui::accesskit::Role::CheckBox, None), bounds(egui::accesskit::Role::Label, Some("Remember the size"))); + assert!( + caption.x0 >= check.x1 && caption.y0 < check.y1 && caption.y1 > check.y0, + "the check box shows its text after the box: {check:?} {caption:?}" + ); + app.session.script_request_stop(); + assert!(!until_window(&mut app)); +} + #[test] fn the_run_asks_its_question_over_the_dialog_only_while_no_popup_is_open_over_it() { let mut app = app();