diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 6729537b5a..1c569c99a3 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify acts as a click or change, addEventListener and removeEventListener take click, change, changing and show (other event types throw that they are not available yet), and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), installed?: true or false (default false; true with a path that script.listInstalled gave: the file is read once, checked as File › Scripts checks it, and that text runs, its #include lines and $.evalFile reading in the folder that read found; a file that is no longer a listed script ends with \"the script is no longer in the Scripts folder\" and nothing runs), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt|window, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt) | [{control, event: click} | {control, event: change, value: text, number, item index or null} | {event: close}] (window: the steps of one show(), control being a control's name, else its text)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file of the code that reads it (the file being run for code that eval or Function compiled; empty for code compiled from a script given as text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; new Window(\"dialog\", title) builds a ScriptUI dialog with add(type, bounds, text or items or value, properties) for group, panel, statictext, edittext, button, checkbox, radiobutton, dropdownlist, listbox (one selection), slider and progressbar (a group takes properties third, and a list may take them there with properties.items), at most 512 controls 16 deep, 1024 list items and 16 KiB a text (other types, palettes, windows and resource strings throw that they are not available yet); preferredSize, size, minimumSize and maximumSize start with width and height -1 (left to the layout), lists have find and remove, containers remove, radio buttons added one after another turn each other off, notify runs a click's or a change's handlers without closing the dialog, addEventListener and removeEventListener take click, change, changing and show (show on the dialog only; at most 256 listeners a window or control; other event types throw that they are not available yet), a removed control leaves the dialog, and Window.alert, Window.confirm and Window.prompt are alert, confirm and prompt; show() waits like a dialog function, runs onClick, onChanging, onChange, onShow, onClose and the listeners in the run's fuel, and returns close(result)'s result, 1 for the default button (OK by name or text) and 2 for the cancel button (Cancel) when they have no onClick or click listener and no capturing listener stopped the click, or 0 for the close box; a show() inside a handler throws, and a run with nobody to ask takes a window answer and ends when a step is missing, is for a control the dialog lacks or cannot take, or is left unused; vc.api.has(\"scriptui\") is true; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; on Unix setting hidden renames the file, or a link itself, with one dot added or its leading dots taken off (both names must be places the script writes; a name in use, a name of dots alone or a folder gives error), and createAlias(target) makes a symbolic link at the object's path, a place the script writes where nothing is, to the real path of a file the script reads, and returns true (a link that leads out afterward is refused like any other path, and writing through a link needs its file to be a place the script writes); on Windows setting hidden and createAlias set error and change nothing; execute returns false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofSetup.save, view.proofSetup.load, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message (not window), title, errorIcon (alert), noAsDefault (confirm), preset (prompt), controls and events (window), answer: \"ok\" | true | false | text | null | show()'s result (window) | \"stop\" | \"missing\" | \"error\" (window)}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), diff --git a/crates/engine/src/script/scriptui.rs b/crates/engine/src/script/scriptui.rs index f3520b41cc..11475fb832 100644 --- a/crates/engine/src/script/scriptui.rs +++ b/crates/engine/src/script/scriptui.rs @@ -617,28 +617,30 @@ fn layout(d: &mut ScriptUiDialog) { let [w, h] = size[k]; let h_align = kid.alignment.0.or(node.align_children.0).unwrap_or(Align::Center); let v_align = kid.alignment.1.or(node.align_children.1).unwrap_or(Align::Center); - let place = |align: Align, own: f32, room: f32| match align { + let max = kid.max_size; + // A control that fills its container's room stays within its maximum. + let place = |align: Align, own: f32, room: f32, axis: usize| match align { Align::Start => (0.0, own), Align::End => ((room - own).max(0.0), own), Align::Center => (((room - own) / 2.0).max(0.0), own), - Align::Fill => (0.0, room.max(own)), + Align::Fill => (0.0, max[axis].map_or(room.max(own), |m| room.max(own).min(m.max(own)))), }; match node.orientation { Orientation::Row => { - let (dy, kh) = place(v_align, h, ch); + let (dy, kh) = place(v_align, h, ch, 1); let r = UiRect { x: x + cursor, y: y + dy, w, h: kh }; cursor += w + node.spacing; r } Orientation::Column => { - let (dx, kw) = place(h_align, w, cw); + let (dx, kw) = place(h_align, w, cw, 0); let r = UiRect { x: x + dx, y: y + cursor, w: kw, h }; cursor += h + node.spacing; r } Orientation::Stack => { - let (dx, kw) = place(h_align, w, cw); - let (dy, kh) = place(v_align, h, ch); + let (dx, kw) = place(h_align, w, cw, 0); + let (dy, kh) = place(v_align, h, ch, 1); UiRect { x: x + dx, y: y + dy, w: kw, h: kh } } } diff --git a/crates/engine/src/tests/script_scriptui.rs b/crates/engine/src/tests/script_scriptui.rs index 7536020534..e572d01f64 100644 --- a/crates/engine/src/tests/script_scriptui.rs +++ b/crates/engine/src/tests/script_scriptui.rs @@ -327,6 +327,12 @@ fn a_control_s_size_keeps_within_its_minimum_and_maximum() { assert_eq!(d.nodes[2].rect.h, 60.0, "the minimum height holds over the estimate"); let plain: ScriptUiDialog = scriptui::parse(&description(vec![dialog, node("button", 0.0)])).unwrap(); assert!(plain.nodes[1].rect.h < 60.0 && plain.nodes[1].rect.w > 0.0, "a size of -1 leaves the side to the estimate"); + let column = with(with(node("dialog", -1.0), "orientation", Data::String("column".into())), "size", pair(300.0, -1.0)); + let fill = |n: Data| with(n, "alignment", Data::String("fill".into())); + let capped = with(fill(node("button", 0.0)), "max", pair(90.0, -1.0)); + let d: ScriptUiDialog = scriptui::parse(&description(vec![column, capped, fill(node("button", 0.0))])).unwrap(); + assert!(d.nodes[2].rect.w > 90.0, "a control that fills its column takes the column's width"); + assert_eq!(d.nodes[1].rect.w, 90.0, "a control that fills its column stays within its maximum width"); } #[test] diff --git a/crates/js/src/scriptui.rs b/crates/js/src/scriptui.rs index 76d4911632..912de3e685 100644 --- a/crates/js/src/scriptui.rs +++ b/crates/js/src/scriptui.rs @@ -9,20 +9,25 @@ //! `checkbox`, `radiobutton`, `dropdownlist`, `listbox` (whose third argument is an array of item //! texts), `slider` (third to fifth: value, minimum, maximum) and `progressbar` (value, maximum). //! The other documented control types throw an `Error` that says they are not available yet. A -//! group takes its creation properties as the third argument, and a list takes them there in place -//! of its items, with the items in `properties.items`. A list's `add("item", text)` adds an item, -//! `find(text)` finds one and `remove(what)` removes one; its `selection` is an item or `null`, and -//! takes an item, an index or `null`. A container's `remove(what)` removes a control. Each element -//! starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose `width` and -//! `height` are -1, which leaves the size to the layout. Setting a radio button's `value` to true -//! sets the other radio buttons next to it in its container to false, as a click does. +//! group takes its creation properties as the third argument (or the fourth when the third is not +//! an object), and a list takes them there in place of its items, with the items in +//! `properties.items`. A list's `add("item", text)` adds an item, `find(text)` finds one and +//! `remove(what)` removes one; its `selection` is an item or `null`, and takes an item, an index or +//! `null`. A container's `remove(what)` removes a control, which then has no `parent` and no longer +//! belongs to the dialog: `add` and `remove` on it, or on a control it holds, throw an `Error`. +//! Each element starts with `preferredSize`, `size`, `minimumSize` and `maximumSize` objects whose +//! `width` and `height` are -1, which leaves the size to the layout. Setting a radio button's +//! `value` to true sets the other radio buttons next to it in its container to false, as a click +//! does. //! //! `addEventListener(type, handler[, capture])` and `removeEventListener` register handlers for -//! the events `show()` runs: `click`, `change`, `changing` and `show`. A handler gets an event -//! object, in the capture phase on the containers above the control, then on the control after its -//! `onClick`, `onChange` or `onChanging`, then in the bubbling phase on the containers again, until -//! one calls `stopPropagation()`. `notify(event)` runs the same handlers, and `notify("onClick")` -//! turns a check box over and turns a radio button on first. `Window.alert`, `Window.confirm` and +//! the events `show()` runs: `click`, `change`, `changing`, and `show` on a dialog only; a window +//! or control takes at most [`MAX_LISTENERS`] of them. A handler gets an event object, in the +//! capture phase on the containers above the control, then on the control after its `onClick`, +//! `onChange` or `onChanging`, then in the bubbling phase on the containers again, until one calls +//! `stopPropagation()`. Events are not cancelable, and `preventDefault()` does nothing. +//! `notify(event)` runs the same handlers, and `notify("onClick")` turns a check box over and turns +//! a radio button on first; it does not close the dialog. `Window.alert`, `Window.confirm` and //! `Window.prompt` are the global functions of those names, when the host defines them. //! //! `show()` gives the host's `open` the dialog's description and runs `onShow`. Then, until the @@ -30,20 +35,23 @@ //! person did, which may pause the run ([`crate::interp::Pause`]): a `click` on a control, a //! `change` with its new value, or a `close`. The control takes the change, its `onClick`, //! `onChanging` or `onChange` runs, and the next description shows what the handler changed. A -//! button without `onClick` closes the dialog with 1 when it is the dialog's default element and -//! with 2 when it is its cancel element. `close(result)` closes the dialog after the running handler -//! returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps the dialog -//! open when it returns `false`. A dialog that is showing cannot be shown again, and no other dialog -//! can be shown while one is. When `show()` ends, the host's `end` is given its result and whether -//! it ended normally. +//! button without `onClick` and without a `click` listener of its own closes the dialog with 1 when +//! it is the dialog's default element and with 2 when it is its cancel element, unless a capturing +//! listener on a container stopped the click. `close(result)` closes the dialog after the running +//! handler returns, and `show()` gives `result`, or 0 without one; `onClose` runs first and keeps +//! the dialog open when it returns `false`. A dialog that is showing cannot be shown again, and no +//! other dialog can be shown while one is. When `show()` ends, the host's `end` is given its result +//! and whether it ended normally. //! //! An element keeps its kind, its container, its controls and a list's items in properties that a //! script cannot change. The description lists the dialog first and every control after the //! container that holds it; it is read with a loop, and a dialog with more than [`MAX_CONTROLS`] //! controls, nested more than [`MAX_DEPTH`] deep, with more than [`MAX_ITEMS`] list items, or with a -//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These are VectorCraft's own limits. A -//! getter that changes a list's items after the list was read makes `show()` read the dialog again, -//! and a list that changes again throws an `Error`. +//! text longer than [`MAX_TEXT_BYTES`] throws a `RangeError`. These and [`MAX_LISTENERS`] are +//! VectorCraft's own limits. A getter that changes a list's items after the list was read makes +//! `show()` read the dialog again, and a list that changes again throws an `Error`. A `text` getter +//! that changes a list or a container while `remove(text)` looks for an item or a control makes +//! `remove` throw an `Error`. use crate::HostItem; use crate::builtins::{arg, constructor, data, method, native, pausable_method}; @@ -60,6 +68,8 @@ pub const MAX_DEPTH: usize = 16; pub const MAX_ITEMS: usize = 1024; /// The most bytes (UTF-8) of one text in a dialog: a control's text or name, or a list item's. pub const MAX_TEXT_BYTES: usize = 16 << 10; +/// The most event listeners one window or control holds. +pub const MAX_LISTENERS: usize = 256; /// The control types `add` makes. pub const BUILT: [&str; 11] = @@ -82,7 +92,6 @@ const LIST: &str = "__vcList"; const VALUE: &str = "__vcValue"; const LISTENERS: &str = "__vcListeners"; const STOPPED: &str = "__vcStopped"; -const PREVENTED: &str = "__vcPrevented"; /// The size properties every element starts with, as objects with `width` and `height`. const SIZES: [&str; 4] = ["preferredSize", "size", "minimumSize", "maximumSize"]; @@ -120,6 +129,8 @@ pub(crate) struct Classes { radio_get: ObjId, radio_set: ObjId, showing: Option, + /// The event objects whose listeners are running, innermost last. + dispatching: Vec, } impl Classes { @@ -138,14 +149,17 @@ impl Classes { self.radio_set, ]; all.extend(self.showing); + all.extend(self.dispatching.iter().copied()); all } } -/// Forgets the dialog that was showing when a run ended where it was. +/// Forgets the dialog that was showing, and the events that were running, when a run ended where +/// it was. pub(crate) fn end_run(i: &mut Interp) { if let Some(c) = i.script_ui.as_mut() { c.showing = None; + c.dispatching.clear(); } } @@ -209,6 +223,15 @@ fn element(i: &mut Interp, this: &Value, what: &str) -> JsResult<(ObjId, String) } } +/// The dialog that holds the element `o`, or an `Error` naming `what` for a control that was +/// removed from its dialog. +fn window_of(i: &mut Interp, o: ObjId, what: &str) -> JsResult { + match object_slot(i, o, WINDOW)? { + Some(w) => Ok(w), + None => Err(error(i, &format!("{what}: the control was removed from its dialog"))), + } +} + /// Are `a` and `b` the same object? fn same(a: &Value, b: &Value) -> bool { matches!((a.as_object(), b.as_object()), (Some(x), Some(y)) if x == y) @@ -380,6 +403,7 @@ fn number_arg(i: &mut Interp, v: &Value, what: &str) -> JsResult { /// `container.add(type[, bounds, text, properties])` and `list.add("item", text)`. fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "add")?; + window_of(i, o, "add")?; let ty = i.to_str(&arg(args, 0))?.to_rust_string(); if kind == "dropdownlist" || kind == "listbox" { if ty.to_lowercase() != "item" { @@ -402,7 +426,7 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult if depth > MAX_DEPTH { return Err(range(i, &format!("add: controls can be nested at most {MAX_DEPTH} deep"))); } - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a control without its window".into())) }; + let win = window_of(i, o, "add")?; let count = number_slot(i, win, COUNT)?; if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); @@ -415,8 +439,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult None => false, }) }; - // A group takes its creation properties third, and so may a list in place of its items. - let props_third = ty == "group" || (list_kind && third.as_object().is_some() && !is_array(i, &third)?); + // A group takes its creation properties third, and so may a list in place of its items; when + // the third argument is not an object, they are the fourth. + let props_third = third.as_object().is_some() && (ty == "group" || (list_kind && !is_array(i, &third)?)); let props = if props_third { third.clone() } else { arg(args, 3) }; let proto = classes(i)?.control_proto; let mark = i.temp_roots.len(); @@ -491,7 +516,9 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult _ => return Err(i.type_error("add: give a list's items as an array")), } } - // A getter or a conversion above may have added controls or items itself. + // A getter or a conversion above may have added controls or items itself, or removed the + // container from its dialog. + window_of(i, o, "add")?; let count = number_slot(i, win, COUNT)?; if count as usize >= MAX_CONTROLS { return Err(range(i, &format!("add: a dialog can hold at most {MAX_CONTROLS} controls"))); @@ -511,10 +538,10 @@ fn add(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult /// Adds an item with `text` to the list `o`, which the dialog holds. fn add_item(i: &mut Interp, o: ObjId, text: &Value) -> JsResult { - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; // The conversion runs first: it may add or remove items itself. let text = text_arg(i, text)?; i.rooted(std::slice::from_ref(&text), |i| { + let win = window_of(i, o, "add")?; let count = number_slot(i, win, ITEM_COUNT)?; if count as usize >= MAX_ITEMS { return Err(range(i, &format!("add: a dialog's lists hold at most {MAX_ITEMS} items in all"))); @@ -624,7 +651,7 @@ fn item_to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult fn remove_all(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let o = list_of(i, &this, "removeAll")?; let n = items_of(i, o)?.len() as f64; - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("a list without its window".into())) }; + let win = window_of(i, o, "removeAll")?; let count = number_slot(i, win, ITEM_COUNT)?; set_slot(i, win, ITEM_COUNT, Value::Number((count - n).max(0.0)))?; let kept = list(i, &[], false)?; @@ -748,8 +775,11 @@ fn event_type(i: &mut Interp, v: &Value, what: &str) -> JsResult<&'static str> { /// `addEventListener(type, handler[, capture])`. fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { - let (o, _) = element(i, &this, "addEventListener")?; + let (o, kind) = element(i, &this, "addEventListener")?; let ty = event_type(i, &arg(args, 0), "addEventListener")?; + if ty == "show" && kind != "dialog" { + return Err(error(i, "addEventListener: the event show runs only on a dialog")); + } let f = arg(args, 1); if !i.is_callable(&f) { return Err(i.type_error("addEventListener: give the handler as a function")); @@ -757,6 +787,9 @@ fn add_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) -> J let capture = arg(args, 2).truthy(); let mut all = listeners_of(i, o)?; if !all.iter().any(|(t, g, c)| is_type(t, ty) && same(g, &f) && *c == capture) { + if all.len() >= MAX_LISTENERS { + return Err(range(i, &format!("addEventListener: a window or control takes at most {MAX_LISTENERS} listeners"))); + } all.push((Value::str(ty), f, capture)); set_listeners(i, o, &all)?; } @@ -778,20 +811,17 @@ fn remove_event_listener(i: &mut Interp, this: Value, args: &[Value], _: bool) - Ok(Value::Undefined) } +/// `event.stopPropagation()`: stops an event whose listeners are running; it does nothing to any +/// other object. fn event_stop(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - if let Some(o) = this.as_object() { + if let Some(o) = this.as_object() + && classes(i)?.dispatching.contains(&o) + { set_slot(i, o, STOPPED, Value::Bool(true))?; } Ok(Value::Undefined) } -fn event_prevent(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - if let Some(o) = this.as_object() { - set_slot(i, o, PREVENTED, Value::Bool(true))?; - } - Ok(Value::Undefined) -} - /// Runs the listeners for `ty` on `at` (only those for `capture` unless it is `None`), with `event`. fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, event: ObjId, phase: f64) -> JsResult { let wanted: Vec = @@ -811,7 +841,9 @@ fn run_listeners(i: &mut Interp, at: ObjId, ty: &str, capture: Option, eve /// Runs the event `ty` on the element `target`: the listeners of the containers above it that /// capture, its `callback`, its own listeners, then the listeners of the containers that do not -/// capture, until one stops it. → whether the element had a callback or a listener for it. +/// capture, until one stops it. → whether the event was handled: the element had a callback or a +/// listener for it, or a capturing listener above it stopped it. Listeners of the containers that +/// do not capture do not count. fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult { let mut above = Vec::new(); let mut at = object_slot(i, target, PARENT)?; @@ -823,6 +855,20 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult let proto = classes(i)?.event_proto; i.reserve_heap(OBJECT_BYTES.saturating_add(PROP_BYTES.saturating_mul(10)))?; let event = i.heap.alloc_object(Object::new(Class::Ordinary, Some(proto))); + if let Some(c) = i.script_ui.as_mut() { + c.dispatching.push(event); + } + let r = run_event(i, event, target, &above, ty, callback); + if let Some(c) = i.script_ui.as_mut() + && let Some(n) = c.dispatching.iter().rposition(|e| *e == event) + { + c.dispatching.remove(n); + } + r +} + +/// The phases of [`dispatch`] for the event object `event`. +fn run_event(i: &mut Interp, event: ObjId, target: ObjId, above: &[ObjId], ty: &str, callback: &str) -> JsResult { i.rooted(&[Value::Object(event)], |i| { let bubbles = ty != "show"; set_open(i, event, "type", Value::str(ty))?; @@ -834,13 +880,13 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult for p in above.iter().rev() { run_listeners(i, *p, ty, Some(true), event, 1.0)?; if stopped(i)? { - return Ok(false); + return Ok(true); } } let had = handler(i, target, callback)?.is_some(); let heard = run_listeners(i, target, ty, None, event, 2.0)?; if bubbles && !stopped(i)? { - for p in &above { + for p in above { run_listeners(i, *p, ty, Some(false), event, 3.0)?; if stopped(i)? { break; @@ -852,7 +898,7 @@ fn dispatch(i: &mut Interp, target: ObjId, ty: &str, callback: &str) -> JsResult } /// A click on the control `c` of `kind`: a check box turns over and a radio button turns on, then -/// the click runs. → whether the control had a callback or a listener for it. +/// the click runs. → whether the click was handled, as [`dispatch`] says. fn click_control(i: &mut Interp, c: ObjId, kind: &str) -> JsResult { if kind == "checkbox" { let on = i.get_value(&Value::Object(c), &key("value"))?.truthy(); @@ -938,9 +984,15 @@ fn subtree_counts(i: &mut Interp, c: &Value) -> JsResult<(f64, f64)> { fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, kind) = element(i, &this, "remove")?; let what = arg(args, 0); - let Some(win) = object_slot(i, o, WINDOW)? else { return Err(Abrupt::Internal("an element without its window".into())) }; + window_of(i, o, "remove")?; if kind == "dropdownlist" || kind == "listbox" { - let (mut items, at) = index_named(i, &what, |i| items_of(i, o))?; + let before = slot(i, o, ITEMS)?; + let (mut items, at) = i.rooted(std::slice::from_ref(&before), |i| index_named(i, &what, |i| items_of(i, o)))?; + // A `text` getter read during the lookup may have changed the list or removed it. + if !same(&slot(i, o, ITEMS)?, &before) { + return Err(error(i, "remove: the list changed while the item was looked up")); + } + let win = window_of(i, o, "remove")?; let Some(at) = at else { return Ok(Value::Undefined) }; items.remove(at); i.rooted(&items.clone(), |i| { @@ -961,7 +1013,13 @@ fn remove(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult JsResult<()> { + let Some(root) = c.as_object() else { return Ok(()) }; + set_slot(i, root, PARENT, Value::Null)?; + set_open(i, root, "parent", Value::Null)?; + let mut stack = vec![c.clone()]; + while let Some(v) = stack.pop() { + i.use_fuel()?; + let Some(o) = v.as_object() else { continue }; + set_slot(i, o, WINDOW, Value::Null)?; + stack.extend(kids_of(i, o)?); + } + Ok(()) +} + fn control_show(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { let (o, _) = element(i, &this, "show")?; i.put(o, key("visible"), Value::Bool(true), true)?; @@ -1504,6 +1579,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul radio_get, radio_set, showing: None, + dispatching: Vec::new(), }); let window = native(i, "Window", window_ctor, 4, NativeKind::Plain, true)?; constructor(i, "Window", window, window_proto)?; @@ -1533,7 +1609,7 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul method(i, control_proto, "show", control_show, 0)?; method(i, control_proto, "hide", control_hide, 0)?; method(i, event_proto, "stopPropagation", event_stop, 0)?; - method(i, event_proto, "preventDefault", event_prevent, 0)?; + method(i, event_proto, "preventDefault", nothing, 0)?; method(i, item_proto, "toString", item_to_string, 0)?; let index = native(i, "index", item_index, 0, NativeKind::Plain, false)?; i.define(item_proto, key("index"), Prop::Accessor { get: Some(index), set: None, flags: 0 })?; diff --git a/crates/js/src/scriptui_tests.rs b/crates/js/src/scriptui_tests.rs index 5ee096a608..4847ba5ac3 100644 --- a/crates/js/src/scriptui_tests.rs +++ b/crates/js/src/scriptui_tests.rs @@ -494,3 +494,87 @@ fn a_radio_button_turned_on_turns_off_the_others_of_its_set() { "a radio button after another kind of control starts a new set" ); } + +#[test] +fn a_click_on_a_radio_button_turns_off_only_the_radio_buttons_of_its_set() { + let (mut r, _, _) = realm(vec![click(4), close()]); + let source = "var w = new Window('dialog'); var r1 = w.add('radiobutton', undefined, 'A'); w.add('statictext', undefined, 'Other'); \ + var r2 = w.add('radiobutton', undefined, 'B'); var r3 = w.add('radiobutton', undefined, 'C'); r1.value = true; r2.value = true; \ + [w.show(), r1.value, r2.value, r3.value].join()"; + assert_eq!(r.run(source).unwrap(), JsValue::String("0,true,false,true".into())); +} + +#[test] +fn a_group_takes_its_creation_properties_fourth_after_an_empty_third_argument() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run("var g = new Window('dialog').add('group', undefined, undefined, {name: 'g', orientation: 'column'}); [g.name, g.orientation].join()") + .unwrap(); + assert_eq!(v, JsValue::String("g,column".into())); +} + +#[test] +fn a_capturing_listener_that_stops_a_click_keeps_the_default_button_open() { + let (mut r, _, _) = realm(vec![click(1), close()]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var log = []; \ + w.addEventListener('click', function (e) { log.push('stopped'); e.stopPropagation(); }, true); [w.show(), log.join()].join('|')"; + assert_eq!(r.run(source).unwrap(), JsValue::String("0|stopped".into())); + let (mut r, _, _) = realm(vec![click(1)]); + let source = "var w = new Window('dialog'); w.add('button', undefined, 'OK'); var seen = 0; \ + w.addEventListener('click', function () { seen++; }); [w.show(), seen].join()"; + assert_eq!( + r.run(source).unwrap(), + JsValue::String("1,1".into()), + "a listener on the dialog that does not capture leaves the default button to close it" + ); +} + +#[test] +fn listeners_are_limited_show_is_the_dialog_s_and_stop_propagation_reaches_only_running_events() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var b = w.add('button'); \ + for (var n = 0; n < 256; n++) b.addEventListener('click', function () {}); \ + var more; try { b.addEventListener('click', function () {}); more = 'added'; } catch (e) { more = e.name; } \ + var shown; try { b.addEventListener('show', function () {}); shown = 'added'; } catch (e) { shown = e.message; } \ + var kept, o = Object.freeze({}); var c = w.add('button'); c.addEventListener('click', function (e) { kept = e; }); c.notify(); \ + kept.stopPropagation.call(o); kept.stopPropagation(); kept.preventDefault(); \ + [more, shown, Object.getOwnPropertyNames(o).length, kept.cancelable].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("RangeError|addEventListener: the event show runs only on a dialog|0|false".into())); +} + +#[test] +fn a_removed_control_leaves_its_dialog() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); w.add('statictext'); var g = w.add('group'); var b = g.add('button', undefined, 'Go'); var heard = 0; \ + w.addEventListener('click', function () { heard++; }, true); w.addEventListener('click', function () { heard++; }); \ + w.remove(g); b.notify('onClick'); var errors = []; \ + try { g.remove(0); } catch (e) { errors.push(e.message); } try { g.add('button'); } catch (e) { errors.push(e.message); } \ + var added = 0; try { while (true) { w.add('button'); added++; } } catch (e) {} \ + [g.parent, heard, added, errors.join(';')].join('|')", + ) + .unwrap(); + assert_eq!( + v, + JsValue::String("|0|511|remove: the control was removed from its dialog;add: the control was removed from its dialog".into()), + "a removed group's controls no longer count toward the dialog's limit and cannot be counted off it twice" + ); +} + +#[test] +fn a_text_getter_that_changes_a_list_while_remove_looks_it_up_makes_remove_throw() { + let (mut r, _, _) = realm(Vec::new()); + let v = r + .run( + "var w = new Window('dialog'); var l = w.add('listbox', undefined, ['a', 'b', 'c']); \ + Object.defineProperty(l.items[0], 'text', {get: function () { l.remove(1); return 'a'; }}); \ + var m; try { l.remove('c'); m = 'removed'; } catch (e) { m = e.message; } [m, l.items.length, l.items[1].text].join('|')", + ) + .unwrap(); + assert_eq!(v, JsValue::String("remove: the list changed while the item was looked up|2|c".into())); +} diff --git a/docs/mcp.md b/docs/mcp.md index 88a9489bc2..63813fbe7f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2909,8 +2909,9 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `listbox`, `slider` and `progressbar`. After `bounds`, a text control takes its text and `properties` (`name`, and `multiline` and `readonly` for `edittext`), a list takes an array of item texts, a `slider` takes its value, minimum and maximum (0 and 100 when left out), and a `progressbar` its value and maximum. A `group` takes - `properties` right after `bounds`, and a list may take `properties` there in place of its items, with the item - texts in `properties.items`; a list given items both ways throws a `TypeError`. The `alignment` in `properties`, + `properties` right after `bounds`, or after an empty third argument, and a list may take `properties` right + after `bounds` in place of its items, with the item texts in `properties.items`; a list given items both ways + throws a `TypeError`. The `alignment` in `properties`, and a container's `orientation`, `alignChildren`, `spacing` and `margins` there, are the control's first values (VectorCraft's own rule). A `listbox` with `multiselect` and the other control types (`tabbedpanel`, `tab`, `scrollbar`, `image`, `iconbutton`, `treeview` and the rest) throw that they are not available yet, and an @@ -2926,38 +2927,46 @@ controls. `vc.api.has("scriptui")` is true. A script builds a modal dialog and s `orientation` (`row`, `column` or `stack`; a group starts as a row and the dialog and a panel as a column), `alignChildren`, `spacing` (10 to start), `margins` (15 to start, 0 for a group), `findElement(name)` and `remove(what)`, which removes the control given by its index, the control itself or its text. Removing an item - or a control that is not there does nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` + or a control that is not there does nothing. A removed control has no `parent` and its handlers no longer reach + the containers it was in; `add` and `remove` on it, or on a control it holds, throw an `Error`. When a `text` + getter changes the list or container while `remove(text)` looks for a match, `remove` throws an `Error` and + removes nothing. The dialog has `defaultElement`, `cancelElement`, `close([result])` and `hide()`. `center()`, `layout.layout()` and `layout.resize()` do nothing. - Radio buttons added one after another in a container form a set: setting one's `value` to true, or clicking it, sets the others in the set to false. A control of another kind between two radio buttons starts a new set, as the JavaScript Tools Guide describes radio buttons (https://raw.githubusercontent.com/Adobe-CEP/CEP-Resources/master/ExtendScript-Toolkit/Guides/JavaScript%20Tools%20Guide%20CC.pdf). -- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` act as the person's click or change would: - a click turns a check box over and turns a radio button on, then runs `onClick` and the `click` listeners. - `notify()` gives a click for a button, a check box and a radio button, and a change for the others. +- `notify("onClick")`, `notify("onChange")` and `notify("onChanging")` run the handlers that the person's click or + change would run: a click turns a check box over and turns a radio button on, then runs `onClick` and the + `click` listeners. `notify` does not close the dialog, even for the default or cancel button. `notify()` gives a + click for a button, a check box and a radio button, and a change for the others. - `addEventListener(type, handler[, capture])` registers a function for `click`, `change`, `changing` or `show`, and `removeEventListener` with the same arguments removes it; a function registered twice for the same type and - phase runs once. A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, - `detail` (1 for a click), `stopPropagation()` and `preventDefault()`. The containers above the control run their - `capture` handlers first, then the control runs its `onClick`, `onChange` or `onChanging` and its own handlers, - then the containers run their other handlers, from the nearest out, until a handler calls `stopPropagation()`; - `show` runs only on the dialog. The other documented event types (`focus`, `mouseover`, `keydown` and the rest) - throw that they are not available yet, and a handler that is not a function throws a `TypeError`. + phase runs once. `show` can be registered only on the dialog, and on a control it throws an `Error`. A window or + control takes at most 256 handlers, past which `addEventListener` throws a `RangeError` (VectorCraft's own + limit). A handler gets an event with `type`, `target`, `currentTarget`, `eventPhase`, `bubbles`, `cancelable` + (always false), `detail` (1 for a click), `stopPropagation()` and `preventDefault()`, which does nothing. The + containers above the control run their `capture` handlers first, then the control runs its `onClick`, + `onChange` or `onChanging` and its own handlers, then the containers run their other handlers, from the nearest + out, until a handler calls `stopPropagation()`. The other documented event types (`focus`, `mouseover`, + `keydown` and the rest) throw that they are not available yet, and a handler that is not a function throws a + `TypeError`. - `Window.alert`, `Window.confirm` and `Window.prompt` open the same dialogs as `alert`, `confirm` and `prompt`. `show()` opens the dialog, runs `onShow` and the `show` handlers, and waits for the person. A click runs the control's `onClick` and `click` handlers; a check box turns its value over first, and a radio button turns on and -the other radio buttons of its set off. An -edit field gives its text when it loses the keyboard focus, at Enter in a one-line field, or before a click on another -control, and a slider gives its -value when it is let go: each runs `onChanging` and then `onChange`. A list's new selection runs `onChange`. -Handlers run in the run's instructions, and a handler that does not end stops the run at its limit. `show()` -returns the number given to `close(result)` (0 when left out), 1 when the default button is clicked and 2 when the -cancel button is clicked, while they have no `onClick` and no `click` handler of their own, and 0 for the close box. `onClose` runs before the dialog -closes, and returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled -OK, and the cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside -a handler, or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in -function. A shown dialog can be shown again after it closes. +the other radio buttons of its set off. An edit field gives its text when it loses the keyboard focus, at Enter in +a one-line field, or before a click on another control, and a slider gives its value when it is let go: each runs +`onChanging` and then `onChange`. A list's new selection runs `onChange`. Handlers run in the run's instructions, +and a handler that does not end stops the run at its limit. `show()` returns the number given to `close(result)` +(0 when left out), 1 when the default button is clicked and 2 when the cancel button is clicked, and 0 for the +close box. The default or cancel button closes the dialog only when it has no `onClick` and no `click` handler of +its own and no `capture` handler on a container stopped the click; `click` handlers on the containers that do not +capture do not keep it from closing (VectorCraft's own rule). `onClose` runs before the dialog closes, and +returning `false` keeps it open. The default button is `defaultElement`, else a button named or titled OK, and the +cancel button is `cancelElement`, else a button named or titled Cancel, in any case. A `show()` inside a handler, +or of a dialog that is showing, throws an `Error`, and so does one inside a callback of a built-in function. A +shown dialog can be shown again after it closes. `show()` checks the dialog: at most 512 controls, nested at most 16 deep, 1,024 list items in all and 16 KiB of text a control, past which it throws a `RangeError`, a size or a place that is not a finite number, which throws