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