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